赞
踩
Lasso 回归(Least Absolute Shrinkage and Selection Operator)是一种线性回归模型,通过引入 正则化(也称为 Lasso 正则化),在训练模型的同时对系数进行约束。Lasso 回归不仅能够避免过拟合,还能够自动进行特征选择,通过将一些不重要的特征的系数缩减为零,从而简化模型。
Lasso 回归的目标是最小化以下损失函数:
其中:
Lasso 回归的损失函数可以分为两部分:
2. 正则化项:用于惩罚模型的复杂度,具体为范数:
因此,Lasso 回归的目标是找到一组回归系数 ,使得上述损失函数最小化。
Lasso 回归的主要作用包括:
Lasso 回归的优化问题可以表示为:
该优化问题通常通过坐标下降法(Coordinate Descent)来求解。
接下来,我们通过一个具体的案例来展示如何使用 Lasso 回归进行建模,并对结果进行详细分析。
我们将使用一个模拟的数据集,其中包含多个特征和目标变量。我们会人为地加入一些噪声,增加特征选择的难度。
- import numpy as np
- import pandas as pd
- from sklearn.model_selection import train_test_split
- from sklearn.linear_model import Lasso
- from sklearn.metrics import mean_squared_error, r2_score
-
- # 生成模拟数据
- np.random.seed(42)
- X = np.random.randn(100, 10) # 100个样本,10个特征
- true_coefficients = np.array([1.5, -2, 0, 0, 3, 0, 0, 0, 0, 5]) # 实际的回归系数
- y = X.dot(true_coefficients) + np.random.randn(100) * 0.5 # 生成目标变量,并加入噪声
-
- # 将数据划分为训练集和测试集
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
-
- # 将数据转化为DataFrame以便查看
- df = pd.DataFrame(X, columns=[f"Feature_{i+1}" for i in range(X.shape[1])])
- df['Target'] = y
- print(df.head())

输出:
- Feature_1 Feature_2 Feature_3 Feature_4 Feature_5 Feature_6 Feature_7 Feature_8 Feature_9 Feature_10 Target
- 0 0.496714 -0.138264 0.647689 1.523030 -0.234153 -0.234137 1.579213 0.767435 -0.469474 0.542560 0.513884
- 1 -0.463418 -0.465730 0.241962 -1.913280 -1.724918 -0.562288 -1.012831 0.314247 -0.908024 -1.412304 -8.905334
- 2 -1.424748 -0.544383 0.110923 -1.150994 0.375698 -0.600639 -0.291694 -0.601707 1.852278 -0.013497 1.041154
- 3 -1.057711 0.822545 -1.220844 0.208864 -1.959670 -1.328186 0.196861 0.738467 0.171368 -0.115648 -5.937149
- 4 -1.478522 -0.719844 -0.460639 1.057122 0.343618 -1.763040 0.324084 -0.385082 -0.676922 0.611676 -0.340138
我们使用 Lasso 回归模型进行训练,并选择合适的正则化参数 。
- # 定义Lasso回归模型,并选择正则化参数alpha
- lasso_model = Lasso(alpha=0.1)
- lasso_model.fit(X_train, y_train)
-
- # 输出模型系数
- print("模型截距 (Intercept):", lasso_model.intercept_)
- print("模型系数 (Coefficients):", lasso_model.coef_)
输出:
- 模型截距 (Intercept): -0.03688971929504553
- 模型系数 (Coefficients): [ 1.36801626 -1.89662579 0. -0. 2.98880389 0.
- 0. -0. 0. 4.93463356]
解释:
使用训练好的模型对测试集进行预测,并评估模型的性能。
- # 对测试集进行预测
- y_pred = lasso_model.predict(X_test)
-
- # 计算均方误差 (MSE) 和决定系数 (R²)
- mse = mean_squared_error(y_test, y_pred)
- r2 = r2_score(y_test, y_pred)
-
- print("均方误差 (MSE):", mse)
- print("决定系数 (R²):", r2)
输出:
- 均方误差 (MSE): 0.27528742481852454
- 决定系数 (R²): 0.9840898373917382
解释:
Lasso 回归是一种有效的线性回归方法,通过引入 正则化项来避免过拟合并自动选择特征。在模型训练过程中,Lasso 回归不仅能够对系数进行缩减,还能够将不重要的特征的系数缩减为零,实现特征选择。通过案例分析,我们验证了 Lasso 回归在特征选择和模型简化中的有效性,并展示了如何使用 Python 进行实现和结果分析。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。