python - python中的操作数无法一起广播错误

标签 python machine-learning

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

#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 问题,但我无法弄清楚我的错误。请帮忙。

最佳答案

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

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 轴上广播 Y_train:

关于python - python中的操作数无法一起广播错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65631396/

相关文章:

machine-learning - 数据科学中的连续或分类数据

r - H2O的Auto ML功能如何平衡类别?

python - 在 Python 中动态地将父类(super class)添加到已知类

python - botocore.exceptions.ClientError : An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

python - 使用 pandas 从 csv 读取日期时间时出错

machine-learning - 实现超分辨率 CNN 时遇到问题

python - scikit-learn .predict() 默认阈值

machine-learning - 为什么训练 LSTM/RNN 模型时我的 GPU 比 CPU 慢?

python - 如何在 python selenium 中获取每个 window_handles 项目的标题

python - 如何从主窗口启动 TKinter 进度条