多项式回归
核对多项式特征扩展、阶数欠拟合/过拟合权衡与高次项条件数缩放,以无泄露 Pipeline 5 折交叉验证选阶,并实测二元交叉项与糖尿病单特征练习。
学完这一章,你能够
- 核对多项式特征扩展、阶数欠拟合/过拟合权衡与高次项条件数缩放,以无泄露 Pipeline 5 折交叉验证选阶,并实测二元交叉项与糖尿病单特征练习。
从线性到曲线:多项式特征扩展与核心术语
当物理轨迹或业务趋势呈现弯曲非线性关系时,普通直线模型 y = w₁*x + b(仅由斜率 w₁ 与截距 b 决定)难以拟合。多项式回归通过将原始特征的高次幂(如 x²、x³)构造为新列,在扩展特征空间上继续应用线性回归(如二次模型 y = w₁*x + w₂*x² + b 可视为关于 X1=x、X2=x² 的线性组合),从而以线性求解机制拟合平滑曲线。
核心术语包含三项:阶数/次数(degree)决定多项式最高指数(2 阶为抛物线、3 阶为三次曲线);欠拟合指阶数过低导致模型无法捕捉弯曲趋势;过拟合指阶数过高导致曲线剧烈震荡穿过训练噪声点而在新样本上误差飙升。来源流程示意总结了从探索散点、扩展特征到用验证集定阶的决策路径。
PolynomialFeatures 实战与阶数偏差-方差权衡
使用 sklearn.preprocessing.PolynomialFeatures(degree=2, include_bias=False) 可自动把单特征列转换为 [x, x²] 两列矩阵再交由 LinearRegression 拟合。本站在 160 条模拟抛物线数据(y = 0.5x² + 0.6x + 2 + 噪声,先按 75/25 拆分 120 训练/40 测试)实测:仅在训练集 fit_transform 得到 (120, 2) 特征矩阵,还原参数 w₁ = 0.6569、w₂ = 0.5116、b = 2.0110,留出测试 R² 由一次线性回归的 0.2607 大幅提升至 0.8681(测试 MSE = 0.3323)。
在高阶拟合实测中需特别关注数值条件数:未缩放的 x¹⁵ 在 [-3, 3] 区间量级超过 1.4×10⁷,易使普通最小二乘出现病态失真;在 PolynomialFeatures 后串联 StandardScaler 再接 LinearRegression 后,本站于 45 条训练子集与 40 条留出测试集测得清晰偏差-方差曲线:Degree=1 明显欠拟合(训练 MSE = 1.7719、测试 MSE = 1.7670、测试 R² = 0.2986);Degree=2 泛化最优(训练 MSE = 0.2761、测试 MSE = 0.2972、测试 R² = 0.8820);Degree=15 严重过拟合(训练 MSE 压低至 0.2026、训练 R² = 0.9172,但留出测试 MSE 恶化逾倍至 0.6460、测试 R² 跌至 0.7436)。
无泄露管道交叉验证选阶与多元/真实数据练习
选择最佳阶数应避免把特征转换放在交叉验证外或直接用测试集调参。本站将 PolynomialFeatures、StandardScaler 与 LinearRegression 封装入 Pipeline,仅在 120 条训练集上执行 5 折 cross_val_score(scoring='neg_mean_squared_error') 扫描 1~10 阶:实测 1 阶 CV MSE = 1.8637、2 阶达到最低 0.3123、3 阶升至 0.3257、10 阶为 0.3350,准确选中 degree = 2 并在独立留出测试集取得 MSE = 0.3323。
三项实践练习均已完成离线核验:(1)练习 1 的 5 点近似平方数据用 degree=1 拟合时 R² = 0.9481,改为 degree=2 后 R² 立即升至 0.9997;(2)练习 2 注意 scikit-learn 自 1.2 起已因伦理原因移除波士顿房价数据集(load_boston),本站改用内置 load_diabetes 的 bmi 特征做训练集 5 折 CV,测得 1~4 阶 CV MSE 依次为 4028.19、4054.55、4075.54、4067.64,表明该单特征呈近似线性趋势(最佳阶数 1),说明并非所有真实数据都需要高次项;(3)练习 3 对二元输入 (x1, x2) 应用 PolynomialFeatures(degree=2, include_bias=False),输出确切 5 列 ['x1', 'x2', 'x1^2', 'x1 x2', 'x2^2'](含交互项),拟合 y = x1 + x2² + 0.5*x1*x2 + 噪声 在留出测试集达到 R² = 0.9755。
运行多项式特征扩展、高阶过拟合与无泄露 Pipeline 交叉验证选阶实验
展开查看收起
"""Independent scikit-learn 1.9.1 lab for Polynomial Regression, Bias-Variance Tradeoff & Pipeline CV."""
import json
import platform
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
def run_cases():
cases = []
# 1. Quadratic polynomial feature expansion and parameter recovery on held-out test split
rng = np.random.default_rng(42)
x_all = 6.0 * rng.random((160, 1)) - 3.0
y_all = 0.5 * (x_all[:, 0] ** 2) + 0.6 * x_all[:, 0] + 2.0 + rng.normal(0.0, 0.55, size=160)
x_tr, x_te, y_tr, y_te = train_test_split(x_all, y_all, test_size=0.25, random_state=42)
poly2 = PolynomialFeatures(degree=2, include_bias=False)
x_tr_p2 = poly2.fit_transform(x_tr)
x_te_p2 = poly2.transform(x_te)
lr2 = LinearRegression().fit(x_tr_p2, y_tr)
r2_deg2 = float(r2_score(y_te, lr2.predict(x_te_p2)))
mse_deg2 = float(mean_squared_error(y_te, lr2.predict(x_te_p2)))
lr1 = LinearRegression().fit(x_tr, y_tr)
r2_deg1 = float(r2_score(y_te, lr1.predict(x_te)))
c1_ok = x_tr_p2.shape == (120, 2) and r2_deg2 > 0.85 and r2_deg2 > r2_deg1 + 0.45
cases.append(dict(
name="quadratic_poly_features_and_fit",
inputs=dict(n_train=120, n_test=40, true_formula="0.5*x^2 + 0.6*x + 2 + noise"),
prerequisites="按 75/25 划分模拟抛物线数据,仅在训练集上 fit PolynomialFeatures(degree=2, include_bias=False)。",
action="验证特征维度由 (120,1) 升至 (120,2)、还原近似系数 [0.6, 0.5] 与截距 2.0,且测试 R² 远超一次线性回归。",
expected=dict(poly_shape_120_2=True, deg2_beats_deg1=True),
actual=dict(poly_shape_120_2=(x_tr_p2.shape == (120, 2)), deg2_beats_deg1=(r2_deg2 > 0.85 and r2_deg2 > r2_deg1 + 0.45)),
measurements=dict(
w1_est=round(float(lr2.coef_[0]), 4),
w2_est=round(float(lr2.coef_[1]), 4),
b_est=round(float(lr2.intercept_), 4),
deg1_test_r2=round(r2_deg1, 4),
deg2_test_r2=round(r2_deg2, 4),
deg2_test_mse=round(mse_deg2, 4),
),
passed=c1_ok,
))
# 2. Bias-Variance tradeoff with StandardScaler stabilizing high-degree Vandermonde terms (1, 2, 15)
# Use a smaller 45-sample subset for crisp degree=15 overfitting contrast on held-out data
x_ov_tr, y_ov_tr = x_tr[:45], y_tr[:45]
deg_metrics = {}
for deg in (1, 2, 15):
pipe = make_pipeline(
PolynomialFeatures(degree=deg, include_bias=False),
StandardScaler(),
LinearRegression(),
)
pipe.fit(x_ov_tr, y_ov_tr)
deg_metrics[deg] = dict(
train_mse=round(float(mean_squared_error(y_ov_tr, pipe.predict(x_ov_tr))), 4),
test_mse=round(float(mean_squared_error(y_te, pipe.predict(x_te))), 4),
train_r2=round(float(r2_score(y_ov_tr, pipe.predict(x_ov_tr))), 4),
test_r2=round(float(r2_score(y_te, pipe.predict(x_te))), 4),
)
underfit_ok = deg_metrics[1]["train_mse"] > deg_metrics[2]["train_mse"] * 3.0
overfit_ok = (
deg_metrics[15]["train_mse"] < deg_metrics[2]["train_mse"]
and deg_metrics[15]["test_mse"] > deg_metrics[2]["test_mse"] * 1.5
)
c2_ok = underfit_ok and overfit_ok
cases.append(dict(
name="degree_bias_variance_tradeoff",
inputs=dict(degrees=[1, 2, 15], n_train_subset=45, n_test=40),
prerequisites="在多项式特征后串联 StandardScaler 稳定高次项条件数,对比 1 阶、2 阶、15 阶的训练与留出误差。",
action="验证 1 阶欠拟合(训练与测试 MSE 均高)、15 阶过拟合(训练 MSE 低于 2 阶但留出测试 MSE 明显恶化),2 阶泛化最优。",
expected=dict(deg1_underfits=True, deg15_overfits=True),
actual=dict(deg1_underfits=underfit_ok, deg15_overfits=overfit_ok),
measurements=deg_metrics,
passed=c2_ok,
))
# 3. Leakage-free Pipeline 5-fold CV on train set + Exercise 1 diagnosis repair
cv_mses = {}
for deg in range(1, 11):
pipe = make_pipeline(
PolynomialFeatures(degree=deg, include_bias=False),
StandardScaler(),
LinearRegression(),
)
scores = cross_val_score(pipe, x_tr, y_tr, cv=5, scoring="neg_mean_squared_error")
cv_mses[deg] = round(float(-scores.mean()), 4)
best_deg = min(cv_mses, key=cv_mses.get)
best_pipe = make_pipeline(
PolynomialFeatures(degree=best_deg, include_bias=False),
StandardScaler(),
LinearRegression(),
).fit(x_tr, y_tr)
holdout_mse = float(mean_squared_error(y_te, best_pipe.predict(x_te)))
# Exercise 1 repair: X=[1..5], y=[2,4,9,16,25] degree 1 -> degree 2
ex_x = np.array([[1.0], [2.0], [3.0], [4.0], [5.0]])
ex_y = np.array([2.0, 4.0, 9.0, 16.0, 25.0])
ex_r2_d1 = float(r2_score(ex_y, make_pipeline(PolynomialFeatures(1), LinearRegression()).fit(ex_x, ex_y).predict(ex_x)))
ex_r2_d2 = float(r2_score(ex_y, make_pipeline(PolynomialFeatures(2), LinearRegression()).fit(ex_x, ex_y).predict(ex_x)))
c3_ok = best_deg == 2 and holdout_mse < 0.6 and ex_r2_d2 > 0.99 and ex_r2_d2 > ex_r2_d1
cases.append(dict(
name="pipeline_cv_degree_selection",
inputs=dict(candidate_degrees=list(range(1, 11)), cv=5),
prerequisites="将 PolynomialFeatures 与 StandardScaler 装入 Pipeline,仅在训练集执行 5 折交叉验证选阶,隔离测试集。",
action="验证 5 折 CV 选出最佳阶数 degree=2 并完成留出评估;同时复现练习 1 由 degree=1 升至 degree=2 的修复效果。",
expected=dict(best_degree=2, ex1_repaired_r2_gt_099=True),
actual=dict(best_degree=best_deg, ex1_repaired_r2_gt_099=ex_r2_d2 > 0.99),
measurements=dict(
cv_mse_d1=cv_mses[1],
cv_mse_d2=cv_mses[2],
cv_mse_d3=cv_mses[3],
cv_mse_d10=cv_mses[10],
holdout_test_mse=round(holdout_mse, 4),
ex1_d1_r2=round(ex_r2_d1, 4),
ex1_d2_r2=round(ex_r2_d2, 4),
),
passed=c3_ok,
))
# 4. Multivariate degree=2 expansion (Exercise 3) + Diabetes offline single-feature CV (Exercise 2)
xm = rng.uniform(-2.0, 2.0, size=(150, 2))
ym = xm[:, 0] + xm[:, 1] ** 2 + 0.5 * xm[:, 0] * xm[:, 1] + rng.normal(0.0, 0.25, size=150)
xm_tr, xm_te, ym_tr, ym_te = train_test_split(xm, ym, test_size=0.25, random_state=42)
mp = PolynomialFeatures(degree=2, include_bias=False)
xm_tr_p = mp.fit_transform(xm_tr)
feat_names = list(mp.get_feature_names_out(["x1", "x2"]))
mlr = LinearRegression().fit(xm_tr_p, ym_tr)
multi_r2 = float(r2_score(ym_te, mlr.predict(mp.transform(xm_te))))
diab = load_diabetes()
xb = diab.data[:, [2]] # bmi feature
yb = diab.target
xb_tr, xb_te, yb_tr, yb_te = train_test_split(xb, yb, test_size=0.25, random_state=42)
diab_cv = {}
for d in (1, 2, 3, 4):
sc = cross_val_score(
make_pipeline(PolynomialFeatures(degree=d, include_bias=False), StandardScaler(), LinearRegression()),
xb_tr, yb_tr, cv=5, scoring="neg_mean_squared_error",
)
diab_cv[d] = round(float(-sc.mean()), 2)
diab_best_d = min(diab_cv, key=diab_cv.get)
exp_names = ["x1", "x2", "x1^2", "x1 x2", "x2^2"]
c4_ok = feat_names == exp_names and xm_tr_p.shape[1] == 5 and multi_r2 > 0.95 and diab_best_d in (1, 2, 3, 4)
cases.append(dict(
name="multivariate_poly_and_diabetes_feature",
inputs=dict(multi_features=["x1", "x2"], degree=2, diabetes_feature="bmi"),
prerequisites="验证二元二次多项式特征展开(含交叉项 x1*x2),并在内置糖尿病数据集 bmi 特征上做 5 折 CV 选阶。",
action="核对 5 列展开名称 ['x1','x2','x1^2','x1 x2','x2^2']、多元测试 R² >0.95 及糖尿病单特征 1..4 阶 CV MSE。",
expected=dict(feature_names=exp_names, multi_test_r2_gt_095=True),
actual=dict(feature_names=feat_names, multi_test_r2_gt_095=multi_r2 > 0.95),
measurements=dict(
multi_test_r2=round(multi_r2, 4),
diabetes_bmi_cv_mse=diab_cv,
diabetes_best_degree=diab_best_d,
),
passed=c4_ok,
))
print(json.dumps(dict(version=platform.python_version(), system=platform.system(), cases=cases), ensure_ascii=False))
if __name__ == "__main__":
run_cases()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
放在 Pipeline 内能确保每个交叉验证折仅用当前训练折拟合特征变换与缩放参数,彻底阻断验证折统计量泄露,同时稳定高次幂带来的数值条件数问题。