python和机器学习 第八章 多项式回归与模型泛化(一)什么是多项式回归

In [79]: import numpy as np
    ...: import matplotlib.pyplot as plt

In [80]: x = np.random.uniform(-3,3,size=100)
    ...: X = x.reshape(-1,1)
In [81]: y = 0.5 * x**2 + x + 2 + np.random.normal(0,1,size=100)
线性回归
In [83]: from sklearn.linear_model import LinearRegression
    ...: lin_reg = LinearRegression()
    ...: lin_reg.fit(X,y)
In [84]: y_predict = lin_reg.predict(X)
In [85]: plt.scatter(x,y)
    ...: plt.plot(x,y_predict,color='r')    

在这里插入图片描述

线性回归效果不好
解决方案,添加一个特征
In [86]: (X**2).shape
Out[86]: (100, 1)
In [87]: X2 = np.hstack([X,X**2])
In [88]: X2.shape
Out[88]: (100, 2)
多项式回归
多项式回归是使用线性回归的方法,只不过在原有的基础上添加了新的特征,即对数据进行升维处理
In [89]: lin_reg2 = LinearRegression()
    ...: lin_reg2.fit(X2,y)
    ...: y_predict2 = lin_reg2.predict(X2)

In [90]: plt.scatter(x,y)
    ...: plt.plot(np.sort(x),y_predict2[np.argsort(x)],color='r')
#得到的系数和y函数系数近似    
In [91]: lin_reg2.coef_
Out[91]: array([1.01871165, 0.51946111])

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值