Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python - Triển khai hồi quy đa thức (Polynomial Regression)


Hồi quy đa thức là một dạng của hồi quy tuyến tính trong đó mối quan hệ giữa biến độc lập x và biến phụ thuộc y được mô hình hóa dưới dạng đa thức bậc n. Hồi quy đa thức phù hợp với mối quan hệ phi tuyến tính giữa giá trị x và trung bình có điều kiện của y, ký hiệu E(y|x).

Ví dụ

# Import các thư viện
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Import tập dữ liệu
datas = pd.read_csv('data.csv')
datas
# Chia tập dữ liệu thành hai thành phần
X = datas.iloc[:, 1:2].values
y = datas.iloc[:, 2].values
# Khớp Hồi quy Tuyến tính với tập dữ liệu
from sklearn.linear_model import LinearRegression
lin = LinearRegression()
lin.fit(X, y)
# Khớp Hồi quy Đa thức với tập dữ liệu
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)
# Trực quan hóa kết quả Hồi quy Tuyến tính
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()
# Trực quan hóa kết quả Hồi quy Đa thức
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()
# Dự đoán kết quả mới với Hồi quy Tuyến tính
lin.predict(110.0)
# Dự đoán kết quả mới với Hồi quy Đa thức
lin2.predict(poly.fit_transform(110.0))