首页 > 解决方案 > 有人可以解释为什么我的矩阵减法会弄乱索引吗?

问题描述

所以我正在研究波士顿住房数据集的回归模型,由于某种原因,当我尝试在我的梯度下降算法中减去两个 506x1 矩阵时(prediction_error = np.subtract(y,prediction_function) 它给了我一个 506x506 矩阵( prediction_error)。我之前做了两次相同的操作,没有发生任何错误。我尝试使用 np.subtract 而不是仅在 python 中使用常规减号,但没有任何改变。有人可以帮助我吗?

theta_grad = np.zeros((14,1))
print(theta_grad.shape) #debugging
prediction_function = X @ theta_grad 
print(prediction_function.shape) #debugging
prediction_error = np.subtract(y,prediction_function.reshape(y.shape))
print(prediction_error.shape) #debugging
gradient = X.T @ prediction_error

标签: pythonnumpymachine-learningstatisticslinear-regression

解决方案


你的数组y是形状(506,)的,另一个是形状的(506,1),python 一个接一个地广播。尝试将它们重新塑造成类似的形状,如下所示:

np.subtract(y,prediction_function.reshape(y.shape))

为了看效果,下面是一个示例代码,以便更好地理解:

A = np.arange(5) #shape (5,)
B = np.arange(5).reshape(5,1)  #shape (5,1)
np.subtract(A, B)

[[ 0  1  2  3  4]
 [-1  0  1  2  3]
 [-2 -1  0  1  2]
 [-3 -2 -1  0  1]
 [-4 -3 -2 -1  0]]   

np.subtract(A, B.reshape(A.shape))

[[0 0 0 0 0]]

推荐阅读