Python | 多项式回归的实现

2019-01-28  本文已影响45人  编程自习室

  多项式回归是一种线性回归形式,其中自变量x和因变量y之间的关系被建模为n次多项式。多项式回归拟合x的值与y的相应条件均值之间的非线性关系,表示为E(y | x)

为什么多项式回归:

多项式回归的使用:

  这些基本上用于定义或描述非线性现象,例如:

  回归分析的基本目标是根据自变量x的值来模拟因变量y的期望值。在简单回归中,我们使用以下等式 -

y = a + bx + e

  这里y是因变量,a是y截距,b是斜率,e是误差率。

  在许多情况下,这种线性模型将无法解决。例如,如果我们在这种情况下根据合成温度分析化学合成的产生,我们使用二次模型

y = a + b1x + b2 ^ 2 + e

  这里y是x的因变量,a是y截距,e是误差率。

  通常,我们可以将其建模为第n个值。

y = a + b1x + b2x ^ 2 + .... + bnx ^ n

  由于回归函数在未知变量方面是线性的,因此这些模型从估计的角度来看是线性的。

因此,通过最小二乘技术,让我们计算y的响应值。

Python中的多项式回归:

要获得用于分析多项式回归的数据集,请单击此处

# Importing the libraries 
import numpy as np 
import matplotlib.pyplot as plt 
import pandas as pd 

# Importing the dataset 
datas = pd.read_csv('data.csv') 
datas 
image.png

  将数据集划分为两个组件,即X和yX将包含1到2之间的列.y将包含2列。

X = datas.iloc[:, 1:2].values 
y = datas.iloc[:, 2].values 

  拟合线性回归模型在两个组件上。

# Fitting Linear Regression to the dataset 
from sklearn.linear_model import LinearRegression 
lin = LinearRegression() 

lin.fit(X, y) 

  将多项式回归模型拟合到两个分量X和y上。

# Fitting Polynomial Regression to the dataset 
from sklearn.preprocessing import PolynomialFeatures 

poly = PolynomialFeatures(degree = 4) 
X_poly = poly.fit_transform(X) 

poly.fit(X_poly, y) 
lin2 = LinearRegression() 
lin2.fit(X_poly, y) 
# Visualising the Linear Regression results 
plt.scatter(X, y, color = 'blue') 

plt.plot(X, lin.predict(X), color = 'red') 
plt.title('Linear Regression') 
plt.xlabel('Temperature') 
plt.ylabel('Pressure') 

plt.show() 
image
# Visualising the Polynomial Regression results 
plt.scatter(X, y, color = 'blue') 

plt.plot(X, lin2.predict(poly.fit_transform(X)), color = 'red') 
plt.title('Polynomial Regression') 
plt.xlabel('Temperature') 
plt.ylabel('Pressure') 

plt.show() 
image
# Predicting a new result with Linear Regression 
lin.predict(110.0) 
image
# Predicting a new result with Polynomial Regression 
lin2.predict(poly.fit_transform(110.0)) 
image

使用多项式回归的优点:

使用多项式回归的缺点

上一篇下一篇

猜你喜欢

热点阅读