为什么提示line 35, in <module> lasso = Lasso(alpha=lasso.alphas_[i]) AttributeError: 'Lasso' object has no attribute 'alphas_'
时间: 2023-12-15 07:04:46 浏览: 213
Lasso+SVM_lasso降不了维_lasso_降维_SVM_lassosvm_
5星 · 资源好评率100%
非常抱歉,我在代码中犯了一个错误。我应该使用`LassoCV`对象的`alphas_`属性来获取1000个Lasso系数,而不是使用`Lasso`对象。以下是修改后的代码:
```python
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.linear_model import LassoCV
from sklearn.linear_model import Lasso
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
# 加载Excel数据
data = pd.read_excel('D:\Data\20230726.xlsx')
X = data.iloc[:, :-1].values # 特征变量
y = data.iloc[:, -1].values # 目标变量
# 数据标准化处理
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 自动交叉验证选择最佳Lasso系数
lasso_cv = LassoCV(cv=5, alphas=np.logspace(-3, 3, 1000))
lasso_cv.fit(X_scaled, y)
# 最佳Lasso系数
best_alpha = lasso_cv.alpha_
# 获取各变量的贡献度
coefficients = lasso_cv.coef_
# 储存1000个lasso系数和8个贡献度列表
X = np.log10(lasso_cv.alphas_)
Y1, Y2, Y3, Y4, Y5, Y6, Y7, Y8 = [], [], [], [], [], [], [], []
for i in range(1000):
lasso = Lasso(alpha=lasso_cv.alphas_[i])
lasso.fit(X_scaled, y)
coef = lasso.coef_
Y1.append(coef[0])
Y2.append(coef[1])
Y3.append(coef[2])
Y4.append(coef[3])
Y5.append(coef[4])
Y6.append(coef[5])
Y7.append(coef[6])
Y8.append(coef[7])
# 绘制Lasso回归系数变化路径图
plt.figure()
plt.plot(X, Y1, label='Feature 1')
plt.plot(X, Y2, label='Feature 2')
plt.plot(X, Y3, label='Feature 3')
plt.plot(X, Y4, label='Feature 4')
plt.plot(X, Y5, label='Feature 5')
plt.plot(X, Y6, label='Feature 6')
plt.plot(X, Y7, label='Feature 7')
plt.plot(X, Y8, label='Feature 8')
plt.xlabel('log(Lasso Alpha)')
plt.ylabel('Contribution')
plt.title('Lasso Coefficient Path')
plt.legend()
plt.show()
# 打印结果
print(f'最佳Lasso系数: {best_alpha}')
for index, feature in enumerate(data.columns[:-1]):
print(f'{feature}的贡献度: {coefficients[index]}')
```
非常抱歉给你带来了困扰,希望这次的修改可以解决问题。如果还有其他问题,请随时提问。
阅读全文