machine-learning - 梯度下降算法引发 valueError
问题描述
我有这些用于多元回归的梯度下降算法,但它提出了一个
ValueError: operands could not be broadcast together with shapes (3,) (3,140).
我在stackoverflow上查看了有关广播错误的其他答案,并且文档中说矩阵的维度必须相同或任何一个矩阵必须为1。但是我怎样才能使我的theta具有相同的维度。
请不要将其标记为重复。
我的 x 有暗淡 (140,3) , y 有 (140,1),alpha=0.0001
def find_mse(x,y,theta):
return np.sum(np.square(np.matmul(x,theta)-y))*1/len(x)
def gradientDescent(x,y,theta,alpha,iteration):
theta=np.zeros(x.shape[1])
m=len(x)
gradient_df=pd.DataFrame(columns=['coeffs','mse'])
for i in range(iteration):
gradient = (1/m) * np.matmul(x.T, np.matmul(x, theta) - y)
theta = np.mat(theta) - alpha * gradient
cost = compute_cost(X, y, theta)
gradient_df.loc[i] = [theta,cost]
return gradient_df
解决方案
您正在x
与 shape(140, 3)
相乘theta
以产生应该具有 shape 的输出(140, 1)
。要实现这一点,您theta
应该具有(3, 1)
. 您需要theta
按以下方式初始化
theta = np.zeros((x.shape[1], y.shape[1]))
推荐阅读
- php - 如何将序列化产品数据发送到 WooCommerce API 上的新产品创建?
- node.js - node.js 中的“无法获取 /messages/”
- sql - 如何在 oracle sql developer 中创建多个模式
- jquery - 脚本标签被 jquery 删除
- c - 从 C 中的函数访问二维字符数组时出错
- unity3d - Unity - 将 3D 对象与背景中的平面图片混合
- java - IntelliJ 上的图形显示
- javascript - 有没有办法从另一个页面更改 x-show 状态?
- html - 图标字体更改时平滑过渡
- google-sheets - 如何根据 6 位数项目编号列表检查共享谷歌驱动器上的文件名列表并自动选中一个框