lasso回归预测代码
时间: 2024-11-28 20:21:48 浏览: 18
Lasso回归是一种线性模型,它通过引入L1正则化来解决过拟合问题。Lasso回归会使得一些特征的系数变为0,因此也被称作“最小绝对值 shrinkage 和 selection operator”(LASSO)。以下是一个简单的Python代码示例,使用sklearn库实现Lasso回归:
```python
# 导入所需的库
from sklearn.linear_model import Lasso
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
import pandas as pd
# 加载波士顿房价数据集
boston = load_boston()
X = boston.data
y = boston.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建Lasso回归模型
lasso = Lasso(alpha=0.1) # alpha参数控制正则化的强度
# 训练模型
lasso.fit(X_train, y_train)
# 预测测试集结果
y_pred_lasso = lasso.predict(X_test)
# 打印特征选择情况(系数不为0的特征)
non_zero_features = [feature for feature in range(len(boston.feature_names)) if abs(lasso.coef_[feature]) > 1e-5]
print("非零特征列表:", non_zero_features)
阅读全文