不太擅长 python 和 numpy,但正在研究机器学习代码的均方误差。
想做一个Python子程序,根据test_data返回均方误差,结果如下。
现在答案很好(不要引用,因为 x 和 y 已经是一个矩阵)
for (x, y) in test_data:
predictedMatrix = self.feedforward(x)
actualMatrix = y
results = ((predictedMatrix - actualMatrix) ** 2).mean()
return(results)
*原来的问题是*
我的代码看起来不像 python 代码,事实上整个练习看起来不像其他人在机器学习上的 numpy 代码。它有效,但效果不好。感谢您提供的建议。
import numpy as np
test_data = [(np.array([[ 0. ], [ 0. ]]), np.array([[ 0.],[ 1.]])), # this is index not actually 1
(np.array([[ 0. ], [ 1. ]]), np.array([[ 1.],[ 0.]])),
(np.array([[ 1. ], [ 0. ]]), np.array([[ 1.],[ 0.]])),
(np.array([[ 1. ], [ 1. ]]), np.array([[ 0.],[ 1.]]))]
#import numpy as np
training_data = [ (np.array([[ 0. ], [ 0. ]]), np.array([[ 0.],[ 1.]])),
(np.array([[ 0. ], [ 1. ]]), np.array([[ 1.],[ 0.]])),
(np.array([[ 1. ], [ 0. ]]), np.array([[ 1.],[ 0.]])),
(np.array([[ 1. ], [ 1. ]]), np.array([[ 0.],[ 1.]]))]
#import numpy as np
validation_data = [(np.array([[ 0. ],[ 0. ]]), np.array([[ 0.],[ 1.]])), # this is index not actually 1
(np.array([[ 0. ],[ 1. ]]), np.array([[ 1.],[ 0.]])),
(np.array([[ 1. ],[ 0. ]]), np.array([[ 1.],[ 0.]])),
(np.array([[ 1. ],[ 1. ]]), np.array([[ 0.],[ 1.]]))]
# We should do self.feedforward(x) but for here just
self_forward_x = np.array([[ 0.],[ 1.]])
test_results = [self_forward_x - y
for (x, y) in test_data]
print "test_results : {0}".format(test_results)
#test_results : [array([[ 0.],[ 0.]]),
# array([[-1.],[ 1.]]),
# array([[-1.],[ 1.]]),
# array([[ 0.],[ 0.]])]
# how to do sum of mean square error to check the progress of the epochs
# i.e. how to get mse which I think is
# (0**2 + 0**2)/2 + (-1**2 + 1**2)/2 + (-1**2 + 1**2)/2 + (0**2 + 0**2)/2 not / 4 as we have 4 cases ? should I divided by 4 ... confused.
sumarray = 0
i = 0
for arrays in test_results:
for arrayi in arrays:
#print "arrayi : {0}".format(arrayi)
#print "sum(arrayi) : {0}".format(sum(arrayi))
sumarray = sumarray + np.sum(arrayi**2)
i = i + 1
return (sumarray / i)
# print "i, sumarray : {0}, {1}".format(i, sumarray)
最佳答案
在 numpy 中计算 MSE 非常简单:
mse = ((predictedMatrix - actualMatrix) ** 2).mean(axis=_axis)
_axis = 0 => 逐行计算以获得向量。
_axis = 1 => 逐列计算以获得向量。
_axis = None => 逐元素计算以获得单个数字。
关于Python Numpy 平方均值计算(这是正确的方法吗),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43705121/