【问题标题】:operands could not be broadcast together error in pythonpython中的操作数无法一起广播错误
【发布时间】:2021-04-14 07:15:27
【问题描述】:

我正在尝试手动编写多元线性回归代码,为此我编写了这个逻辑,

#building the model

#lets start with a random value of m and c

import numpy as np
n_samples,n_features=X_train.shape

weight=np.zeros(n_features)
bias=0

lr=0.0001 #l is the learning rate

mse=[]

for i in range (0,20000):
    Y_pred=np.dot(X_train,weight)+bias
    mse.append(np.sum((Y_pred-Y_train)**2)/n_samples)
    
     # compute gradients
    dw = (1 / n_samples) * np.dot(X_train.T, (Y_pred - Y_train))
    db = (1 / n_samples) * np.sum(Y_pred - Y_train)
    
    # update parameters
    weight -= lr * dw
    bias -= lr * db
    
plt.plot(mse)

但我不知道为什么会出现以下错误

> ValueError                                Traceback (most recent call
> last) <ipython-input-17-6302f8353768> in <module>
>      22 
>      23     # update parameters
> ---> 24     weight -= lr * dw
>      25     bias -= lr * db
>      26 
> 
> ValueError: operands could not be broadcast together with shapes (6,)
> (6,40) (6,)

请帮忙,因为我是 python 新手,我无法找出我哪里出错了。任何帮助都会非常有帮助。我已经看到this stackoverflow 问题,但我无法弄清楚我的错误。请帮忙。

【问题讨论】:

  • 使用虚拟输入,我的工作正常。 X_trainY_train的形状是什么?
  • (40,6) for xtrain 和 (40,1) for y_train using jupyter notebook

标签: python machine-learning


【解决方案1】:

将您的权重初始化更改为:

weight = np.zeros((n_features, 1))

说明: 像您所做的那样初始化权重将创建一个形状为(n_features,) 的数组,在数学运算中它被视为(1, n_features)(并在此答案中从这里开始处理)。然后,在前馈之后,你会得到形状为(1, n_samples)Y_pred 而不是(n_samples, 1)。这导致Y_pred - Y_train 的形状为(n_samples, n_samples) 而不是(n_samples, 1)

广播在 NumPy 中的工作方式是首先尝试匹配维度,如果其中任何一个匹配,则它们是好的。然后,对于不匹配的维度,如果其中一个为 1,则将其广播为另一个数组的维度的形状。在您的示例中,在减法期间,Y_pred 在 x 轴上广播,Y_train 在 y 轴上广播:

【讨论】:

    猜你喜欢
    • 2022-09-24
    • 2016-12-26
    • 2019-09-01
    • 1970-01-01
    • 2020-09-06
    • 2012-10-31
    • 2013-04-07
    • 2014-08-24
    • 2018-02-01
    相关资源
    最近更新 更多