【发布时间】:2021-11-28 08:51:45
【问题描述】:
我正在尝试预测由两个角度(theta 和 phi)给出的方向。我定义了一个损失函数,它是预测方向和真实方向之间的角距离,但在几个时期后我继续得到 nan 值。
鉴于输出激活是线性的,我的自定义损失是:
import tensorflow as tf
import numpy as np
import tensorflow.keras.backend as K
def square_angular_distance(y_true, y_pred):
the_pred = K.abs(y_pred[:, 0])
phi_pred = (y_pred[:, 1])%(2*np.pi)
the_true = y_true[:, 0]
phi_true = y_true[:, 1]
cos_phi_pred = K.cos(phi_pred)
cos_phi_true = K.cos(phi_true)
sin_phi_pred = K.sin(phi_pred)
sin_phi_true = K.sin(phi_true)
cos_the_pred = K.cos(the_pred)
cos_the_true = K.cos(the_true)
sin_the_pred = K.sin(the_pred)
sin_the_true = K.sin(the_true)
v_true = K.stack((sin_the_true*cos_phi_true, sin_the_true*sin_phi_true, cos_the_true), axis=1)
v_pred = K.stack((sin_the_pred*cos_phi_pred, sin_the_pred*sin_phi_pred, cos_the_pred), axis=1)
v_dot = K.batch_dot(v_true, v_pred)
angle_dist = tf.math.acos(K.clip(v_dot, -1., 1.))*180./np.pi
return K.mean(K.square(angle_dist), axis=-1)
其中 y_pred[:, 0] 和 y_pred[:, 1] 分别是酉向量的 theta 和 phi 角(y_true 相同)。
我尝试使用正则化器来裁剪梯度、学习率,并且我还检查了数据是否没有 Nan/Inf 值。
我还尝试使用输出层的自定义激活函数来裁剪输出值,但没有解决问题。
关于我做错了什么有什么建议吗?
【问题讨论】:
-
这是一个疯狂的想法:你尝试过不同的 TF 版本吗?可以说,解决此类问题已经不是第一次了。
-
还有一件事,你有没有试过把
tf.math.acos的输入剪短一点;即K.clip(v_dot, -.999, .999)以避免边缘情况。
标签: python tensorflow keras deep-learning neural-network