Not every relationship is a straight line. A car's fuel efficiency rises with speed up to a point, then falls. Electricity demand is high on cold days and on hot days, and lowest in between. A straight line through a curve will always miss, however well you fit it.
Polynomial regression fits curves while still using ordinary linear regression underneath. This lesson shows how it works, how to build it with scikit-learn, and how to choose the degree, the setting that decides how bendy the curve can be. Choosing it is the clearest example of the most important trade-off in machine learning: underfitting vs overfitting.
The data: a curved relationship
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(1)
temp = np.sort(rng.uniform(5, 45, 60)) # daily temperature, °C
demand = 0.09 * (temp - 24) ** 2 + 30 + rng.normal(0, 3, 60) # electricity, GWh
fig, ax = plt.subplots()
ax.scatter(temp, demand)
ax.set_xlabel("Temperature (°C)")
ax.set_ylabel("Electricity demand (GWh)")
ax.set_title("Demand is high on cold and hot days")
plt.show()
Heating on cold days, air conditioning on hot days: a U shape. (The numbers are simulated for the example.)
A straight line underfits
from sklearn.linear_model import LinearRegression
X = temp.reshape(-1, 1)
line = LinearRegression().fit(X, demand)
print(round(line.score(X, demand), 3))
0.093
An R² of 0.09: the line explains almost nothing, because no straight line can follow a U. This is underfitting: the model is too simple for the pattern.
The trick: add powers of x as features
A degree-2 polynomial is:
y = b + m₁·x + m₂·x²
That's a curve in x, but it's still linear in the coefficients m₁ and m₂. So if we create a new feature column holding x², ordinary linear regression can fit it. PolynomialFeatures creates those columns:
from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(degree=2, include_bias=False)
print(poly.fit_transform([[2], [3], [10]]))
[[ 2. 4.]
[ 3. 9.]
[ 10. 100.]]
Each x becomes [x, x²]. include_bias=False leaves out a column of 1s, because LinearRegression adds its own intercept.
Fit the curve
Chain the two steps in a pipeline:
from sklearn.pipeline import make_pipeline
curve = make_pipeline(PolynomialFeatures(degree=2, include_bias=False),
LinearRegression())
curve.fit(X, demand)
print(round(curve.score(X, demand), 3))
print(curve[-1].coef_.round(3), round(curve[-1].intercept_, 2))
0.949
[-4.259 0.089] 80.84
R² jumps from 0.09 to 0.95. The learnt curve is about demand = 80.8 − 4.26·temp + 0.089·temp², close to the true rule we used to make the data (0.09·temp² once expanded).
Underfitting, a good fit and overfitting
What if we let the curve bend even more? Compare degrees 1, 2 and 15:
from sklearn.preprocessing import StandardScaler
def poly_model(degree):
return make_pipeline(StandardScaler(),
PolynomialFeatures(degree, include_bias=False),
LinearRegression())
grid = np.linspace(5, 45, 300).reshape(-1, 1)
fig, axes = plt.subplots(1, 3, figsize=(13, 4), sharey=True)
for ax, degree in zip(axes, [1, 2, 15]):
model = poly_model(degree).fit(X, demand)
ax.scatter(temp, demand, s=15)
ax.plot(grid, model.predict(grid), color="crimson", lw=2)
ax.set_title(f"Degree {degree}")
ax.set_xlabel("Temperature (°C)")
ax.set_ylim(15, 85)
axes[0].set_ylabel("Demand (GWh)")
plt.show()
poly_model scales the temperature before taking powers. Without that, temp¹⁵ reaches about 6 × 10²⁴ and the computer can no longer fit the coefficients accurately.
- Degree 1 underfits: too simple, it misses the shape.
- Degree 2 fits well: it captures the real pattern and ignores the noise.
- Degree 15 overfits: it bends to chase random noise in individual points and swings wildly at the edges. It has memorised the data instead of learning the pattern.
Choose the degree with a validation set
The training score always improves as the degree grows, so it can't pick the degree. Use data the model hasn't seen, as explained in train, validation and test sets:
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
X_train, X_val, y_train, y_val = train_test_split(X, demand, test_size=0.3, random_state=0)
for degree in [1, 2, 3, 5, 10, 15]:
model = poly_model(degree).fit(X_train, y_train)
train_rmse = mean_squared_error(y_train, model.predict(X_train)) ** 0.5
val_rmse = mean_squared_error(y_val, model.predict(X_val)) ** 0.5
print(f"degree {degree:2}: train RMSE {train_rmse:5.2f} validation RMSE {val_rmse:6.2f}")
degree 1: train RMSE 10.22 validation RMSE 10.81
degree 2: train RMSE 2.51 validation RMSE 2.44
degree 3: train RMSE 2.51 validation RMSE 2.45
degree 5: train RMSE 2.50 validation RMSE 2.45
degree 10: train RMSE 2.40 validation RMSE 4.13
degree 15: train RMSE 2.18 validation RMSE 4.60
RMSE is the typical prediction error in GWh (lower is better), explained in regression metrics. Training error keeps falling as the degree rises, but validation error is lowest at degree 2, stays flat to degree 5, then nearly doubles. That rising validation error is overfitting made visible. Pick the simplest model near the lowest validation error: degree 2.
Tips for polynomial regression
| Tip | Why |
|---|---|
| Start with degree 2 or 3 | Higher degrees rarely help and often overfit |
| Scale features for high degrees | x¹⁵ for x = 45 is about 6 × 10²⁴; huge numbers cause numerical problems |
| Watch the edges | Polynomials swing wildly beyond the training range; don't extrapolate |
| With several features, use few degrees | PolynomialFeatures also makes every combination (x₁·x₂, x₁²…), so the column count explodes |
| Add regularisation | Ridge keeps high-degree coefficients in check |
| Consider other models | Decision trees and gradient boosting fit curves without choosing a degree |
Practice
- How many columns does
PolynomialFeatures(degree=3, include_bias=False)make from one feature?
Show the answer
Three: x, x² and x³.
- Fit degree 4 to the full data and print its R². Is it worth using instead of degree 2?
Show the answer
m4 = make_pipeline(PolynomialFeatures(4, include_bias=False), LinearRegression()).fit(X, demand)
print(m4.score(X, demand))
It's only a tiny bit higher on training data, and it doesn't improve validation error, so the simpler degree 2 is better.
- A model has a training RMSE of 0.5 and a validation RMSE of 9.0. Underfitting or overfitting?
Show the answer
Overfitting: it fits the training data almost perfectly but does badly on new data. Reduce the degree, add regularisation, or get more data.
Interview questions
What is polynomial regression?
Linear regression on polynomial features of the inputs (x, x², x³…). It models curved relationships while remaining linear in its coefficients, so it's fitted with ordinary least squares.
What is the difference between underfitting and overfitting?
Underfitting: the model is too simple to capture the pattern, so errors are high on both training and new data. Overfitting: the model is so flexible it learns noise, so training error is low but error on new data is high.
How do you choose the polynomial degree?
Compare degrees by error on a validation set or with cross-validation, and choose the simplest degree near the lowest validation error. Regularisation can make higher degrees safer.
What to learn next
- Learn the error measures used here in regression metrics: MAE, MSE, RMSE and R².
- Control overfitting with Ridge and Lasso regularisation.