Python Numpy平方计算的意思(这是正确的方法)

时间:2017-04-30 09:53:50

标签: python numpy neural-network mse

在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)

1 个答案:

答案 0 :(得分:1)

在numpy中计算MSE非常简单:

mse = ((predictedMatrix - actualMatrix) ** 2).mean(axis=_axis)

_axis = 0 =>行计算以获得向量。

_axis = 1 =>逐列计算得到一个向量。

_axis = None =>元素计算得到一个数字。