要计算均方误差,我一直在使用tf.reduce_mean(tf.square())
。最近在Tensorflow API页面上,我发现它有一个API,tf.losses.mean_squared_error()
。
我比较了这两种方法,我发现它们给出的结果略有不同。更具体地说,tf.reduce_mean(tf.square())
给出与NumPy结果完全相同的结果,但tf.losses.mean_squared_error()
给出的结果略有不同。以下是验证它的简单代码。
#!/usr/bin/python
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
def GenerateData(num_size):
x = np.linspace(0, 10, num_size)
y = 0.7 * x + 0.4
y_hat = y + np.random.normal(0.0, 2.0, num_size)
return (y, y_hat)
def main():
(y, y_hat) = GenerateData(100)
a = tf.Variable(y)
b = tf.Variable(y_hat)
mse0 = tf.reduce_mean(tf.square(a - b))
mse1 = tf.losses.mean_squared_error(a, b)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
value0 = (sess.run(mse0))
value1 = (sess.run(mse1))
print "MSE calculation using NumPy: ", (np.mean((y - y_hat) ** 2))
print "MSE calculation using tf.reduce_mean(tf.square): ", value0
print "MSE calculation using tf.losses.mean_squared_error: ", value1
print "The value difference: ", (value0 - value1)
if __name__ == "__main__":
main()
以下是执行结果。
MSE calculation using NumPy: 3.45982961943
MSE calculation using tf.reduce_mean(tf.square): 3.45982961943
MSE calculation using tf.losses.mean_squared_error: 3.4598296
The value difference: 5.0563521814e-08
有谁可以告诉我为什么tf.losses.mean_squared_error()
给出的结果略有不同?要计算MSE,是否建议在tf.reduce_mean(tf.square())
上使用此API?