在Tensorflow中训练模型时,如何使用haversine函数作为损失函数?

在Tensorflow中训练模型时,如何使用haversine函数作为损失函数?,tensorflow,keras,loss-function,haversine,Tensorflow,Keras,Loss Function,Haversine,我想训练一个LSTM模型来预测海洋浮标的位置(纬度、经度)。我尝试使用haversine损失函数,但我不知道如何实现它 确切地说,我使用Keras,模型输出的形状是(批次大小,2) 当我训练模型时,我有以下错误: “运算符NOTALLOWEDINGRAPHORR:不允许在tf上迭代。不允许使用张量:AutoGraph未转换此函数。” 非常感谢 考虑到tensorflow的工作原理,我的解决方案是通过矩阵运算计算haversine距离。代码如下: import tensorflow as tf

我想训练一个LSTM模型来预测海洋浮标的位置(纬度、经度)。我尝试使用haversine损失函数,但我不知道如何实现它

确切地说,我使用Keras,模型输出的形状是(批次大小,2)

当我训练模型时,我有以下错误: “运算符NOTALLOWEDINGRAPHORR:不允许在
tf上迭代。不允许使用张量
:AutoGraph未转换此函数。”


非常感谢

考虑到tensorflow的工作原理,我的解决方案是通过矩阵运算计算haversine距离。代码如下:

import tensorflow as tf

RADIUS_KM = 6378.1

def degrees_to_radians(deg):
    pi_on_180 = 0.017453292519943295
    return deg * pi_on_180

def loss_haversine(observation, prediction):    
    obv_rad = tf.map_fn(degrees_to_radians, observation)
    prev_rad = tf.map_fn(degrees_to_radians, prediction)

    dlon_dlat = obv_rad - prev_rad 
    v = dlon_dlat / 2
    v = tf.sin(v)
    v = v**2

    a = v[:,1] + tf.cos(obv_rad[:,1]) * tf.cos(prev_rad[:,1]) * v[:,0] 

    c = tf.sqrt(a)
    c = 2* tf.math.asin(c)
    c = c*RADIUS_KM
    final = tf.reduce_sum(c)

    #if you're interested in having MAE with the haversine distance in KM
    #uncomment the following line
    #final = final/tf.dtypes.cast(tf.shape(observation)[0], dtype= tf.float32)

    return final
import tensorflow as tf

RADIUS_KM = 6378.1

def degrees_to_radians(deg):
    pi_on_180 = 0.017453292519943295
    return deg * pi_on_180

def loss_haversine(observation, prediction):    
    obv_rad = tf.map_fn(degrees_to_radians, observation)
    prev_rad = tf.map_fn(degrees_to_radians, prediction)

    dlon_dlat = obv_rad - prev_rad 
    v = dlon_dlat / 2
    v = tf.sin(v)
    v = v**2

    a = v[:,1] + tf.cos(obv_rad[:,1]) * tf.cos(prev_rad[:,1]) * v[:,0] 

    c = tf.sqrt(a)
    c = 2* tf.math.asin(c)
    c = c*RADIUS_KM
    final = tf.reduce_sum(c)

    #if you're interested in having MAE with the haversine distance in KM
    #uncomment the following line
    #final = final/tf.dtypes.cast(tf.shape(observation)[0], dtype= tf.float32)

    return final