简体   繁体   English

Numpy 中的均方误差?

[英]Mean Squared Error in Numpy?

Is there a method in numpy for calculating the Mean Squared Error between two matrices? numpy 中是否有计算两个矩阵之间的均方误差的方法?

I've tried searching but found none.我试过搜索,但没有找到。 Is it under a different name?它是在不同的名称下吗?

If there isn't, how do you overcome this?如果没有,你如何克服这个? Do you write it yourself or use a different lib?您是自己编写还是使用不同的库?

You can use:您可以使用:

mse = ((A - B)**2).mean(axis=ax)

Or或者

mse = (np.square(A - B)).mean(axis=ax)
  • with ax=0 the average is performed along the row, for each column, returning an array ax=0沿行执行平均值,对于每一列,返回一个数组
  • with ax=1 the average is performed along the column, for each row, returning an array ax=1沿列执行平均值,对于每一行,返回一个数组
  • with ax=None the average is performed element-wise along the array, returning a scalar value使用ax=None沿数组按元素执行平均值,返回标量值

This isn't part of numpy , but it will work with numpy.ndarray objects.这不是numpy一部分,但它适用于numpy.ndarray对象。 A numpy.matrix can be converted to a numpy.ndarray and a numpy.ndarray can be converted to a numpy.matrix . numpy.matrix可以转换为numpy.ndarraynumpy.ndarray可以转换为numpy.matrix

from sklearn.metrics import mean_squared_error
mse = mean_squared_error(A, B)

See Scikit Learn mean_squared_error for documentation on how to control axis.有关如何控制轴的文档,请参阅Scikit Learn mean_squared_error

更麻木

np.square(np.subtract(A, B)).mean()

Another alternative to the accepted answer that avoids any issues with matrix multiplication:已接受答案的另一种替代方法,可避免矩阵乘法的任何问题:

 def MSE(Y, YH):
     return np.square(Y - YH).mean()

From the documents for np.square :np.square文档中:

Return the element-wise square of the input.

只是为了踢

mse = (np.linalg.norm(A-B)**2)/len(A)

The standard numpy methods for calculation mean squared error (variance) and its square root (standard deviation) are numpy.var() and numpy.std() , see here andhere .计算均方误差(方差)及其平方根(标准偏差)的标准 numpy 方法是numpy.var()numpy.std() ,请参见此处此处 They apply to matrices and have the same syntax as numpy.mean() .它们适用于矩阵并具有与numpy.mean()相同的语法。

I suppose that the question and the preceding answers might have been posted before these functions became available.我想这个问题和前面的答案可能是在这些功能可用之前发布的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM