python - TensorFlow 均方误差计算与 sklearn 不同
问题描述
我正在尝试mse
使用 tensorflow 进行计算并将结果与sklearn.metrics.mean_squared_error
方法进行比较。
def mse(y,y_hat):
return tf.reduce_mean(tf.squared_difference(y, y_hat)).eval()
compute_mse = lambda vector1, vector2: mse(vector1,vector2)
我的测试循环
for n in [1,5,10,10**3]:
elems = [np.arange(n),np.arange(n,0,-1), np.zeros(n),
np.ones(n),np.random.random(n),np.random.randint(100,size=n)]
for el in elems:
for el_2 in elems:
true_mse = np.array(mean_squared_error(el,el_2))
my_mse = compute_mse(el,el_2)
if not np.allclose(true_mse,my_mse):
print('Wrong result:')
print("All tests passed")
但是我的 tf 函数总是返回 0 或 1。你能指出我错在哪里吗?
UPD
感谢@apnorton 指出类型问题。
def mse(y,y_hat):
y_ = tf.Variable(y, tf.float64)
y_hat_ = tf.Variable(y_hat, tf.float64)
return tf.reduce_mean(tf.squared_difference(y_, y_hat_).eval()
解决方案
如果您打印 tf 函数的所有输出,您会看到它不仅返回 1 和 0,而且只返回整数。这是因为 的值elems
都是 type numpy.int32
。在执行平均步骤时,该sklearn
函数似乎将这些转换为浮点数,而张量流方法则没有。
要查看固定变体,请考虑将compute_mse
行更改为:
my_mse = compute_mse(el.astype(float),el_2.astype(float))
编辑:针对评论中的问题,我会避免仅出于演员表的目的创建变量。相反,我建议使用以下tf.to_float
方法:
def mse(y,y_hat):
return tf.reduce_mean(tf.squared_difference(tf.to_float(y), tf.to_float(y_hat))).eval()