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

如何解决‘X有1个特征,但LinearRegression期望输入3个特征’的报错?

解决多项式回归中特征数不匹配的报错问题

错误原因

训练阶段你用PolynomialFeatures(degree=2)把X_train转换成了包含常数项、x、x²的3维特征,但预测时直接传入了仅做reshape的X_test(还是1维特征),模型期望输入3个特征,自然会报错。

修正后的代码

from sklearn import linear_model
from sklearn.metrics import mean_squared_error
from math import sqrt
import matplotlib.pyplot as plt
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import train_test_split

def f(x):
    return np.sin(2*np.pi*x) + np.random.normal(scale=0.1, size=len(x))

NUM_SAMPLES=15
x = np.random.uniform(0,1,NUM_SAMPLES)
y = f(x)
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.33)
plt.plot(x,y,'bo')
plt.show()

poly = PolynomialFeatures(degree=2)
# 对训练集做多项式特征转换
X_train = poly.fit_transform(np.array(X_train).reshape(-1, 1))

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

# 关键修改:用同一个poly实例对测试集做特征转换,而不是仅reshape
X_test_poly = poly.transform(np.array(X_test).reshape(-1, 1))
y_pred = regr.predict(X_test_poly)

# 输出系数
print('Coefficients: \n', regr.coef_)
rmse = sqrt(mean_squared_error(y_test, y_pred))
# 输出均方根误差
print('Root mean squared error: %.2f' % rmse)

核心修改点

  • 必须复用训练时初始化的poly对象对测试集做transform操作,确保测试集的特征维度和训练集完全一致
  • 永远不要在预测时跳过特征预处理步骤,预处理逻辑要在训练和预测阶段保持统一

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 01:07:40