Python遇见机器学习 ---- 多项式回归 Polynomial Regression

本文探讨Python中的多项式回归,通过scikit-learn库的PolynomialFeatures和Pipeline实现。同时讨论过拟合和欠拟合,解释train-test-split与交叉验证的重要性,并介绍岭回归和LASSO作为正则化方法降低模型复杂度。
摘要由CSDN通过智能技术生成

综述 

“寒泉自可斟,况复杂肴醴。”

 本文采用编译器:jupyter 

在介绍线性回归模型时,曾假设所有模拟的数据均满足线性关系,即y是x的一次函数,然而现实中极少有这么理想的数据,这是我们就需要考虑更一般化的方法了,其中多项式回归为我们提供了一些思路。

如上图,虽然y是关于x的二次方程,但实际上如果把x平方与x分别看成两个特征就变成我们之前所介绍的线性回归问题。

即,相当于我们对原来的数据增加了一些特征(升维),但本质上还是求的这条曲线。

01 多项式回归

 

import numpy as np
import matplotlib.pyplot as plt

x = np.random.uniform(-3, 3, size=100)
X = x.reshape(-1, 1)

y = 0.5 * x**2 + x + 2 + np.random.normal(0, 1, size=100)

plt.scatter(x, y)
plt.show()

# 先查看线性回归的效果
from sklearn.linear_model import LinearRegression
​
lin_reg = LinearRegression()
lin_reg.fit(X, y)
# Out[6]:
# LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)

y_predict = lin_reg.predict(X)

plt.scatter(x, y)
plt.plot(x, y_predict, color='r')
plt.show() # 可以看到效果并不是很好

 解决方法,添加一个特征


(X**2).shape
# Out[9]:
# (100, 1)

X2 = np.hstack([X, X**2])

X2.shape
# Out[11]:
# (100, 2)

lin_reg2 = LinearRegression()
lin_reg2.fit(X2, y)
y_predict2 = lin_reg2.predict(X2)

plt.scatter(x, y)
# x是乱序的,我们应该按照x从小到大来绘制
plt.plot(np.sort(x), y_predict2[np.argsort(x)], color='r')
plt.show() 

lin_reg2.coef_ # 查看系数a和b
# Out[15]:
# array([ 0.84918223,  0.48009585])

lin_reg2.intercept_ # 查看截距
# Out[16]:
# 1.9942420971618127

02 scikit-learn中的多项式回归和Pipeline

 

PolynomialFeatures(degree=3) 中的参数degree表示阶数,计算如下:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.uniform(-3, 3, size=100)
X = x.reshape(-1, 1)
y = 0.5 * x**2 + x + 2 + np.random.normal(0, 1, size=100)

# 多项式回归最主要的事情是数据预处理
from sklearn.preprocessing import PolynomialFeatures

poly = PolynomialFeatures(degree=2) # 添加二次幂特征
​
poly.fit(X)
X2 = poly.transform(X)

X2.shape
# Out[5]:
# (100, 3)

X2[:5,:] # 第一列是x的0次方,最后一列是x的2次方
# Out[7]:
"""
array([[ 1.        ,  1.72084082,  2.96129314],
       [ 1.        , -0.72185736,  0.52107804],
       [ 1.        , -0.97576562,  0.95211855],
       [ 1.        , -1.76849693,  3.12758138],
       [ 1.        , -1.54863002,  2.39825493]])
"""

from sklearn.linear_model import LinearRegression
​
lin_reg2 = LinearRegression()
lin_reg2.fit(X2, y)
y_predict2 = lin_reg2.predict(X2)

plt.scatter(x, y)
plt.plot(np.sort(x), y_predict2[np.argsort(x)], color='r')
plt.show()

 

lin_reg2.coef_
# Out[10]:
# array([ 0.        ,  1.0779785 ,  0.55559044])

lin_reg2.intercept_
# Out[11]:
# 1.7321546824053558

关于PolynomialFeatures

 

X = np.arange(1, 11).reshape(-1, 2)

X.shape
# Out[13]:
# (5, 2)

X
"""
Out[14]:
array([[ 1,  2],
       [ 3,  4],
       [ 5,  6],
       [ 7,  8],
       [ 9, 10]])
"""

poly = PolynomialFeatures(degree=2)
poly.fit(X)
X2 = poly.transform(X)

X2.shape
# Out[16]:
# (5, 6)

# X的平方变成三列,分别是第一列的平方,第一列乘以第二列,第二列的平方
X2
"""
Out[17]:
array([[   1.,    1.,    2.,    1.,    2.,    4.],
       [   1.,    3.,    4.,    9.,   12.,   16.],
       [   1.,    5.,    6.,   25.,   30.,   36.],
       [   1.,    7.,    8.,   49.,   56.,   64.],
       [   1.,    9.,   10.,   81.,   90.,  100.]])
"""

poly = PolynomialFeatures(degree=3)
poly.fit(X)
X3 = poly.transform(X)

X3.shape
# Out[19]:
# (5, 10)

X3
"""
Out[20]:
array([[    1.,     1.,     2.,     1.,     2.,     4.,     1.,     2.,
            4.,     8.],
       [    1.,     3.,     4.,     9.,    12.,    16.,    27.,    36.,
           48.,    64.],
       [    1.,     5.,     6.,    25.,    30.,    36.,   125.,   150.,
          180.,   216.],
       [    1.,     7.,     8.,    49.,    56.,    64.,   343.,   392.,
          448.,   512.],
       [    1.,     9.,    10.,    81.,    90.,   100.,   729.,   810.,
          900.,  1000.]])
"""

Pipeline

 

x = np.random.uniform(-3, 3, size=100)
X = x.reshape(-1, 1)
y = 0.5 * x**2 + x + 2 + np.random.normal(0, 1, size=100)

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
​
# 传入每一步骤所对应的类 1.多项式的特征 2.数据归一化 3.线性回归
poly_reg = Pipeline([
    ("poly", PolynomialFeatures(degree=2)),
    ("std_scaler", StandardScaler()),
    ("lin_reg", LinearRegression())
])

poly_reg.fit(X, y)
y_predict = poly_reg.predict(X)

plt.scatter(x, y)
plt.plot(np.sort(x), y_predict[np.argsort(x)], color='r')
plt.show()

 

03 过拟合,欠拟合

 

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(666)
x = np.random.uniform(-3, 3, size=100)
X = x.reshape(-1, 1)
y = 0.5 * x**2 + x + 2 + np.random.normal(0, 1, size=100)

plt.scatter(x, y)
plt.show()

使用线性回归

 

from sklearn.linear_model import LinearRegression
​
lin_reg = LinearRegression()
lin_reg.fit(X, y)
lin_reg.score(X, y)
# Out[4]:
# 0.49537078118650091

# 欠拟合
y_predict = lin
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小王曾是少年

如果对你有帮助,欢迎支持我

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

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

打赏作者

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

抵扣说明:

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

余额充值