用Python给我写一个套索回归并画图实现
时间: 2023-06-01 13:02:50 浏览: 56
以下是使用Python实现套索回归并绘图的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import Lasso
# 生成数据
np.random.seed(42)
n_samples, n_features = 50, 100
X = np.random.randn(n_samples, n_features)
coef = 3 * np.random.randn(n_features)
inds = np.arange(n_features)
np.random.shuffle(inds)
coef[inds[10:]] = 0
y = np.dot(X, coef)
# 拟合模型
alpha = 0.1
lasso = Lasso(alpha=alpha)
lasso.fit(X, y)
coef_lasso = lasso.coef_
# 绘图
plt.figure(figsize=(10, 6))
plt.plot(coef, label='True coef')
plt.plot(coef_lasso, label='Lasso coef')
plt.legend(loc='best')
plt.title('Lasso Regression')
plt.show()
```
在上面的代码中,我们首先生成了50个样本和100个特征的数据。其中,真实的系数向量为3倍的随机向量,但我们将随机向量中的10个元素设为0,以模拟实际情况下的稀疏性。然后,我们使用Lasso回归拟合数据,并将真实系数向量和Lasso回归得到的系数向量绘制在同一张图上进行比较。
运行上面的代码,我们将得到以下绘图结果:
![Lasso Regression](https://i.imgur.com/L4M0Jce.png)