【发布时间】:2018-02-22 07:33:36
【问题描述】:
基本上,我希望我的自定义损失函数在通常的 MSE 和从不同索引中减去值的自定义 MSE 之间交替。
为了澄清,假设我有一个 y_pred 张量是 [1, 2, 4, 5] 和一个 y_true 张量是 [2, 5, 1, 3]。在通常的 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])
问题是我不能对 y_true 和 y_pred 张量使用 eval() 方法,不知道为什么。最后,我的问题是:
- 是否有更简单的方法来处理张量和损失函数内部的索引?总的来说,我是 Tensorflow 和 Keras 的新手,我坚信在 numpy 数组中转换所有内容根本不是最佳方法。
- 与问题不完全相关,但是当我尝试使用 K.shape(y_true) 打印 y_true 张量的形状时,我得到了“Tensor("Shape_1:0", shape=(2,), dtype=int32)"。这让我很困惑,因为我使用的 y.shape 等于 (7032, 6),即 7032 个图像,每个图像有 6 个标签。可能是与损失函数使用的我的 y 和 y_pred 相关的一些误解。
【问题讨论】:
标签: tensorflow neural-network keras