python - 有人可以解释为什么我的矩阵减法会弄乱索引吗?
问题描述
所以我正在研究波士顿住房数据集的回归模型,由于某种原因,当我尝试在我的梯度下降算法中减去两个 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
解决方案
你的数组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]]
推荐阅读
- c# - 如何使用 C# 使用记事本打开 .txt 文件
- javascript - 如何添加 HTML 附加 javascript...“引号”问题
- apache-spark - Spark EMR 作业失败:原因:org.apache.spark.memory.SparkOutOfMemoryError: Unable to acquire 16384 bytes of memory, got 0
- c# - 带有包含空格和“/”的字符串的 Http 请求
- react-native - 如何在 react-native 中使用加速度计传感器找到方向?
- r - R:使用 id 和记录频率创建新的数据框
- active-directory - 如何修复具有静态 IP 地址的域网络上的“未识别网络”?
- r - 使用参考列总结数据框
- java - JFLEX 是否有替代 \b 和/或负前瞻的方法?
- python - 使用 Discord.py 存储每个服务器的设置