ML Polynomial Regression
Not every relationship is a straight line. Think about the fuel use of a car at different speeds: very slow driving is inefficient, there is a sweet spot around medium speed, and fuel use climbs again at high speed because of air resistance. A straight line cannot follow that curve. Polynomial regression fits a curved line instead.
A polynomial of degree 2 (a parabola) looks like this:
y = a*x² + b*x + cDegree 3 adds an x³ term, and so on. Higher degrees allow more bends.
Data that curves
Here is invented data: a car's fuel use (litres per 100 km) measured at different speeds.
import numpy as np
import matplotlib.pyplot as plt
speed = np.array([20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130])
fuel = np.array([9.1, 7.6, 6.4, 5.8, 5.4, 5.3, 5.5, 5.9, 6.4, 7.0, 7.9, 8.8])
plt.scatter(speed, fuel)
plt.xlabel("Speed (km/h)")
plt.ylabel("Fuel use (l/100 km)")
plt.show()
print("correlation:", np.corrcoef(speed, fuel)[0, 1].round(3))correlation: 0.079
The correlation is close to zero even though the relationship is obvious — the correlation coefficient only measures straight-line relationships. A U-shape needs a different model.
Fitting a polynomial with NumPy
np.polyfit(x, y, degree) finds the coefficients, and np.poly1d turns them into a function you can call:
import numpy as np
import matplotlib.pyplot as plt
speed = np.array([20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130])
fuel = np.array([9.1, 7.6, 6.4, 5.8, 5.4, 5.3, 5.5, 5.9, 6.4, 7.0, 7.9, 8.8])
coeffs = np.polyfit(speed, fuel, 2)
model = np.poly1d(coeffs)
a, b, c = coeffs
print(f"a = {a:.5f}, b = {b:.5f}, c = {c:.3f}")
smooth_x = np.linspace(20, 130, 100)
plt.scatter(speed, fuel)
plt.plot(smooth_x, model(smooth_x), color="red")
plt.xlabel("Speed (km/h)")
plt.ylabel("Fuel use (l/100 km)")
plt.show()
print("Curve drawn through the data")a = 0.00118, b = -0.17403, c = 11.770
Curve drawn through the data
np.linspace(20, 130, 100) makes 100 evenly spaced speeds, so the red curve looks smooth instead of being drawn as straight segments between the 12 data points.
R² and predictions
Is the curve a good fit? sklearn.metrics.r2_score compares the true values with the model's predictions:
import numpy as np
from sklearn.metrics import r2_score
speed = np.array([20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130])
fuel = np.array([9.1, 7.6, 6.4, 5.8, 5.4, 5.3, 5.5, 5.9, 6.4, 7.0, 7.9, 8.8])
for degree in [1, 2, 3]:
model = np.poly1d(np.polyfit(speed, fuel, degree))
print(f"degree {degree}: R^2 = {r2_score(fuel, model(speed)):.4f}")
best = np.poly1d(np.polyfit(speed, fuel, 2))
print(f"predicted fuel at 75 km/h: {best(75):.2f} l/100 km")degree 1: R^2 = 0.0063
degree 2: R^2 = 0.9740
degree 3: R^2 = 0.9986
predicted fuel at 75 km/h: 5.35 l/100 km
The straight line (degree 1) explains almost nothing, while degree 2 explains nearly everything. Degree 3 squeezes out a little more, but that gain is small compared with the jump from degree 1 to 2, and every extra degree makes the curve more likely to chase noise.
Polynomial regression in scikit-learn
scikit-learn does not have a separate polynomial model. Instead it creates new features (x², x³, …) with PolynomialFeatures and then fits an ordinary LinearRegression on them. The model is still linear in its coefficients — only the inputs are curved.
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
speed = np.array([20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130]).reshape(-1, 1)
fuel = np.array([9.1, 7.6, 6.4, 5.8, 5.4, 5.3, 5.5, 5.9, 6.4, 7.0, 7.9, 8.8])
poly = PolynomialFeatures(degree=2, include_bias=False)
X_poly = poly.fit_transform(speed)
print("new features for the first row:", X_poly[0])
print("feature names:", poly.get_feature_names_out(["speed"]))
model = LinearRegression().fit(X_poly, fuel)
print("R^2:", round(model.score(X_poly, fuel), 4))
print("75 km/h ->", model.predict(poly.transform([[75]])).round(2))new features for the first row: [ 20. 400.]
feature names: ['speed' 'speed^2']
R^2: 0.974
75 km/h -> [5.35]
When a curve is a bad idea
A high degree can twist itself through every point, including the noise. Such a model looks perfect on the data it has seen and fails on new data — it overfits:
import numpy as np
rng = np.random.default_rng(0)
x = np.linspace(0, 10, 10)
y = 2 * x + 1 + rng.normal(0, 2, size=10) # truly a line plus noise
for degree in [1, 9]:
model = np.poly1d(np.polyfit(x, y, degree))
print(f"degree {degree}: prediction at x=10.5 -> {model(10.5):8.2f}")
print("true value at x=10.5 is about", 2 * 10.5 + 1)degree 1: prediction at x=10.5 -> 21.54
degree 9: prediction at x=10.5 -> 34.62
true value at x=10.5 is about 22.0
The degree-9 curve goes through every point, but just past the data its prediction lands far from the true value, while the humble straight line is almost spot on. Choose the simplest degree that captures the pattern; the Train/Test and Overfitting lessons show how to make that choice with data instead of guesswork.
Test yourself
Which data is a good candidate for polynomial regression?
- Points along a straight rising line
- Points forming a U-shape
- Two unrelated random variables
- Category labels
What does PolynomialFeatures(degree=2, include_bias=False) produce from a single column x?
- Just x
- x and x²
- 1, x and x²
- x² only
Why can a very high polynomial degree be harmful?
- It is always slower to print
- It fits the noise and predicts badly on new data
- It cannot be plotted
- scikit-learn does not allow it