Python Numpy 中的均方误差?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16774849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:38:17  来源:igfitidea点击:

Mean Squared Error in Numpy?

pythonarraysnumpymeanmean-square-error

提问by TheMeaningfulEngineer

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?

如果没有,你如何克服这个?您是自己编写还是使用不同的库?

采纳答案by Saullo G. P. Castro

You can use:

您可以使用:

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

Or

或者

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

回答by Charity Leschinski

This isn't part of numpy, but it will work with numpy.ndarrayobjects. A numpy.matrixcan be converted to a numpy.ndarrayand a numpy.ndarraycan be converted to a numpy.matrix.

这不是 的一部分numpy,但它适用于numpy.ndarray对象。Anumpy.matrix可以转换为 a numpy.ndarray,anumpy.ndarray可以转换为 a numpy.matrix

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

See Scikit Learn mean_squared_errorfor documentation on how to control axis.

有关如何控制轴的文档,请参阅Scikit Learn mean_squared_error

回答by nickandross

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: "Return the element-wise square of the input."

来自np.square的文档:“返回输入的元素平方。”

回答by Mark Swardstrom

Even more numpy

更麻木

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