"""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()
本例需在 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。
入口文件:projects/ml-multinomial-regression-lab/explore-multinomial-regression.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-multinomial-regression.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a488.zip