机器学习的练功方式(十)——岭回归

十 岭回归

岭回归是线性回归的改进,有时候迫不得已我们的参数确实不能少,这时候过拟合的现象就可能发生。为了避免过拟合现象的发生,既然不能从减少参数上面下手,那我们转而在线性回归的最后面添加一个罚项,罚项有时也被称为正则化项,其主要用于控制模型的平滑度,当模型参数越多,模型越复杂,那么罚项惩罚值就越大。

罚项可以是L1范数也可以是L2范数,对于使用L1范数的回归我们一般叫做Lasso线性回归。而对于使用L2范数的回归我们一般叫做岭回归。在这一讲中,我们主要讲述岭回归。

10.1 岭回归的接口

Ridge回归通过对系数的大小施加惩罚来解决普通线性模型使用最小二乘法带来的一些问题。

sklearn.linear_model.Ridge(alpha = 1.0,fit_intercept = True,solver = “auto”,normalize = False)

  • 具有L2正则化的线性回归
  • alpha:正则化力度,也叫 λ λ λ
  • λ取值为0~1或 1~10
  • solver:会根据数据自动选择优化方法
  • SAG:如果数据集、特征都比较大,那么建议选择sag作为优化策略
  • normalize:数据是否进行标准化
  • normalize = False:可以在fit之前调用preprocessing.StandardScaler标准化数据
  • Ridge.coef_:回归权重
  • Ridge.intercept_:回归偏置

image-20220315114214511

从图上来看,当alpha数值越高,则惩罚力度越大,权重系数越小,曲线越平滑。

10.2 岭回归处理房价预测

让我们用岭回归来预测波士顿房价吧。

from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error


def load_data():
    """加载数据集"""
    boston_data = load_boston()
    x_train, x_test, y_train, y_test = train_test_split(boston_data.data, boston_data.target, random_state=22)
    return x_train, x_test, y_train, y_test


def ridge_linear_model():
    """用岭回归做预测"""
    x_train, x_test, y_train, y_test = load_data()

    # 预估器
    estimator = Ridge(normalize=True)
    estimator.fit(x_train, y_train)

    # 得出模型
    print("权重系数为:\n", estimator.coef_)
    print("偏置为:\n", estimator.intercept_)

    # 模型评估
    y_predict = estimator.predict(x_test)
    print("预测房价:\n", y_predict)
    error = mean_squared_error(y_test, y_predict)
    print("岭回归——均方误差为:\n", error)


ridge_linear_model()
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ArimaMisaki

如果知识有用请我喝杯咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值