You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

线性回归代码报错:输出操作数形状与广播形状不匹配求助

解决线性回归代码中的形状不匹配报错

问题根源

报错ValueError: non-broadcastable output operand with shape (1,) doesn't match the broadcast shape (1,15)的核心是数组形状不兼容:

  • 初始化的weights是一维数组(1,),而权重更新时计算出的weights_delta是二维数组(1,15)(形状由数据行数决定),两者无法进行广播运算,导致减法赋值失败。
  • 触发点是y被处理成二维数组(m,1),而y_pred是一维数组(m,),两者相减后触发numpy广播,得到二维数组,最终导致weights_delta与weights形状不匹配。

解决方案

方案1:统一使用一维数组处理标签

修改数据准备步骤中y的形状,让它和y_pred保持一致的一维结构:

  • 将y = data['Weight'].values.reshape(-1, 1)改为y = data['Weight'].values,去掉reshape操作,让y保持一维数组(m,)。
  • 注意原学习率0.01过大,会导致权重发散,建议调整为0.0001或更小。

方案2:统一使用二维数组处理权重

如果需要保留y的二维结构,就把weights也初始化为二维数组:

  • 在linearRegression_train函数中,将weights = np.zeros(X.shape[1])改为weights = np.zeros((X.shape[1], 1)),让weights成为二维数组(1,1)。
  • 这样所有运算的数组形状都会匹配,避免广播冲突。

完整修正代码(方案1)

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# 加载数据集
data = pd.read_csv('heights_weights.csv')

# 绘制数据分布
plt.scatter(data['Height'], data['Weight'], color='b')
plt.xlabel('Height')
plt.ylabel('Weight')
plt.title('Height vs. Weight')
plt.show()

# 定义线性回归模型
def linearRegression_model(X, weights):
    y_pred = np.dot(X, weights)
    return y_pred

# 定义权重更新函数
def linearRegression_update_weights(X, y, weights, learning_rate):
    y_pred = linearRegression_model(X, weights)
    weights_delta = np.dot(X.T, y_pred - y)
    m = len(y)
    weights -= (learning_rate/m) * weights_delta
    return weights

# 定义训练函数
def linearRegression_train(X, y, learning_rate, num_epochs):
    # 初始化权重
    weights = np.zeros(X.shape[1])
    for epoch in range(num_epochs):
        weights = linearRegression_update_weights(X, y, weights, learning_rate)
        if (epoch % 100 == 0):
            print('epoch: %s, weights: %s' % (epoch, weights))
    return weights

# 定义预测函数
def linearRegression_predict(X, weights):
    y_pred = linearRegression_model(X, weights)
    return y_pred

# 定义均方误差函数
def mean_squared_error(y_true, y_pred):
    mse = np.mean(np.power(y_true-y_pred, 2))
    return mse

# 数据预处理
X = data['Height'].values.reshape(-1, 1)
y = data['Weight'].values  # 修改:使用一维数组存储标签

# 训练模型
lr = 0.0001  # 调整学习率避免权重发散
n_epochs = 1000
weights = linearRegression_train(X, y, lr, n_epochs)

# 预测
y_pred = linearRegression_predict(X, weights)

# 评估模型
mse = mean_squared_error(y, y_pred)
print('Mean Squared Error: %s' % mse)

# 绘制回归直线
plt.scatter(data['Height'], data['Weight'], color='b')
plt.plot(X, y_pred, color='k')
plt.xlabel('Height')
plt.ylabel('Weight')
plt.title('Height vs. Weight')
plt.show()

# 绘制真实值与预测值对比
plt.scatter(data['Height'], y, color='b', label='Actual')
plt.scatter(data['Height'], y_pred, color='r', label='Predicted')
plt.xlabel('Height')
plt.ylabel('Weight')
plt.title('Actual vs. Predicted')
plt.legend()
plt.show()

内容的提问来源于stack exchange,提问作者Melad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 17:20:27