进行方差选择后lasso的两幅图代码
时间: 2023-08-23 15:04:51 浏览: 106
下面是进行方差选择后使用lasso的两幅图的代码。
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LassoCV
from sklearn.datasets import load_boston
from sklearn.preprocessing import StandardScaler
# 加载数据
boston = load_boston()
X = boston.data
y = boston.target
# 数据标准化
scaler = StandardScaler()
X = scaler.fit_transform(X)
# 进行方差选择
variances = np.var(X, axis=0)
idx = variances.argsort()[::-1]
X = X[:, idx][:, :50]
# Lasso模型
model = LassoCV(cv=10)
# 拟合模型
model.fit(X, y)
# 绘制系数变化图
m_log_alphas = -np.log10(model.alphas_)
plt.figure()
plt.plot(m_log_alphas, model.coef_, '.-')
plt.axvline(-np.log10(model.alpha_), linestyle='--', color='k',
label='alpha CV')
plt.xlabel('-log(alpha)')
plt.ylabel('coefficients')
plt.title('Lasso coefficients as a function of the regularization')
plt.axis('tight')
plt.legend()
# 绘制MSE变化图
plt.figure()
plt.plot(m_log_alphas, model.mse_path_, ':')
plt.plot(m_log_alphas, model.mse_path_.mean(axis=-1), 'k',
label='Average across the folds', linewidth=2)
plt.axvline(-np.log10(model.alpha_), linestyle='--', color='k',
label='alpha CV')
plt.legend()
plt.xlabel('-log(alpha)')
plt.ylabel('Mean square error')
plt.title('Mean square error on each fold: coordinate descent')
plt.axis('tight')
plt.show()
```
这段代码的核心步骤是进行方差选择,这里使用的方法是计算每个特征的方差,并根据方差大小排序,最终选取前50个特征。然后使用LassoCV模型进行拟合,得到系数和MSE随alpha变化的曲线并绘制两幅图。
注意:这里的LassoCV模型是根据交叉验证来选择最优alpha值的,因此需要指定cv参数。
阅读全文
相关推荐














