4.弹性网络( Elastic Net)

本文介绍了ElasticNet回归模型,一种结合了L1和L2正则化的线性回归方法,适用于特征间存在多重共线性的场景。文章通过实例展示了不同正则化参数下系数的变化路径,并比较了Lasso、Ridge及ElasticNet等模型的特点。

ElasticNet 是一种使用L1和L2先验作为正则化矩阵的线性回归模型.这种组合用于只有很少的权重非零的稀疏模型,比如:class:Lasso, 但是又能保持:class:Ridge 的正则化属性.我们可以使用 l1_ratio 参数来调节L1和L2的凸组合(一类特殊的线性组合)。

当多个特征和另一个特征相关的时候弹性网络非常有用。Lasso 倾向于随机选择其中一个,而弹性网络更倾向于选择两个.
在实践中,Lasso 和 Ridge 之间权衡的一个优势是它允许在循环过程(Under rotate)中继承 Ridge 的稳定性.
弹性网络的目标函数是最小化:

\underset{w}{min\,} { \frac{1}{2n_{samples}} ||X w - y||_2 ^ 2 + \alpha \rho ||w||_1 +\frac{\alpha(1-\rho)}{2} ||w||_2 ^ 2}

ElasticNetCV 可以通过交叉验证来用来设置参数 alpha (\alpha) 和 l1_ratio (\rho)




print(__doc__)

import numpy as np
import matplotlib.pyplot as plt

from sklearn.linear_model import lasso_path, enet_path
from sklearn import datasets

diabetes = datasets.load_diabetes()
X = diabetes.data
y = diabetes.target

X /= X.std(axis=0)  # Standardize data (easier to set the l1_ratio parameter)

# Compute paths

eps = 5e-3  # the smaller it is the longer is the path

print("Computing regularization path using the lasso...")
alphas_lasso, coefs_lasso, _ = lasso_path(X, y, eps, fit_intercept=False)

print("Computing regularization path using the positive lasso...")
alphas_positive_lasso, coefs_positive_lasso, _ = lasso_path(
    X, y, eps, positive=True, fit_intercept=False)
print("Computing regularization path using the elastic net...")
alphas_enet, coefs_enet, _ = enet_path(
    X, y, eps=eps, l1_ratio=0.8, fit_intercept=False)

print("Computing regularization path using the positve elastic net...")
alphas_positive_enet, coefs_positive_enet, _ = enet_path(
    X, y, eps=eps, l1_ratio=0.8, positive=True, fit_intercept=False)

# Display results

plt.figure(1)
ax = plt.gca()
ax.set_color_cycle(2 * ['b', 'r', 'g', 'c', 'k'])
l1 = plt.plot(-np.log10(alphas_lasso), coefs_lasso.T)
l2 = plt.plot(-np.log10(alphas_enet), coefs_enet.T, linestyle='--')

plt.xlabel('-Log(alpha)')
plt.ylabel('coefficients')
plt.title('Lasso and Elastic-Net Paths')
plt.legend((l1[-1], l2[-1]), ('Lasso', 'Elastic-Net'), loc='lower left')
plt.axis('tight')


plt.figure(2)
ax = plt.gca()
ax.set_color_cycle(2 * ['b', 'r', 'g', 'c', 'k'])
l1 = plt.plot(-np.log10(alphas_lasso), coefs_lasso.T)
l2 = plt.plot(-np.log10(alphas_positive_lasso), coefs_positive_lasso.T,
              linestyle='--')

plt.xlabel('-Log(alpha)')
plt.ylabel('coefficients')
plt.title('Lasso and positive Lasso')
plt.legend((l1[-1], l2[-1]), ('Lasso', 'positive Lasso'), loc='lower left')
plt.axis('tight')


plt.figure(3)
ax = plt.gca()
ax.set_color_cycle(2 * ['b', 'r', 'g', 'c', 'k'])
l1 = plt.plot(-np.log10(alphas_enet), coefs_enet.T)
l2 = plt.plot(-np.log10(alphas_positive_enet), coefs_positive_enet.T,
              linestyle='--')

