Keras MeanSquaredError 计算每个样本的损失
Keras MeanSquaredError calculate loss per individual sample
我正在尝试获取张量中每个样本的 MeanSquaredError。
下面是一些示例代码来说明我的问题。
src = np.random.uniform(size=(2, 5, 10))
tgt = np.random.uniform(size=(2, 5, 10))
srcTF = tf.convert_to_tensor(src)
tgtTF = tf.convert_to_tensor(tgt)
print(srcTF, tgtTF)
lf = tf.keras.losses.MeanSquaredError(reduction=tf.compat.v1.losses.Reduction.NONE)
flowResults = lf(srcTF, tgtTF)
print(flowResults)
结果如下:
(2, 5, 10) (2, 5, 10)
(2, 5)
我想保留张量的所有原始维度,并只计算单个样本的损失。有没有办法在 Tensorflow 中做到这一点?
请注意,pytorch 的 torch.nn.MSELoss(reduction = 'none') 正是我想要的,那么有没有更像那样的替代方案?
这里有一个方法:
[ins] In [97]: mse = tf.keras.losses.MSE(tf.expand_dims(srcTF, axis=-1) , tf.expand_dims(tgtTF, axis=-1))
[ins] In [98]: mse.shape
Out[98]: TensorShape([2, 5, 10])
我认为这里的关键是示例。由于 MSE 是在最后一个轴上计算的,因此您会丢失该轴,因为它正在“减少”。该五维向量中的每个点代表最后一个轴中 10 个维度的均方误差。因此,为了恢复原始形状,本质上,我们必须对每个标量进行 MSE,为此我们需要扩展维度。本质上,我们是说 (2, 5, 10) 是我们拥有的批次数,每个标量是我们的 sample/prediction,这就是 tf.expand_dims(, -1) 完成的。
我正在尝试获取张量中每个样本的 MeanSquaredError。
下面是一些示例代码来说明我的问题。
src = np.random.uniform(size=(2, 5, 10))
tgt = np.random.uniform(size=(2, 5, 10))
srcTF = tf.convert_to_tensor(src)
tgtTF = tf.convert_to_tensor(tgt)
print(srcTF, tgtTF)
lf = tf.keras.losses.MeanSquaredError(reduction=tf.compat.v1.losses.Reduction.NONE)
flowResults = lf(srcTF, tgtTF)
print(flowResults)
结果如下:
(2, 5, 10) (2, 5, 10)
(2, 5)
我想保留张量的所有原始维度,并只计算单个样本的损失。有没有办法在 Tensorflow 中做到这一点? 请注意,pytorch 的 torch.nn.MSELoss(reduction = 'none') 正是我想要的,那么有没有更像那样的替代方案?
这里有一个方法:
[ins] In [97]: mse = tf.keras.losses.MSE(tf.expand_dims(srcTF, axis=-1) , tf.expand_dims(tgtTF, axis=-1))
[ins] In [98]: mse.shape
Out[98]: TensorShape([2, 5, 10])
我认为这里的关键是示例。由于 MSE 是在最后一个轴上计算的,因此您会丢失该轴,因为它正在“减少”。该五维向量中的每个点代表最后一个轴中 10 个维度的均方误差。因此,为了恢复原始形状,本质上,我们必须对每个标量进行 MSE,为此我们需要扩展维度。本质上,我们是说 (2, 5, 10) 是我们拥有的批次数,每个标量是我们的 sample/prediction,这就是 tf.expand_dims(