Tensorflow--MSE, mean squared error 表示方法

我们考虑两个3×3的数组,可以理解为两张3×3的图片,如下:

a = tf.constant([[4.0, 4.0, 4.0], [3.0, 3.0, 3.0], [1.0, 1.0, 1.0]])
b = tf.constant([[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [2.0, 2.0, 2.0]])
print(a)
print(b)
  
  
  • 1
  • 2
  • 3
  • 4

以上打印出来的结果如下:

Tensor("Const_16:0", shape=(3, 3), dtype=float32)
Tensor("Const_17:0", shape=(3, 3), dtype=float32)
  
  
  • 1
  • 2

而如果要得到具体的类似array形式的值,则需要用到sess.run:

with tf.Session() as sess:
    print(sess.run(a))
    print(sess.run(b))
  
  
  • 1
  • 2
  • 3

得到:

[[4. 4. 4.]
 [3. 3. 3.]
 [1. 1. 1.]]
[[1. 1. 1.]
 [1. 1. 1.]
 [2. 2. 2.]]
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

下面我们用三种方法来计算这两个数组的均方误差(MSE, mean squared error),具体公式为
MSE公式

1. tf.square()与tf.reduce_mean()组合

c = tf.square(a - b)
mse = tf.reduce_mean(c) 
with tf.Session() as sess:
    print(sess.run(c))
    print(sess.run(mse))
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
[[9. 9. 9.]
 [4. 4. 4.]
 [1. 1. 1.]]
4.6666665
  
  
  • 1
  • 2
  • 3
  • 4

上面就是c张量中的数组结果,mse结果为 4.6666665,手动计算c总和42,然后除以元素个数9,结果也是这个。
tf.square(a - b)就是在a数组减去b数组之后,对得到的数组所有元素逐个求平方。tf.reduce_mean(c),没有指定维度的话就是求所有元素的平均值。具体用法可以参考:https://blog.csdn.net/qq_32166627/article/details/52734387

2. tf.nn.l2_loss()

tf.nn.l2_loss(t)的具体计算为:sum(t ** 2) / 2,也就是说相当于2倍的tf.square(t)。那么用于计算mse的话用法如下:

mse1 = (2.0/9)*tf.nn.l2_loss(a - b)  #  sum(t ** 2) / 2
with tf.Session() as sess:
    print(sess.run(mse1))
  
  
  • 1
  • 2
  • 3

可以得到结果也是4.6666665。

3. tf.losses.mean_squared_error()

tf.losses.mean_squared_error()就是直接计算mse值了。

mse2 = tf.losses.mean_squared_error(a, b)
with tf.Session() as sess:
    print(sess.run(mse2))
  
  
  • 1
  • 2
  • 3

可以得到结果为4.6666665。

猜你喜欢

转载自blog.csdn.net/m0_37075274/article/details/89281490