Lesson 05
多元回归与正则化:从一个特征到多个特征
真实问题的预测几乎都依赖多个特征。本章从多元线性回归出发,引入多项式扩展、过拟合问题,再用 Ridge / Lasso 正则化控制复杂度。
本章细分学习地图
| 模块 | 拆细学习单元 | 完成后应产出 | 掌握标准 |
|---|---|---|---|
| 多元回归 | 矩阵形式 ŷ = Xw + b,多系数解读。 | 多特征回归代码。 | 能解读每个特征的 coef_ 并判断重要性。 |
| 多项式回归 | PolynomialFeatures 构造、阶数与过拟合。 | 不同阶数拟合对比。 | 能解释为什么高阶会过拟合。 |
| 正则化 | L2(Ridge) 压缩系数、L1(Lasso) 产生稀疏。 | 正则强度对比实验。 | 能选择 Ridge 或 Lasso 并调 alpha。 |
| 综合实战 | Pipeline + 交叉验证选 alpha。 | 完整 Pipeline 代码。 | 能构建端到端回归 Pipeline。 |
学习目标
多元回归到正则化
1多特征输入
2多项式扩展
3正则化约束
4模型训练与评估
本章完成度
已完成 0/4
多元线性回归
当特征不止一个时,假设函数变成向量形式:
ŷ = w₁x₁ + w₂x₂ + … + wpxp + b = Xw + b
p 个特征,每个 wⱼ 表示第 j 个特征对预测的贡献
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
X, y = make_regression(n_samples=200, n_features=3, noise=10, random_state=42)
model = LinearRegression().fit(X, y)
for i, c in enumerate(model.coef_):
print(f"特征 {i}: coef = {c:.3f}")
print(f"截距: {model.intercept_:.3f}")
系数大小 ≠ 特征重要性
只有在特征缩放后,coef_ 的绝对值才能作为特征重要性的参考。未缩放时,量纲不同会导致系数大小不可比。
多项式回归
当线性模型拟合不了非线性关系时,可以用 PolynomialFeatures 把特征扩展成高阶多项式,再用线性回归拟合。
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_score
from sklearn.datasets import make_regression
import numpy as np
X, y = make_regression(n_samples=100, n_features=1, noise=15, random_state=42)
for degree in [1, 2, 3, 5]:
pipe = Pipeline([
("poly", PolynomialFeatures(degree=degree, include_bias=False)),
("lr", LinearRegression()),
])
score = cross_val_score(pipe, X, y, cv=5, scoring="r2").mean()
print(f"degree={degree} R²={score:.4f}")
过拟合警告
阶数越高,模型越灵活,但特征数量爆炸式增长。degree=5 时一个特征变成 5 个,三个特征变成 56 个。高阶多项式几乎必须配合正则化使用。
正则化:Ridge 与 Lasso
正则化在代价函数中加入惩罚项,防止系数过大导致过拟合。
JRidge = MSE + α · Σwj²
L2 正则化:整体压缩系数但不置零
JLasso = MSE + α · Σ|wj|
L1 正则化:可以将部分系数压至 0(自动特征选择)
| 方法 | 效果 | 适用场景 |
|---|---|---|
| Ridge (L2) | 所有系数缩小但不为零。 | 特征都可能有用,只想控制复杂度。 |
| Lasso (L1) | 部分系数变成 0,自动特征选择。 | 高维稀疏场景,想找出关键特征。 |
| ElasticNet | L1 + L2 的混合。 | 折中场景,特征相关性高。 |
from sklearn.linear_model import Ridge, Lasso
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_score
from sklearn.datasets import make_regression
X, y = make_regression(n_samples=100, n_features=1, noise=15, random_state=42)
for name, Model in [("Ridge", Ridge), ("Lasso", Lasso)]:
pipe = Pipeline([
("poly", PolynomialFeatures(degree=5, include_bias=False)),
("scaler", StandardScaler()),
("model", Model(alpha=1.0)),
])
score = cross_val_score(pipe, X, y, cv=5, scoring="r2").mean()
print(f"{name} R²={score:.4f}")
pipe.fit(X, y)
print(f" coef_: {pipe.named_steps['model'].coef_[:5].round(3)}")
综合实战:Pipeline + 交叉验证选 alpha
from sklearn.linear_model import Ridge
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import make_regression
X, y = make_regression(n_samples=200, n_features=3, noise=20, random_state=42)
pipe = Pipeline([
("poly", PolynomialFeatures(include_bias=False)),
("scaler", StandardScaler()),
("ridge", Ridge()),
])
param_grid = {
"poly__degree": [1, 2, 3],
"ridge__alpha": [0.01, 0.1, 1.0, 10.0],
}
grid = GridSearchCV(pipe, param_grid, cv=5, scoring="r2", n_jobs=-1)
grid.fit(X, y)
print(f"最佳参数: {grid.best_params_}")
print(f"最佳 R²: {grid.best_score_:.4f}")
练习题
第 1 题:多元回归中 coef_ = [3.2, -1.5, 0.8],哪个特征影响最大?前提是什么?
参考思路:特征 0(|3.2| 最大)影响最大,前提是所有特征已缩放到同一量纲。
第 2 题:Ridge 和 Lasso 的 alpha 越大,模型越简单还是越复杂?
参考思路:alpha 越大,正则越强,模型越简单(系数被压缩更多)。alpha=0 退化为普通线性回归。
检查点
离开本章前,请确认:
- 能写出多元回归的矩阵形式并解读每个特征的系数。
- 能解释多项式扩展如何捕捉非线性关系以及过拟合风险。
- 能区分 Ridge(L2)和 Lasso(L1)的效果和适用场景。
- 能构建 PolynomialFeatures + Scaler + Ridge 的 Pipeline 并用 GridSearchCV 选参数。