基本上,我希望我的自定义损失函数在通常的 MSE 和从不同索引中减去值的自定义 MSE 之间交替。
为了澄清起见,假设我有一个 [1, 2, 4, 5] 的 y_pred 张量和一个 [2, 5, 1, 3] 的 y_true 张量。在通常的 MSE 中,我们应该得到:
return K.mean(K.squared(y_pred - y_true))
这将执行以下操作:
[1, 2, 4, 5] - [2, 5, 1, 3] = [-1, -3, 3, 2]
[-1, -3, 3, 2]² = [1, 9, 9, 4]
平均值([1, 9, 9, 4]) = 5.75
我需要我的自定义损失函数来选择这个平均值和其他从 y_pred 张量切换索引 1 和 3 之间的最小值,即:
[1, 5, 4, 2] - [2, 5, 1, 3] = [-1, 0, 3, 1]
[-1, 0, 3, 1]² = [1, 0, 9, 1]
平均值([1, 0, 9, 1]) = 2.75
因此,我的自定义损失将返回 2.75,这是两种均值之间的最小值。为此,我尝试在 numpy 数组中转换 y_true 和 y_pred 张量,执行以下所有相关数学运算:
def new_mse(y_true, y_pred):
sess = tf.Session()
with sess.as_default():
np_y_true = y_true.eval()
np_y_pred = y_pred.eval()
np_err_mse = np.empty(np_y_true.shape)
np_err_mse = np.square(np_y_pred - np_y_true)
np_err_new_mse = np.empty(np_y_true.shape)
l0 = np.square(np_y_pred[:, 2] - np_y_true[:, 0])
l1 = np.square(np_y_pred[:, 3] - np_y_true[:, 1])
l2 = np.square(np_y_pred[:, 0] - np_y_true[:, 2])
l3 = np.square(np_y_pred[:, 1] - np_y_true[:, 3])
l4 = np.square(np_y_pred[:, 4] - np_y_true[:, 4])
l5 = np.square(np_y_pred[:, 5] - np_y_true[:, 5])
np_err_new_mse = np.transpose(np.vstack(l0, l1, l2, l3, l4, l5))
np_err_mse = np.mean(np_err_mse)
np_err_new_mse = np.mean(np_err_new_mse)
return np.amin([np_err_mse, np_err_new_mse])
问题是我不能将 eval() 方法与 y_true 和 y_pred 张量一起使用,不知道为什么。最后,我的问题是:
最佳答案
通常您只与 backend functions 一起工作,并且您永远不会尝试知道张量的实际值。
from keras.losses import mean_square_error
def new_mse(y_true,y_pred):
#swapping elements 1 and 3 - concatenate slices of the original tensor
swapped = K.concatenate([y_pred[:1],y_pred[3:],y_pred[2:3],y_pred[1:2]])
#actually, if the tensors are shaped like (batchSize,4), use this:
#swapped = K.concatenate([y_pred[:,:1],y_pred[:,3:],y_pred[:,2:3],Y_pred[:,1:2])
#losses
regularLoss = mean_squared_error(y_true,y_pred)
swappedLoss = mean_squared_error(y_true,swapped)
#concat them for taking a min value
concat = K.concatenate([regularLoss,swappedLoss])
#take the minimum
return K.min(concat)
因此,对于您的元素:
K.shape()
也是张量。它可能具有形状 (2,),因为它有两个值,一个值为 7032,另一个值为 6。但是您只能在评估此张量时看到这些值。在损失函数中这样做通常是个坏主意。 关于tensorflow - 自定义损失函数中的张量索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46200080/