定义
在深度学习中,做回归任务时使用的loss多为均方差。公式为

其中:Batch为样本数量,M为网络输出层的元素的个数
实现
- loss = tf.nn.l2_loss(x, x') *2.0/ (Batch*M)
- loss = tf.losses.mean_squared_error(x, x')
- loss = tf.reduce_mean((x - x')**2)
- loss = tf.reduce_mean(tf.aquare(x - x')) (与上面的同意)
对于tf.nn.l2_loss(),数学表达式为 output = sum(t**2)/2
测试
认为a中有3个数据,计算a和b的均方差
import tensorflow as tf
a= [[1.0,2.0,3.0,5.0],[1.0,2.0,3.0,7.0],[1.0,2.0,3.0,2.0]]
b= [[2.0,4.0,3.0,7.0],[2.0,4.0,3.0,5.0],[2.0,4.0,3.0,5.0]]
c = tf.convert_to_tensor(a)
d = tf.convert_to_tensor(b)
loss1 = tf.nn.l2_loss(c-d) *2/(3*4)
loss2 = tf.reduce_mean((c-d)**2)
loss3 = tf.reduce_mean(tf.square(c-d))
loss4 = tf.losses.mean_squared_error(c,d)
with tf.Session() as sess:
print(sess.run(loss1)) # 2.6666667
print(sess.run(loss2)) # 2.6666667
print(sess.run(loss3)) # 2.6666667
print(sess.run(loss4)) # 2.6666667
上面四种表达结果是一样的

本文详细介绍了深度学习中回归任务常用的损失函数——均方误差(MSE),并通过TensorFlow展示了四种不同的实现方式,包括tf.nn.l2_loss、tf.reduce_mean、tf.square等,最后通过一个具体的测试案例验证了这些实现的一致性。
37万+

被折叠的 条评论
为什么被折叠?



