Lasso回归与岭回归

正则化

正则化是指在损失函数后面添加一个范数,以此防止模型过拟合的方式。

  • 范数定义:
    ∣ ∣ x ∣ ∣ p = ( ∑ i = 1 n ∣ x ∣ p ) 1 p ||x||_p = (\sum_{i=1}^{n}|x|^p)^\frac{1}{p} xp=(i=1nxp)p1
    1)p = 1时,即L1范数:
    ∣ ∣ x ∣ ∣ p = ( ∑ i = 1 n ∣ x ∣ ) ||x||_p = (\sum_{i=1}^{n}|x|) xp=(i=1nx)
    2)p = 2时,即L2范数:
    ∣ ∣ x ∣ ∣ p = ( ∑ i = 1 n ∣ x ∣ 2 ) 1 2 ||x||_p = (\sum_{i=1}^{n}|x|^2)^\frac{1}{2} xp=(i=1nx2)21
    通过对损失函数添加正则项,整体上压缩了参数的大小,从而防止过拟合。

Lasso回归

Lasso回归(Least absolute shrinkage and selection operator / 最小绝对值收敛和选择算子,又称套索算法),损失函数如下:
E = 1 n ∑ i = 1 n ( y − y i ′ ) + λ ∣ ∣ w ∣ ∣ 1 E = \frac{1}{n}\sum_{i=1}^{n}(y-y_i') + \lambda ||w||_1 E=n1i=1n(yyi)+λw1
其中, ∣ ∣ w ∣ ∣ 1 ||w||_1 w1为参数的一范数, λ \lambda λ为权重

岭回归

岭回归的损失函数如下:
E = 1 n ∑ i = 1 n ( y − y i ′ ) + λ ∣ ∣ w ∣ ∣ 2 E = \frac{1}{n}\sum_{i=1}^{n}(y-y_i') + \lambda ||w||_2 E=n1i=1n(yyi)+λw2
其中, ∣ ∣ w ∣ ∣ 2 ||w||_2 w2为参数的二范数, λ \lambda λ为权重

sklearn实现Lasso回归与岭回归

import numpy as np
import sklearn.linear_model as lm
import sklearn.metrics as sm
import matplotlib.pyplot as plt

x, y = [], []
with open('D:\\python\\data\\abnormal.txt', 'r') as f:
    for line in f.readlines():
        data = [float(substr) for substr in line.split(',')]
        x.append(data[:-1])
        y.append(data[-1])
x = np.array(x)
y = np.array(y)

# 1)
# 创建线性回归器
model = lm.LinearRegression()
# 训练线性回归器
model.fit(x, y)
# 预测
pred_y = model.predict(x)

# 2)
# 创建Lasso回归器
model_lasso = lm.Lasso(alpha=0.5, # 损失函数中L1范数的权重
         max_iter=1000 # 最大迭代次数
        )
# 训练Lasso回归器
model_lasso.fit(x, y)
# 预测
pred_y_lasso = model_lasso.predict(x)

# 3)
# 创建岭回归器
model_ridge = lm.Ridge(alpha=200, # 正则强度,改值越大,异常样本权重越小
                       max_iter=1000 # 最大迭代次数
                      )
# 训练岭回归器
model_ridge.fit(x, y)
# 预测
pred_y_ridge = model_ridge.predict(x)

print('--------可视化--------')
plt.figure('Linear & Ridge & Lasso', facecolor='lightgray')
plt.title('Linear & Ridge & Lasso', fontsize=18)
plt.xlabel('x', fontsize=18)
plt.ylabel('y', fontsize=18)
plt.tick_params(labelsize=12)
plt.grid(':')

plt.scatter(x, y, c='red', alpha=0.8, s=60, label='Sample')

plt.plot(x, pred_y, c='yellow', label='Linear')
plt.plot(x, pred_y_lasso, c='blue', label='Lasso')
plt.plot(x, pred_y_ridge, c='green', label='Ridge')

plt.legend()
plt.show()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_46278903/article/details/113278713