【问题标题】:Gradient Descent algorithm raises valueError梯度下降算法引发 valueError
【发布时间】:2019-06-24 20:08:29
【问题描述】:

我有这些用于多元回归的梯度下降算法,但它提出了一个

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   

【问题讨论】:

标签: machine-learning linear-regression gradient-descent


【解决方案1】:

您将x(140, 3)theta 相乘以产生应具有(140, 1) 形状的输出。为此,您的theta 的形状应为(3, 1)。你需要初始化theta如下

theta = np.zeros((x.shape[1], y.shape[1]))

【讨论】:

  • 幸运的是它解决了。但我没有找到问题所在,你能解释一下吗。我是该领域的新手。
  • 它遵循矩阵乘法的性质。要将 2 个矩阵 A 和 B 相乘,A 的列数必须与 B 中的行数相同。
猜你喜欢
  • 2016-06-13
  • 2021-01-21
  • 1970-01-01
  • 2014-01-11
  • 2017-07-17
  • 1970-01-01
  • 2017-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多