逻辑回归正则化解释性实验报告:L2 正则对模型系数收缩的可视化分析
逻辑回归正则化解释性实验报告
L2 正则化对模型系数的影响
L2 正则化(Ridge 正则化)通过在损失函数中增加系数的平方和惩罚项,约束模型复杂度,防止过拟合。其目标函数为:
[ J(\theta) = -\frac{1}{m} \sum_{i=1}^m [y^{(i)} \log(h_\theta(x^{(i)})) + (1-y^{(i)}) \log(1-h_\theta(x^{(i)}))] + \frac{\lambda}{2m} \sum_{j=1}^n \theta_j^2 ]
其中 $\lambda$ 是正则化强度参数,$\theta_j$ 为模型系数。
实验设计与可视化方法
固定其他超参数(如学习率、迭代次数),逐步增大 $\lambda$ 值(例如从 0.01 到 100),记录每次训练后模型系数的绝对值。
使用 Python 的 sklearn.linear_model.LogisticRegression 实现,设置 penalty='l2',并通过 coef_ 属性提取系数。
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression# 模拟数据
X = np.random.randn(100, 5)
y = np.random.randint(0, 2, 100)# 不同 lambda 值(C=1/lambda)
lambdas = np.logspace(-2, 2, 20)
coefs = []
for l in lambdas:model = LogisticRegression(penalty='l2', C=1/l, solver='liblinear')model.fit(X, y)coefs.append(np.abs(model.coef_[0]))# 可视化
plt.figure(figsize=(10, 6))
for i in range(5):plt.plot(lambdas, [c[i] for c in coefs], label=f'Feature {i+1}')
plt.xscale('log')
plt.xlabel('Lambda (Regularization Strength)')
plt.ylabel('Absolute Coefficient Value')
plt.title('L2 Regularization Effect on Logistic Regression Coefficients')
plt.legend()
plt.grid(True)
plt.show()
典型可视化结果分析
- 低 $\lambda$ 值(弱正则化):系数接近无正则化时的原始值,模型可能过拟合。
- 中等 $\lambda$ 值:系数被均匀压缩,但保留相对重要性排序。
- 高 $\lambda$ 值(强正则化):所有系数趋近于零,模型趋向欠拟合。
关键结论
- L2 正则化会平滑地减小所有系数的绝对值,但通常不会将任何系数压缩至零。
- 特征重要性排序在适度正则化下保持稳定,适用于需要保留所有特征的场景。
- 最优 $\lambda$ 需通过交叉验证确定,平衡偏差与方差。
