我使用均方误差(MSE)来衡量损失。在下面的代码中,我实现了一个名为loss_mse的函数,该函数应计算给定theta的输入集的MSE。
def loss_mse(X,y,theta): length = len(y) predictions = X.dot(theta) error = (1/2*length) * np.sum(np.square(predictions - y)) return error
为了测试上述函数,我编写了以下测试用例:
X = np.array([[2.0, 1.0, 3.0], [3.0, 6.0, 2.0]])y = np.array([1.0, 1.0])theta = np.array([[1.0], [2.0],[1.0]])error = loss_mse(X, y, theta)print(error)
我应该得到答案73
,但我得到的是584
。我不明白我哪里做错了。
回答:
您是乘以length
而不是除以length
。
尝试
1/(2*length) * np.sum(np.square(predictions - y))
对于给定的输入,这将得到146
,您是否可能意指1/(4*length)
?