Chapter 12 of 42 · ~18 min read & lab+60 XP
Chapter 12 · Machine Learning

Polynomial Regression & Linear Assumptions: Curved Fits, Residuals & Homoscedasticity

How adding x², x³ lets a linear model bend around curves, how to read residual plots, and the 4 LINE assumptions of Linear Regression

What Is It?

Polynomial Regression fits curved relationships by expanding raw features into powers (x, x², x³) while still solving a linear model in the weights — and Residual Analysis checks whether a regression model's core LINE assumptions hold.

Why Is It Required?

Real-world phenomena (braking distance vs. speed, diminishing ad returns) are rarely straight lines, and violating Linear Regression assumptions (like non-constant error spread) makes confidence intervals and predictions unreliable.

Everyday Analogy: Bending a flexible wooden strip through curved road markers instead of forcing a rigid straight ruler across a hairpin turn.
Why ML Engineers & Data Scientists Actually Need This

Residual plots are the X-ray machine of regression — a 2-second scatter plot reveals non-linearity and variance blow-ups that a single RMSE score hides.

ML / AI Engineer

Polynomial & interaction terms (PolynomialFeatures(degree=2)) let fast linear models capture non-linear curves at microsecond serving latency.

Data Scientist

Checking homoscedasticity and residual normality is mandatory whenever stakeholders need trustworthy p-values or prediction intervals.

Interview & Debug Edge

Classic question: 'Why is Polynomial Regression still called a linear model, and what does a funnel-shaped residual plot mean?'

Step 0 · Test Your Gut Before Any Math!

In a residual plot (predicted value ŷ on the X-axis, residual y − ŷ on the Y-axis), what does a HEALTHY regression model look like?

What You Will Master in This Chapter
  • Explain why Polynomial Regression is still mathematically a 'linear model' (linear in the parameters w, non-linear in x).
  • Diagnose underfitting (degree 1) vs. sweet-spot fit (degree 2–3) vs. catastrophic overfitting (degree 12+).
  • Inspect a Residual Plot (ŷ vs. y − ŷ) to spot curved bias and heteroscedasticity (fan-shaped error spread).
  • Recall the 4 LINE assumptions of OLS Linear Regression: Linearity, Independence, Normality of residuals, Equal variance (Homoscedasticity).
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 2
ei=yi−y^ie_i = y_i - \hat{y}_iSay aloud:“Residual (prediction error)”
Plain-English Meaning
How far above or below the regression curve data point i sits.
Everyday Example
True price $320k, predicted $300k → residual e_i = +$20k.
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

You don't need a new algorithm to fit curves! By feeding [x, x², x³] into ordinary Linear Regression, the model stays linear in its weights w while drawing smooth curves in x-space. Just watch the degree — crank it too high and the curve violently wiggles through every noisy dot!

1. The 4 LINE Assumptions of Linear Regression

Everyday Story First (Zero Math Yet!)

Think of Linear Regression like a precision scale that promises accurate weights only if you place it on a flat floor, away from wind, and zero it first.

Remember the acronym LINE:

  1. L — Linearity: The true mean of yy is a linear function of your (possibly engineered) features. Check: No U-shape in the residual plot.
  2. I — Independence: Errors eie_i are independent across rows (violated in time-series autocorrelation!).
  3. N — Normality of Residuals: Residuals eie_i are roughly bell-shaped (mostly needed for small-sample confidence intervals & p-values, NOT for point prediction).
  4. E — Equal Variance (Homoscedasticity): Residual spread stays constant across all y^\hat{y}. If errors fan out like a megaphone (Heteroscedasticity), try log1p(y) or Weighted Least Squares!

2. Choosing Polynomial Degree Without Overfitting

With dd original features, degree-pp PolynomialFeatures creates (d+pp)\binom{d + p}{p} columns — which explodes rapidly!

  • Degree 1: Straight line (high bias if data is curved).
  • Degree 2–3: Smooth curves + pairwise interactions (usually the tabular sweet spot).
  • Degree 10+: Wild Runge oscillations between points (extreme variance!). Always pair PolynomialFeatures with StandardScaler (since x3x^3 is huge!) and Ridge/Lasso regularization.
Hands-On Mini-Lab · Slide Polynomial Degree d to Watch Underfit → Sweet Spot → Overfit!Sweet Spot (Generalizes!)
Train MSE: 0.015 (always drops!)
Unseen Test MSE: 0.021
“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

In ML, 'linear' refers to the parameters (weights) ww, not the raw input xx. Because y^=w0+w1x+w2x2\hat{y} = w_0 + w_1 x + w_2 x^2 is a straight weighted sum of w0,w1,w2w_0, w_1, w_2, the loss surface is still a single convex bowl with a unique global minimum!

Interactive Visual Lab
Lab Challenge: Watch how increasing polynomial degree moves from underfitting to overfitting on the learning curve.
Interactive Deep Lab · Learning Curve Doctor

Diagnose Both Learning Curves & Prescribe the Right ML Fix

TrainValTraining Set Size n →
Case A: Train Error 24%, Val Error 26% (Both Stuck High!)
Intuition Takeaway: Expand features into powers (x, x²) to capture curves linearly, inspect residual plots for U-shapes or megaphone variance, and always pair polynomial expansion with scaling + Ridge/Lasso.
Production NumPy & PyTorch Code Patterns
import numpy as np

# Compare Degree-1 (Linear) vs. Degree-2 (Polynomial) Fit + Residual Check
rng = np.random.default_rng(7)
x = np.linspace(-3, 3, 40)
y = 0.8 * x**2 - 1.2 * x + 2.0 + rng.normal(0, 0.4, size=len(x))

for deg in (1, 2, 10):
    coeffs = np.polyfit(x, y, deg)
    y_hat = np.polyval(coeffs, x)
    residuals = y - y_hat
    rmse = float(np.sqrt(np.mean(residuals ** 2)))
    print(f"Degree {deg:2d} | Train RMSE={rmse:.3f} | Max |residual|={np.abs(residuals).max():.3f}")
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Assuming Linear Regression requires the input features X themselves to be Normally distributed.
Best Practice: OLS assumes residuals (errors) are roughly normal for inference — NOT the input features X!
Chapter Mastery Check (+60 XP)
Score: 0 / 1
1You inspect a Linear Regression residual plot (ŷ vs. y − ŷ) and see a clear U-shape. What does this diagnose?

Apply What You Learned — Solve Matching Coding Problems