机器学习 l2正则化--岭回归

一、欠拟合和过拟合

       训练集上表现好,测试集上不好--过拟合
 欠拟合:
   学习到的数据的特征过少
   解决:通过增加数据的特征数量
 过拟合:
   原始特征过多,存在一些嘈杂的特征。模型复杂,模型尝试兼顾的数据较多
  解决:
        L1正则化:LASSO回归
             损失函数+λ惩罚项|w| (绝对值会使一些w的值直接=0,相当于删除了该特征的影响)
        L2正则化(更常用):Ridge回归--岭回归
             损失函数+λ惩罚项w^2 (接近于0,削弱了特征值的影响)

二、带有L2正则化的线性回归--岭回归
  API:
  sklearn.linear_model.Ridge(alpha=1.0,fit_intercept=True,solver='auto',normalize=False)
   ·alpha:正则化力度--L2正则化的惩罚项的系数λ
        ·λ取值:0~1 1~10
   ·fit_intercept:偏置
   ·solver:会根据数据自动选择优化方法
         ·SAG:如果数据集、特征都比较大,选择该随机梯度下降优化
    ·normalize:数据是否进行标准化(默认为False)
         ·normalize=False:可以在fit之前调用preprocessing.StandardScaler标准化数据
    ·Ridge.coef_:回归权重
    ·Ridge.intercept_:回归偏置
正则化力度(alpha)越大-->权重系数 ( W ) 越小
正则化力度(alpha) 越小-->权重系数(W)越大

三、岭回归预测案例代码:

# 岭回归进行预测
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_diabetes#导入数据集
from sklearn.model_selection import train_test_split #划分数据集
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression,SGDRegressor,Ridge
from sklearn.metrics import mean_squared_error

    # 1)获取数据
diab=load_diabetes()
    # 2)划分数据集
x_train,x_test,y_train,y_test=train_test_split(diab.data,diab.target,random_state=22)
    # 3)标准化
transfer=StandardScaler()
x_train=transfer.fit_transform(x_train)
x_test=transfer.transform(x_test)
    # 4)预估器
estimatar=Ridge(max_iter=10000,alpha=0.05)
estimatar.fit(x_train,y_train)
    # 5)得出模型
print('岭回归权重系数为:',estimatar.coef_)
print('岭回归偏置为:',estimatar.intercept_)
    # 6)模型评估
y_predict=estimatar.predict(x_test)
print('预测值',y_predict)
error=mean_squared_error(y_test,y_predict)
print('岭回归的均方误差:',error)


fig=plt.figure()
ax1=fig.add_subplot(221)
plt.scatter(y_test,y_predict,s=50,c='r',marker='o')
ax1.set_xlabel('y_test',labelpad=10,color='blue')
ax1.set_ylabel('y_predict',color='blue')
ax1.set_title('ax1',color='blue',size=30)

y_chazhi=np.array(y_predict-y_test)
ax2=fig.add_subplot(222)
plt.scatter(y_test,y_chazhi,s=50,c='y',marker='o')
ax2.set_xlabel('y_test',labelpad=10,color='blue')
ax2.set_ylabel('y_chazhi',color='blue')
ax2.set_title('ax2',color='blue',size=30)

# 特征名和权重系数的bar图
ax3=fig.add_subplot(223)
name_diab=diab.feature_names
y=estimatar.coef_
plt.bar(name_diab,y)
ax3.set_xlabel('name_diab',labelpad=10,color='blue')
ax3.set_ylabel('estimatar.coef_',color='blue')
ax3.set_title('ax3',color='blue',size=30,alpha=0.5)

plt.show()

四、数据可视化处理

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值