plt.xlabel('-Log(alpha)')
plt.ylabel('coefficients')
plt.title('Elastic-Net and positive Elastic-Net')
plt.legend((l1[-1], l2[-1]), ('Elastic-Net', 'positive Elastic-Net'),
           loc='lower left')
plt.axis('tight')
plt.show()


### ElasticNet回归的基本原理 ElasticNet是一种线性回归模型,它结合了L1正则化(Lasso回归)和L2正则化(岭回归)的优点。通过引入两个正则化参数,ElasticNet能够在处理高维数据时提供更好的性能。具体来说,ElasticNet的损失函数可以表示为: $$ J(\beta) = \frac{1}{2n} \| y - X\beta \|^2_2 + \lambda \left[ \alpha \| \beta \|^2_2 + (1 - \alpha) \| \beta \|_1 \right] $$ 其中: - $ \| y - X\beta \|^2_2 $ 是最小二乘损失项。 - $ \lambda $ 是正则化强度参数。 - $ \alpha $ 是L1和L2正则化之间的平衡参数,取值范围为 $ 0 \leq \alpha \leq 1 $。 - $ \| \beta \|^2_2 $ 表示L2正则化项。 - $ \| \beta \|_1 $ 表示L1正则化项 [^3]。 当 $ \alpha = 0 $ 时,ElasticNet退化为岭回归;而当 $ \alpha = 1 $ 时,ElasticNet等同于Lasso回归。这种混合正则化方法不仅能够防止过拟合,还能够进行特征选择,尤其适用于高维数据中存在多重共线性的情况 [^2]。 ### ElasticNet的应用场景 ElasticNet在以下场景中表现尤为出色: 1. **高维数据处理**:当特征数量远大于样本数量时,ElasticNet能够有效地进行特征选择和模型正则化 [^1]。 2. **多重共线性问题**:当自变量之间存在高度相关性时,ElasticNet通过L2正则化部分缓解了这一问题 [^2]。 3. **稀疏特征选择**:通过调整 $ \alpha $ 参数,ElasticNet可以在稀疏模型中选择重要的特征 [^3]。 例如,在基因表达数据分析中,ElasticNet被广泛用于识别与特定疾病相关的基因。在金融领域,ElasticNet也常用于预测股票价格或评估投资组合风险 [^1]。 ### ElasticNet的超参数调优 ElasticNet有两个关键的超参数需要调优: 1. **Alpha ($ \alpha $)**:控制L1和L2正则化之间的平衡。当 $ \alpha $ 接近1时,模型更倾向于Lasso回归;而当 $ \alpha $ 接近0时,模型更倾向于岭回归 [^3]。 2. **Lambda ($ \lambda $)**:控制正则化的强度。较大的 $ \lambda $ 值会导致更强的正则化效果,从而减少模型复杂度 [^3]。 通常使用交叉验证来选择最佳的 $ \alpha $ 和 $ \lambda $ 组合。例如,在某些建模任务中,最佳超参数组合可能是 $ \alpha = 1 $ 和 $ \lambda \approx 9.55 $,这表明L1正则化对当前数据的特征选择更有效 [^3]。 ### ElasticNet的实现示例 以下是一个使用Python的Scikit-learn库实现ElasticNet回归的示例代码: ```python from sklearn.linear_model import ElasticNet from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error import numpy as np # 生成随机数据 np.random.seed(42) X = np.random.rand(100, 10) y = np.random.rand(100) # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 初始化ElasticNet模型 elastic_net = ElasticNet(alpha=0.1, l1_ratio=0.5) # 训练模型 elastic_net.fit(X_train, y_train) # 预测 y_pred = elastic_net.predict(X_test) # 评估模型 mse = mean_squared_error(y_test, y_pred) print(f"Mean Squared Error: {mse}") ``` 在上述代码中,`alpha` 参数控制正则化的强度,而 `l1_ratio` 参数控制L1和L2正则化之间的平衡。通过调整这些参数,可以优化模型的性能 [^3]。
评论 9
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值