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

拟合多项式回归时出现Shapes not aligned形状不匹配错误如何解决

问题原因与解决方案

第一个报错的根因

你在训练模型时用了PolynomialFeatures对训练集做了升维处理,但预测时直接输入了原始维度的X_predict_input,模型接收的输入维度和训练时的要求不匹配:

  • 比如当degree=1时,PolynomialFeatures默认会生成截距项,转换后的训练集维度为(11, 2),但你传入的预测输入维度是(100, 1),矩阵运算时维度无法对齐,就触发了第一个报错。

第二个报错的根因

你尝试对X_train_poly做reshape((-1,1))的操作是完全错误的:

  • 以degree=1为例,原本(11,2)的训练集会被转换为(22, 1),样本数从11变成了22,和y_train的11个样本无法对应,自然会报样本数不一致的错误。

正确修改方法

你只需要在预测前,对X_predict_input做和训练集一致的多项式转换即可,不需要修改训练集的形状,另外注意提前初始化result数组避免未定义报错。

修正后的完整可运行代码如下:

import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

# 数据生成
np.random.seed(0)
n = 15
x = np.linspace(0,10,n) + np.random.randn(n)/5
y = np.sin(x)+x/6 + np.random.randn(n)/10

X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)

# 初始化参数
X_predict_input = np.linspace(0,10,100).reshape(-1,1)
y_train = y_train.reshape((-1,1))
X_train = X_train.reshape((-1,1))
# 提前初始化result数组,4个degree对应4行,100个预测点对应100列
result = np.zeros((4, 100))

# 遍历不同多项式阶数
for i, degree in enumerate([1,3,6,9]):
    poly = PolynomialFeatures(degree=degree)
    X_train_poly = poly.fit_transform(X_train)
    linreg = LinearRegression().fit(X_train_poly, y_train)
    # 对预测输入做相同的多项式转换,不需要重新fit
    X_predict_poly = poly.transform(X_predict_input)
    result[i,:] = linreg.predict(X_predict_poly).flatten()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:45:08