python - Python 中的梯度下降实现

标签 python linear-regression gradient-descent

我在 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/

相关文章:

python - 从 django 自定义命令请求输入?

python - Google 自定义设备操作在 Raspberry Pi Google Assistant 上出现错误

machine-learning - 点击收入预测模型

python - 多臂老虎机练习的反直觉结果

r - R 函数 nlminb() 使用的函数

python - 解压 map() 参数的嵌套列表

python - 使用 pd.to_datetime 将 int 转换为 HHMMSS 格式

matlab - 牛顿梯度下降线性回归

r - 使用 R 从较大的方程创建特定的线性回归方程

matlab - 梯度下降和闭合形式解 - MATLAB 中的不同假设线