我正在尝试手动编写多元线性回归代码,为此我编写了这个逻辑,
#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/