"""Independent scikit-learn + NumPy CPU lab for L1/L2/ElasticNet regularization, Dropout, EarlyStopping, and Regularization Path chart."""
import argparse
import hashlib
import json
import platform
from pathlib import Path
import numpy as np
from sklearn.linear_model import ElasticNet, Lasso, LinearRegression, Ridge
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPRegressor
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
def sha(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def run_cases(fig_dir: Path | None):
rng = np.random.default_rng(42)
cases = []
figures = {}
# 1. Lasso (L1) sparsity & automatic feature selection on 4 informative + 8 pure noise features
n_samples, n_features = 160, 12
X_sp = rng.normal(0.0, 1.0, size=(n_samples, n_features))
true_w = np.array([5.0, -3.5, 2.8, -2.0] + [0.0] * 8)
y_sp = X_sp @ true_w + rng.normal(0.0, 1.2, size=n_samples)
X_tr, X_te, y_tr, y_te = train_test_split(X_sp, y_sp, test_size=0.25, random_state=42)
scaler_sp = StandardScaler().fit(X_tr)
X_tr_s, X_te_s = scaler_sp.transform(X_tr), scaler_sp.transform(X_te)
ols_sp = LinearRegression().fit(X_tr_s, y_tr)
ols_mse = round(float(mean_squared_error(y_te, ols_sp.predict(X_te_s))), 4)
lasso_small = Lasso(alpha=0.05, max_iter=10000).fit(X_tr_s, y_tr)
lasso_med = Lasso(alpha=0.35, max_iter=10000).fit(X_tr_s, y_tr)
lasso_strong = Lasso(alpha=1.5, max_iter=10000).fit(X_tr_s, y_tr)
nz_small = int(np.sum(np.abs(lasso_small.coef_) > 1e-8))
nz_med = int(np.sum(np.abs(lasso_med.coef_) > 1e-8))
nz_strong = int(np.sum(np.abs(lasso_strong.coef_) > 1e-8))
lasso_med_mse = round(float(mean_squared_error(y_te, lasso_med.predict(X_te_s))), 4)
# Check whether the 4 true informative features remain non-zero at alpha=0.35
recovered_top4 = set(np.flatnonzero(np.abs(lasso_med.coef_) > 1e-8).tolist()) == {0, 1, 2, 3}
c1_ok = nz_strong <= nz_med < n_features and recovered_top4 and lasso_med_mse < ols_mse
cases.append(dict(
name="lasso_l1_sparsity_and_feature_selection",
inputs=dict(n_samples=n_samples, informative=4, noise_features=8, alphas=[0.05, 0.35, 1.5]),
prerequisites="4 个真实特征 + 8 个纯噪声特征,先划分训练/测试集并在训练集拟合 StandardScaler",
action="验证 Lasso 随 alpha 增大产生精确零权重,在 alpha=0.35 精准保留全部 4 个真实特征并将 8 个噪声特征清零,且测试 MSE 低于 OLS。",
expected=dict(exact_true_4_recovered=True, test_mse_beats_ols=True, sparsity_monotonic=True),
actual=dict(exact_true_4_recovered=recovered_top4, test_mse_beats_ols=lasso_med_mse < ols_mse, sparsity_monotonic=(nz_strong <= nz_med < n_features)),
measurements=dict(ols_test_mse=ols_mse, lasso_035_test_mse=lasso_med_mse, nz_005=nz_small, nz_035=nz_med, nz_150=nz_strong),
passed=c1_ok,
))
# 2. Ridge (L2) weight shrinkage & stabilization under strong multicollinearity
z0 = rng.normal(0.0, 1.0, size=140)
z1 = z0 + rng.normal(0.0, 0.015, size=140) # nearly collinear with z0
z2 = rng.normal(0.0, 1.0, size=140)
X_col = np.column_stack([z0, z1, z2])
y_col = 2.0 * z0 + 2.0 * z1 - 1.5 * z2 + rng.normal(0.0, 0.6, size=140)
Xc_tr, Xc_te, yc_tr, yc_te = train_test_split(X_col, y_col, test_size=0.25, random_state=42)
sc_col = StandardScaler().fit(Xc_tr)
Xc_tr_s, Xc_te_s = sc_col.transform(Xc_tr), sc_col.transform(Xc_te)
ols_col = LinearRegression().fit(Xc_tr_s, yc_tr)
ridge_norms = {}
ridge_nz = {}
for alpha in (0.1, 1.0, 10.0, 100.0):
rm = Ridge(alpha=alpha).fit(Xc_tr_s, yc_tr)
ridge_norms[str(alpha)] = round(float(np.linalg.norm(rm.coef_)), 4)
ridge_nz[str(alpha)] = int(np.sum(np.abs(rm.coef_) > 1e-12))
ols_col_norm = round(float(np.linalg.norm(ols_col.coef_)), 4)
ridge_1_mse = round(float(mean_squared_error(yc_te, Ridge(alpha=1.0).fit(Xc_tr_s, yc_tr).predict(Xc_te_s))), 4)
ols_col_mse = round(float(mean_squared_error(yc_te, ols_col.predict(Xc_te_s))), 4)
norms_list = [ridge_norms[str(a)] for a in (0.1, 1.0, 10.0, 100.0)]
monotonic_shrink = all(norms_list[i] > norms_list[i + 1] for i in range(len(norms_list) - 1))
all_dense = all(v == 3 for v in ridge_nz.values())
c2_ok = ols_col_norm > ridge_norms["1.0"] and monotonic_shrink and all_dense
cases.append(dict(
name="ridge_l2_shrinkage_and_collinearity",
inputs=dict(n_samples=140, collinear_noise=0.015, alphas=[0.1, 1.0, 10.0, 100.0]),
prerequisites="强共线性特征 (x1 ≈ x0) 上比较 OLS 与 Ridge 权重 L2 范数及稠密性",
action="验证 OLS 在共线性下权重范数剧烈膨胀,而 Ridge 随 alpha 增大严格单调收缩权重范数且保持全非零稠密解。",
expected=dict(ols_inflated_vs_ridge1=True, l2_norm_strictly_decreasing=True, all_weights_nonzero=True),
actual=dict(ols_inflated_vs_ridge1=ols_col_norm > ridge_norms["1.0"], l2_norm_strictly_decreasing=monotonic_shrink, all_weights_nonzero=all_dense),
measurements=dict(ols_l2_norm=ols_col_norm, ols_coefs=[round(float(v), 3) for v in ols_col.coef_], ridge_l2_norms=ridge_norms, ols_test_mse=ols_col_mse, ridge_1_test_mse=ridge_1_mse),
passed=c2_ok,
))
# 3. Degree-10 polynomial overfitting vs Lasso / Ridge / ElasticNet on held-out test set
X_poly = np.linspace(-3.0, 3.0, 100).reshape(-1, 1)
y_poly = 0.5 * X_poly.ravel() ** 2 + X_poly.ravel() + rng.normal(0.0, 0.85, size=100)
Xp_tr, Xp_te, yp_tr, yp_te = train_test_split(X_poly, y_poly, test_size=0.3, random_state=42)
poly_models = {
"OLS": Pipeline([("poly", PolynomialFeatures(10, include_bias=False)), ("scaler", StandardScaler()), ("reg", LinearRegression())]),
"Lasso": Pipeline([("poly", PolynomialFeatures(10, include_bias=False)), ("scaler", StandardScaler()), ("reg", Lasso(alpha=0.08, max_iter=20000))]),
"Ridge": Pipeline([("poly", PolynomialFeatures(10, include_bias=False)), ("scaler", StandardScaler()), ("reg", Ridge(alpha=5.0))]),
"ElasticNet": Pipeline([("poly", PolynomialFeatures(10, include_bias=False)), ("scaler", StandardScaler()), ("reg", ElasticNet(alpha=0.08, l1_ratio=0.5, max_iter=20000))]),
}
poly_metrics = {}
for name, pipe in poly_models.items():
pipe.fit(Xp_tr, yp_tr)
tr_mse = round(float(mean_squared_error(yp_tr, pipe.predict(Xp_tr))), 4)
te_mse = round(float(mean_squared_error(yp_te, pipe.predict(Xp_te))), 4)
w_norm = round(float(np.linalg.norm(pipe.named_steps["reg"].coef_)), 4)
poly_metrics[name] = dict(train_mse=tr_mse, test_mse=te_mse, coef_l2_norm=w_norm)
c3_ok = (
poly_metrics["Lasso"]["test_mse"] < poly_metrics["OLS"]["test_mse"]
and poly_metrics["Ridge"]["test_mse"] < poly_metrics["OLS"]["test_mse"]
and poly_metrics["ElasticNet"]["test_mse"] < poly_metrics["OLS"]["test_mse"]
and poly_metrics["OLS"]["coef_l2_norm"] > poly_metrics["Ridge"]["coef_l2_norm"] * 5
)
cases.append(dict(
name="elasticnet_and_poly_overfitting_control",
inputs=dict(n_samples=100, degree=10, test_size=0.3),
prerequisites="10 次多项式回归管线(先划分后标准化),对比无正则化 OLS 与 Lasso/Ridge/ElasticNet 留出测试 MSE",
action="验证无正则化 10 次多项式权重范数极高且测试 MSE 恶化,而 Lasso/Ridge/ElasticNet 均显著降低留出测试 MSE。",
expected=dict(all_regularizers_beat_ols_test_mse=True, ols_weight_norm_gt_5x_ridge=True),
actual=dict(
all_regularizers_beat_ols_test_mse=(
poly_metrics["Lasso"]["test_mse"] < poly_metrics["OLS"]["test_mse"]
and poly_metrics["Ridge"]["test_mse"] < poly_metrics["OLS"]["test_mse"]
and poly_metrics["ElasticNet"]["test_mse"] < poly_metrics["OLS"]["test_mse"]
),
ols_weight_norm_gt_5x_ridge=(poly_metrics["OLS"]["coef_l2_norm"] > poly_metrics["Ridge"]["coef_l2_norm"] * 5),
),
measurements=poly_metrics,
passed=c3_ok,
))
# 4. Dropout expectation invariance (NumPy) + EarlyStopping (scikit-learn MLPRegressor)
p_drop = 0.5
activations = np.ones(50000, dtype=np.float64) * 2.0
keep_mask = (rng.random(activations.shape) >= p_drop).astype(np.float64)
# Classic dropout: train unscaled masked (mean = 2*(1-p)=1.0), eval scales by (1-p) -> 1.0
classic_train_mean = round(float(np.mean(activations * keep_mask)), 4)
classic_eval_mean = round(float(np.mean(activations * (1.0 - p_drop))), 4)
# Inverted dropout: train scales kept units by 1/(1-p) -> mean ~ 2.0, eval untouched -> 2.0
inverted_train_mean = round(float(np.mean(activations * keep_mask / (1.0 - p_drop))), 4)
inverted_eval_mean = round(float(np.mean(activations)), 4)
mlp_es = Pipeline([
("scaler", StandardScaler()),
("mlp", MLPRegressor(
hidden_layer_sizes=(48, 24), max_iter=500,
early_stopping=True, validation_fraction=0.2,
n_iter_no_change=10, random_state=42,
)),
])
mlp_es.fit(X_tr, y_tr)
stopped_iter = int(mlp_es.named_steps["mlp"].n_iter_)
es_r2 = round(float(r2_score(y_te, mlp_es.predict(X_te))), 4)
c4_ok = (
abs(classic_train_mean - classic_eval_mean) < 0.03
and abs(inverted_train_mean - inverted_eval_mean) < 0.05
and stopped_iter < 500
and es_r2 >= 0.85
)
cases.append(dict(
name="dropout_expectation_and_early_stopping",
inputs=dict(dropout_p=0.5, units=50000, mlp_max_iter=500, n_iter_no_change=10),
prerequisites="NumPy 校验经典 Dropout 与 Inverted Dropout 训练/推理期望一致 + scikit-learn MLPRegressor 早停实测",
action="验证 p=0.5 时两种缩放策略训练与推理期望偏差均 <0.05,且早停使 MLPRegressor 在远小于 500 轮时终止并保持测试 R2 >=0.85。",
expected=dict(dropout_expectation_matched=True, stopped_before_max_iter=True, test_r2_ge_85=True),
actual=dict(
dropout_expectation_matched=(abs(classic_train_mean - classic_eval_mean) < 0.03 and abs(inverted_train_mean - inverted_eval_mean) < 0.05),
stopped_before_max_iter=stopped_iter < 500,
test_r2_ge_85=es_r2 >= 0.85,
),
measurements=dict(
classic_train_mean=classic_train_mean,
classic_eval_mean=classic_eval_mean,
inverted_train_mean=inverted_train_mean,
inverted_eval_mean=inverted_eval_mean,
stopped_iter=stopped_iter,
test_r2=es_r2,
),
passed=c4_ok,
))
# 5. Matplotlib Ridge vs Lasso regularization path chart
alphas_grid = np.logspace(-2, 2.5, 45)
ridge_path = np.array([Ridge(alpha=a).fit(X_tr_s, y_tr).coef_ for a in alphas_grid])
lasso_path = np.array([Lasso(alpha=a, max_iter=20000).fit(X_tr_s, y_tr).coef_ for a in alphas_grid])
mpl_ver = None
if fig_dir is not None:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig_dir.mkdir(parents=True, exist_ok=True)
fig, axes = plt.subplots(1, 2, figsize=(9.8, 3.8), dpi=140, sharey=True)
log_a = np.log10(alphas_grid)
for j in range(n_features):
is_sig = j < 4
color = ["#174d79", "#ae511d", "#2b7a5b", "#7c3f8c"][j] if is_sig else "#b0b8bf"
lw = 2.0 if is_sig else 0.9
alpha_line = 0.95 if is_sig else 0.65
lbl = f"Signal f{j} (w={true_w[j]:+.1f})" if is_sig else ("Noise f4..f11" if j == 4 else None)
axes[0].plot(log_a, ridge_path[:, j], color=color, linewidth=lw, alpha=alpha_line, label=lbl)
axes[1].plot(log_a, lasso_path[:, j], color=color, linewidth=lw, alpha=alpha_line, label=lbl)
axes[0].axhline(0.0, color="#444444", linewidth=0.7, linestyle=":")
axes[0].set_title("Ridge (L2) Regularization Path", fontsize=10)
axes[0].set_xlabel("log10(alpha)")
axes[0].set_ylabel("Standardized Coefficient")
axes[0].grid(True, alpha=0.3)
axes[0].legend(fontsize=7.5, loc="upper right")
axes[1].axhline(0.0, color="#444444", linewidth=0.7, linestyle=":")
axes[1].axvline(np.log10(0.35), color="#d9534f", linewidth=1.2, linestyle="--", label="alpha=0.35 (4 nonzero)")
axes[1].set_title("Lasso (L1) Regularization Path", fontsize=10)
axes[1].set_xlabel("log10(alpha)")
axes[1].grid(True, alpha=0.3)
axes[1].legend(fontsize=7.5, loc="upper right")
fig.tight_layout()
out_png = fig_dir / "regularization-path-ridge-lasso.png"
fig.savefig(out_png)
plt.close(fig)
figures["regularization-path-ridge-lasso.png"] = sha(out_png)
mpl_ver = matplotlib.__version__
cases.append(dict(
name="observed_regularization_path_plot",
inputs=dict(alpha_points=len(alphas_grid), n_features=n_features),
prerequisites="在 4 信号 + 8 噪声特征训练集上沿 log10(alpha) 计算 Ridge 与 Lasso 系数路径",
action="输出 Ridge 连续衰减路径与 Lasso 稀疏归零路径双图 PNG。",
expected=dict(path_points=45),
actual=dict(path_points=len(alphas_grid)),
measurements=dict(figure_generated="regularization-path-ridge-lasso.png" in figures),
passed=len(alphas_grid) == 45,
))
payload = dict(
version=platform.python_version(),
system=platform.system(),
cases=cases,
)
if mpl_ver:
payload["matplotlib"] = mpl_ver
payload["figures"] = figures
print(json.dumps(payload, ensure_ascii=False))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--figures", type=Path, default=None)
args = parser.parse_args()
run_cases(args.figures)
本例需在 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-model-optimization-regularization-lab/explore-model-optimization-regularization.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-model-optimization-regularization.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章) · 含当前章节或实例 · mbskycom202612a487.zip