Python-多项式回归的实现


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

示例

# 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
# divide the dataset into two components
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)
# 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()
# 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()
# Predicting a new result with Linear Regression
lin.predict(110.0)
# Predicting a new result with Polynomial Regression
lin2.predict(poly.fit_transform(110.0))

更新于:06-8-2020

378 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始
广告