【问题标题】:Can someone explain why my matrix subtraction is messing up the index?有人可以解释为什么我的矩阵减法会弄乱索引吗?
【发布时间】:2020-08-21 21:06:33
【问题描述】:

所以我正在研究波士顿住房数据集的回归模型,由于某种原因,当我尝试在我的梯度下降算法中减去两个 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

【问题讨论】:

  • 请将您的代码添加为文本输出。 Stack Overflow 上不接受文本屏幕截图。
  • 欢迎来到 SO;请重新阅读How to ask,因为您第一次阅读时似乎错过了一些关键点,例如“请勿发布代码、数据、错误消息等的图像。”(强调原文)。

标签: python numpy machine-learning statistics linear-regression


【解决方案1】:

您的数组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]]

【讨论】:

    猜你喜欢
    • 2022-08-20
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多