我正在尝试从EuclideanLoss
中的Caffe
重现Tensorflow
。我找到了一个名为tf.nn.l2_loss
的函数,根据文档计算如下:
output = sum(t ** 2) / 2
在查看Python版本的caffe中的EuclideanLoss时,它说:
def forward(self, bottom, top):
self.diff[...] = bottom[0].data - bottom[1].data
top[0].data[...] = np.sum(self.diff**2) / bottom[0].num / 2.
在原始文件中说:
对我来说,这是完全相同的计算。但是,我在Tensorflow中对同一网络的损失值约为3000,而在Caffe中,它们的损失值大约为300.那么差异在哪里呢?答案 0 :(得分:1)
tf.nn.l2_loss
未考虑批量大小以计算损失。为了获得与caffe相同的值,您应该除以批量大小。为此,最简单的方法是使用均值(sum / n):
import tensorflow as tf
y_pred = tf.constant([1, 2, 3, 4], tf.float32)
y_real = tf.constant([1, 2, 4, 5], tf.float32)
mse_loss = tf.reduce_mean(tf.square(y_pred - y_real)) / 2.
sess = tf.InteractiveSession()
mse_loss.eval()