Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - การ Implement Polynomial Regression

Polynomial Regression เป็นรูปแบบของ Linear Regression ที่ความสัมพันธ์ระหว่างตัวแปรอิสระ x และตัวแปร従属 y ถูกจำลองเป็น polynomial อันดับ n Polynomial regression ตรงกับความสัมพันธ์ nonlinear ระหว่างค่า x และ conditional mean ของ y

ตัวอย่างโค้ด


import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

# โหลดข้อมูล
datas = pd.read_csv('data.csv')

# แบ่ง features และ target
X = datas.iloc[:, 1:2].values  # 2D array (n_samples, 1)
y = datas.iloc[:, 2].values    # 1D array

# Linear Regression
lin = LinearRegression()
lin.fit(X, y)

# Polynomial Regression (degree = 4)
poly = PolynomialFeatures(degree=4)
X_poly = poly.fit_transform(X)
poly.fit(X_poly, y)
lin2 = LinearRegression()
lin2.fit(X_poly, y)

# Visualize Linear Regression
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()

# Visualize Polynomial Regression
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()

# ทำนายค่าใหม่
print("Linear prediction (110):", lin.predict([[110.0]]))
print("Poly prediction (110):", lin2.predict(poly.fit_transform([[110.0]])))

ขั้นตอนสำคัญ

  1. PolynomialFeatures: สร้าง polynomial features (x, x², x³, ...)
  2. fit_transform: แปลง X เป็น polynomial matrix
  3. LinearRegression: ฝึกโมเดลบน features ที่แปลงแล้ว
  4. predict: ใช้ poly.fit_transform() ก่อน predict

PolynomialFeatures Detail


from sklearn.preprocessing import PolynomialFeatures

poly = PolynomialFeatures(degree=3, include_bias=True)
X = [[2], [3]]
X_poly = poly.fit_transform(X)
print(X_poly)
# [[1. 2. 4. 8.]   ← 1, x, x², x³
#  [1. 3. 9. 27.]]

Pipeline (แนะนำ - ป้องกัน Data Leakage)


from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

# Pipeline: Scale → Polynomial → Linear Regression
model = Pipeline([
    ('scaler', StandardScaler()),
    ('poly', PolynomialFeatures(degree=4)),
    ('linear', LinearRegression())
])

model.fit(X, y)
pred = model.predict([[110.0]])

Model Selection: เลือก Degree ยังไง?


from sklearn.model_selection import cross_val_score
import numpy as np

degrees = range(1, 10)
cv_scores = []

for degree in degrees:
    model = Pipeline([
        ('poly', PolynomialFeatures(degree=degree)),
        ('linear', LinearRegression())
    ])
    scores = cross_val_score(model, X, y, cv=5, scoring='neg_mean_squared_error')
    cv_scores.append(-scores.mean())

best_degree = degrees[np.argmin(cv_scores)]
print(f"Best degree: {best_degree}")

Overfitting Warning

  • Degree สูงเกินไป → Overfit (เรียนรู้ noise)
  • ใช้ Cross-validation เลือก degree
  • Regularization (Ridge/Lasso) ช่วยลด overfitting
  • Visualize residuals ตรวจสอบ pattern

Regularized Polynomial Regression


from sklearn.linear_model import Ridge, Lasso
from sklearn.pipeline import Pipeline

# Ridge (L2 regularization)
ridge_poly = Pipeline([
    ('poly', PolynomialFeatures(degree=10)),
    ('ridge', Ridge(alpha=1.0))
])

# Lasso (L1 regularization - feature selection)
lasso_poly = Pipeline([
    ('poly', PolynomialFeatures(degree=10)),
    ('lasso', Lasso(alpha=0.1))
])