我在 python 中实现梯度下降时卡住了。
梯度下降的公式为:
for iter in range(1, num_iters):
hypo_function = np.sum(np.dot(np.dot(theta.T, X)-y, X[:,iter]))
theta_0 = theta[0] - alpha * (1.0 / m) * hypo_function
theta_1 = theta[1] - alpha * (1.0 / m) * hypo_function
出现错误:
---> hypo_function = np.sum(np.dot(np.dot(theta.T, X)-y, X[:,iter])) ValueError: shapes (1,97) and (2,) not aligned: 97 (dim 1) != 2 (dim 0)
PS:这里我的X是(2L, 97L), y是(97L,) theta是(2L,)。
最佳答案
np.dot(a,b) 如果 a 和 b 是向量(一维数组),则取 a 和 b 的内积 如果 a 和 b 是二维数组,np .dot(a,b) 做矩阵乘法。
如果 a 的最后一个维度的大小与 b 的倒数第二个维度的大小不匹配,它将抛出 ValueError。它们必须匹配。
在您的情况下,您正在尝试将某个点积中的 97 数组乘以 2 数组,因此存在不匹配。因此,您需要修复输入数据,以便可以计算点积/矩阵乘法。
关于python - Python 中的梯度下降实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32792703/