Reading history

Polynomial Regression in Python with scikit-learn

5 min read 1 views

Learn polynomial regression in Python: PolynomialFeatures, fitting curves with a pipeline, choosing the degree with test error, and avoiding overfitting.

Polynomial regression fits a curve instead of a straight line. The trick is simple: add powers of a feature, such as x² and x³, as new columns, then run ordinary linear regression on them. The model stays linear in its coefficients, so it trains just as fast, but it can now follow bends in the data.

In this lesson you will learn

  • How PolynomialFeatures creates new columns
  • Fitting a curve with a pipeline
  • Reading the coefficients and finding the lowest point
  • Choosing the degree with a test set
  • Why high degrees overfit

You should know linear regression and regression metrics.

A Curve That a Line Cannot Fit

Cars use more fuel at very low speeds and at very high speeds. The best economy is somewhere in the middle. A straight line can only go up or down, so it cannot capture this U shape.

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures

# Fuel used (litres per 100 km) at different speeds: high at both ends
speed = np.array([30, 40, 50, 60, 70, 80, 90, 100, 110, 120]).reshape(-1, 1)
fuel = np.array([8.1, 6.9, 6.0, 5.6, 5.4, 5.6, 6.1, 6.8, 7.7, 8.9])

line = LinearRegression().fit(speed, fuel)
curve = make_pipeline(PolynomialFeatures(degree=2), LinearRegression()).fit(speed, fuel)

print("Straight line R^2:", round(r2_score(fuel, line.predict(speed)), 3))
print("Degree-2 curve R^2:", round(r2_score(fuel, curve.predict(speed)), 3))

print("\nNew features for speed 50:", PolynomialFeatures(degree=2).fit_transform([[50]]))
lr = curve.named_steps["linearregression"]
print("Coefficients:", np.round(lr.coef_, 5), "intercept:", round(lr.intercept_, 3))

grid = np.arange(30, 121).reshape(-1, 1)
best = grid[curve.predict(grid).argmin()][0]
print("Most economical speed:", best, "km/h")

Output

Straight line R^2: 0.081
Degree-2 curve R^2: 0.994

New features for speed 50: [[1.0e+00 5.0e+01 2.5e+03]]
Coefficients: [ 0.      -0.21208  0.00149] intercept: 13.015
Most economical speed: 71 km/h
  • The straight line explains only 8% of the variation (R² = 0.081). The degree-2 curve explains 99.4%.
  • PolynomialFeatures(degree=2) turns the single value 50 into three columns: 1, 50 and 2500 (that is 50²). The first column is a constant.
  • The fitted equation is roughly fuel = 13.015 − 0.212 × speed + 0.00149 × speed². The constant column’s coefficient is 0 because LinearRegression already has its own intercept.
  • Predicting over every speed from 30 to 120 and taking argmin finds the most economical speed: 71 km/h.

How Many Powers? Choosing the Degree

The degree is a setting you choose. Too low and the curve is too stiff (underfitting). Too high and it bends to chase noise (overfitting). Compare degrees on data the model did not see.

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler

rng = np.random.default_rng(0)
x = rng.uniform(-3, 3, 60).reshape(-1, 1)
y = 0.5 * x[:, 0] ** 3 - 2 * x[:, 0] + rng.normal(0, 1.5, 60)   # a cubic with noise
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5, random_state=0)

print("degree   train RMSE   test RMSE")
for degree in [1, 2, 3, 6, 12]:
    model = make_pipeline(PolynomialFeatures(degree), StandardScaler(), LinearRegression())
    model.fit(x_train, y_train)
    tr = mean_squared_error(y_train, model.predict(x_train)) ** 0.5
    te = mean_squared_error(y_test, model.predict(x_test)) ** 0.5
    print(f"{degree:>6}   {tr:>10.2f}   {te:>9.2f}")

Output

degree   train RMSE   test RMSE
     1         2.23        2.96
     2         1.87        3.22
     3         1.32        1.94
     6         1.18        3.32
    12         1.02        7.16
  • The true shape is a cubic, and degree 3 has the lowest test error, 1.94.
  • Training error keeps falling as the degree grows, all the way down to 1.02. Training error alone always prefers the most complex model.
  • At degree 12 the test error jumps to 7.16. The curve swings wildly between training points, especially near the edges.
  • Degree 2 does worse than degree 1 here. A cubic is lopsided, and an x² term alone adds a U shape that the data does not have.
  • StandardScaler sits after PolynomialFeatures because powers such as x¹² create huge numbers that are hard to fit accurately without scaling.

Several Features at Once

With two features a and b, PolynomialFeatures(degree=2) creates 1, a, b, a², ab and b². The ab column is an interaction: it lets the effect of one feature depend on the other. The number of columns grows quickly, so with many features use a low degree, set interaction_only=True, or add Ridge regularization.

Original featuresDegreeColumns created (with constant)
134
226
10266
103286

Common Mistakes

  1. Choosing the degree by training score, which always picks the highest degree.
  2. Predicting far outside the training range. Polynomials shoot off to huge values beyond the data.
  3. Forgetting to scale high-degree features before regularized models.
  4. Using a high degree on many features, which creates hundreds of columns and overfits.

Practice Exercises

Exercise 1. Use the fuel model to predict consumption at 65 km/h.

Show answer
print(curve.predict([[65]]))

About 5.5 litres per 100 km, close to the measured values at 60 and 70 km/h.

Exercise 2. Replace the degree loop with GridSearchCV to pick the degree by cross-validation.

Show answer
from sklearn.model_selection import GridSearchCV
pipe = make_pipeline(PolynomialFeatures(), StandardScaler(), LinearRegression())
search = GridSearchCV(pipe, {"polynomialfeatures__degree": [1, 2, 3, 4, 5, 6]},
                      cv=5, scoring="neg_root_mean_squared_error")
search.fit(x_train, y_train)
print(search.best_params_)

Frequently Asked Questions

Is polynomial regression linear or non-linear?

Both, in different senses. The curve is non-linear in x, but the model is linear in its coefficients. That is why ordinary least squares can fit it.

When should I use a tree model instead?

When the shape is irregular, has sudden steps, or involves many features. Polynomials suit smooth, gentle curves in a small number of features.

Summary

  • Polynomial regression adds powers of the features, then fits a linear model.
  • make_pipeline(PolynomialFeatures(d), LinearRegression()) does it in one step.
  • Pick the degree using test or cross-validation error, never training error.
  • High degrees overfit and behave badly outside the training range.

Next: Feature Selection in Python.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *