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

使用Sklearn LinearRegression的predict()时触发ValueError:特征数量不匹配

问题解决:LinearRegression特征数不匹配的ValueError

你的错误源于错误的reshape方向:

  • reshape(1,-1)会把数组转换成1行、列数自动计算的形状,这导致X_train变成了1个样本+2529个特征(训练集样本数为2529),X_test变成1个样本+844个特征(测试集样本数为844)。
  • 模型训练时学习的是2529维特征到目标的映射,预测时传入844维特征,自然出现维度不匹配的错误。

正确的做法是将特征数组转换成**(样本数, 1)**的形状(每个样本对应1个特征,这里payment是单特征),用reshape(-1,1)即可实现。

修正后的代码:

fp = Path('master_borrower.xlsx')

df = build_customer_df(fp)

df = df[['payment', 'trailer_sales_price']]
df = df[df['payment']!= 0]

X = df['payment'].values
y = df['trailer_sales_price'].values

# 分割数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1)

# 修正reshape:将数组转为(n_samples, 1)的标准特征矩阵格式
X_train = X_train.reshape(-1, 1)
X_test = X_test.reshape(-1, 1)
# 目标变量y可以保持一维数组,LinearRegression支持这种格式,无需reshape
# y_train = y_train.reshape(-1, 1)
# y_test = y_test.reshape(-1, 1)

model = linear_model.LinearRegression()
model.fit(X_train, y_train)

predictions = model.predict(X_test)

补充说明:

  • 单特征线性回归中,特征矩阵必须是二维结构,维度为(样本数量, 特征数量),这里特征数量是1,reshape(-1,1)会自动匹配样本数作为行数,固定列数为1。
  • 目标变量y无需强制转为二维,一维数组完全符合LinearRegression的输入要求,当然转成二维也能正常运行,不影响模型效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 07:00:57