要可视化每个参数对应的特征数量和R2,可以使用Matplotlib库绘制散点图。具体地,我们可以将LassoCV模型的alpha值作为x轴,将模型选择的特征数量作为y轴,并使用散点图展示每个alpha值下选择的特征数量。同时,我们也可以将LassoCV模型在训练集上的R2值作为另一个y轴,并使用双y轴展示每个alpha值下的R2值。
下面是一个使用Matplotlib可视化LassoCV模型参数和性能指标的Python代码示例:
```python
import matplotlib.pyplot as plt
from sklearn.linear_model import LassoCV
from sklearn.datasets import load_boston
from sklearn.metrics import r2_score
# 加载数据集
X, y = load_boston(return_X_y=True)
# 定义LassoCV模型
lasso_cv = LassoCV(cv=5)
# 在训练集上训练模型
lasso_cv.fit(X, y)
# 获取每个alpha值下选择的特征数量和对应的R2值
alphas = lasso_cv.alphas_
n_features = [sum(coef != 0) for coef in lasso_cv.coefs_]
r2_scores = [r2_score(y, lasso_cv.predict(X)) for alpha in alphas]
# 绘制散点图
fig, ax1 = plt.subplots()
color = 'tab:red'
ax1.set_xlabel('alpha')
ax1.set_ylabel('Number of features', color=color)
ax1.scatter(alphas, n_features, color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax2 = ax1.twinx()
color = 'tab:blue'
ax2.set_ylabel('R2 score', color=color)
ax2.plot(alphas, r2_scores, color=color)
ax2.tick_params(axis='y', labelcolor=color)
fig.tight_layout()
plt.show()
```
在上面的代码中,我们首先加载了波士顿房价数据集,然后定义了一个LassoCV模型,并在训练集