Stop 07 · Supervised Learning: RegressionTopics · 5/8

Polynomial Regression

Part of the Machine Learning Roadmap

In short

Plenty of real relationships curve. Ice cream sales rise with temperature, then dip when it gets too hot to step outside. Polynomial regression lets a straight-line model bend, without learning a new algorithm.

Polynomial regression fits curves by adding squared, cubed and interaction features and then running ordinary linear regression. Higher degrees fit training data better but quickly start to overfit.

The jaadu gently bends a long bamboo stick to follow a curved stone garden path, with a wildly wiggly bent stick lying discarded nearby.

Think of it like this

Bending a bamboo stick

A straight bamboo stick can't follow a curved garden path. Heat it and you can bend it once, and it fits a gentle curve. Bend it many times and it can trace every pebble on the path, but now it only fits that one path. Polynomial degree is how many bends you allow: a few is helpful, too many is overfitting.

Watch it happen

Same data, rising degree

degree 1
0
degree 2
1
degree 3
2
degree 15
3

1/5The data rises and then falls, like sales against temperature.

The big ideas

What you need to know

Add powers as features

From x, create x², x³ and so on. The model is still linear in its weights, so ordinary linear regression fits it.

Interactions too

With two features, degree 2 also creates x1·x2, letting the effect of one depend on the other.

Scale after expanding

x¹⁰ can be astronomically large. Put a StandardScaler after PolynomialFeatures.

Degree is a hyperparameter

Pick it with cross-validation, and add Ridge regularisation if you need a higher degree.

See it in code

Walk through the code

python
1import numpy as np2from sklearn.linear_model import LinearRegression3from sklearn.model_selection import cross_val_score4from sklearn.pipeline import make_pipeline5from sklearn.preprocessing import PolynomialFeatures, StandardScaler6 7rng = np.random.default_rng(1)8temp = rng.uniform(20, 45, 120).reshape(-1, 1)            # temperature in °C9sales = -2 * (temp[:, 0] - 34) ** 2 + 500 + rng.normal(0, 20, 120)10 11for degree in [1, 2, 3, 15]:12    model = make_pipeline(13        PolynomialFeatures(degree=degree, include_bias=False),14        StandardScaler(),15        LinearRegression(),16    )17    score = cross_val_score(model, temp, sales, cv=5, scoring="r2").mean()18    print(degree, round(score, 3))

1/3Sales rise to a peak near 34°C and fall after, plus noise. reshape makes temp a 2-D column.

Ice cream sales peak around 34°C. Cross-validation shows which degree generalises.

Save yourself the pain

Common mistakes

Oops

Choosing the degree that gives the best training score.

Do this instead

Training score always improves with degree. Choose by validation or cross-validation score.

Oops

Using high-degree polynomials to extrapolate beyond the data.

Do this instead

Polynomials shoot off wildly outside the training range. Don't trust predictions at 50°C if you only saw up to 45°C.

Your mission

Find the sweet spot

~25 min

Quick check

Why is polynomial regression still called linear regression?

Go deeper

  1. 1Use PolynomialFeatures with degrees 1, 3 and 15 on curved data and plot each fit.
  2. 2Compare training and validation error as the degree grows.
  3. 3Put PolynomialFeatures, StandardScaler and Ridge together in one Pipeline.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge