When data follows a curve, a straight line fits badly. Polynomial Regression adds powers of the feature (x², x³…) so a linear model can fit curves. A classic example: salary rising faster at higher job levels.
Prerequisites
The Idea
Instead of ŷ = b₀ + b₁x, we fit ŷ = b₀ + b₁x + b₂x² + … + bₙxⁿ. It is still “linear regression” because it is linear in the coefficients; we just give it extra columns x², x³.
Step 1: Data
import numpy as np
rng = np.random.default_rng(1)
level = np.arange(1, 11)
salary = (4000 * level**2 + 15000 + rng.normal(0, 8000, 10)).round(-2)
X = level.reshape(-1, 1)
print(salary)
[ 21800. 37600. 53600. 68600. 122200. 162600. 206700. 275600. 341900. 417400.]
Step 2: A Straight Line First
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
lin = LinearRegression().fit(X, salary)
print('linear R2', round(r2_score(salary, lin.predict(X)), 4), 'pred6.5', round(lin.predict([[6.5]])[0], 0))
Explanation: R² looks fine, but the line overestimates the middle levels and underestimates the top ones.
linear R2 0.9443 pred6.5 214771.0
Step 3: Polynomial Model
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
for d in [2, 3]:
pm = make_pipeline(PolynomialFeatures(degree=d), LinearRegression()).fit(X, salary)
print('deg', d, 'R2', round(r2_score(salary, pm.predict(X)), 4), 'pred6.5', round(pm.predict([[6.5]])[0], 0))
Explanation:
PolynomialFeatures(degree=2)turns x into [1, x, x²].make_pipelinechains the transformation and the model, so new inputs are transformed automatically.- Degree 2 fits almost perfectly and predicts about ₹1.85 lakh for level 6.5, much more sensible than the straight line’s ₹2.15 lakh. Degree 3 adds nothing here.
deg 2 R2 0.9986 pred6.5 184565.0 deg 3 R2 0.9986 pred6.5 185045.0
Step 4: Plot
import matplotlib.pyplot as plt
grid = np.linspace(1, 10, 100).reshape(-1, 1)
pm = make_pipeline(PolynomialFeatures(2), LinearRegression()).fit(X, salary)
plt.scatter(X, salary, label='Data')
plt.plot(grid, lin.predict(grid), label='Linear')
plt.plot(grid, pm.predict(grid), label='Degree 2')
plt.legend(); plt.show()
Choosing the Degree
A higher degree always fits the training data better, but too high a degree wiggles through every point and predicts badly on new data (overfitting). Choose the degree with cross-validation, and keep it as low as possible. Note that R² here is measured on training data, which is why we keep the lowest degree that works.
Common Errors
| Problem | Cause and fix |
|---|---|
| Huge or wild predictions outside the data range | Polynomials extrapolate badly; avoid predicting far beyond the training range. |
| Numerical warnings with high degree | Scale features (StandardScaler) before PolynomialFeatures. |
Practice Exercises
- Try degree 8 and plot it. What happens between the points?
- Use cross_val_score to pick the best degree.
Interview Questions
Q: Is polynomial regression linear?
Yes, linear in the parameters, even though the curve is non-linear in x.
Q: Risk of a high degree?
Overfitting and bad extrapolation.
Summary
Add polynomial features with PolynomialFeatures, fit LinearRegression in a pipeline, and choose the smallest degree that fits well on validation data.
Machine Learning Tutorials, Courses and Certifications