我有一个用于多元回归的梯度下降算法,但在运行时引发了以下错误:
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
回答:
您正在将形状为(140, 3)
的x
与theta
相乘,期望得到形状为(140, 1)
的输出。要实现这一点,您的theta
应该具有(3, 1)
的形状。您需要按照以下方式初始化theta
:
theta = np.zeros((x.shape[1], y.shape[1]))