Chapter 11 of 42 · ~26 min read & lab+65 XP
Chapter 11 · Machine Learning

Linear Regression, Loss Functions (MSE/MAE/Huber) & Gradient Descent

Best-fit lines, why MSE hates outliers while MAE/Huber stay calm, Closed-Form OLS vs. Mini-Batch GD, and R² / Adjusted R²

What Is It?

Linear Regression predicts a continuous number by fitting the best straight line (or hyperplane) y = w^T x + b that minimizes prediction error.

Why Is It Required?

It is the fastest, most interpretable baseline for predicting prices, revenue, or demand—and introduces loss functions and gradient descent used across all of AI.

Everyday Analogy: Stretching a taut rubber band through a cloud of scattered house-price dots so the total vertical tug from all dots is as small as possible.
Why ML Engineers & Data Scientists Actually Need This

Linear Regression + Gradient Descent is the exact optimization skeleton of EVERY neural network and GLM!

ML / AI Engineer

Choosing MSE vs. Huber Loss in production pricing/ETA models prevents a handful of noisy outliers from skewing predictions for 99% of normal users.

Data Scientist

Knowing why R² ALWAYS rises when you add pure random noise columns — and why Adjusted R² catches that — prevents shipping bloated, fake-improved models.

Interview & Debug Edge

'Why does MSE learn the conditional mean while MAE learns the conditional median?' and 'Closed-form OLS vs. Gradient Descent trade-offs' are classic ML screens!

Step 0 · Test Your Gut Before Any Math!

You have 5 house prices: [$200k, $220k, $240k, $260k, $2,000k]. If you predict ONE constant number ŷ to minimize MAE (Mean Absolute Error), what exact number wins?

What You Will Master in This Chapter
  • Formulate Linear Regression ŷ = Xw + b and interpret every coefficient wⱼ as 'expected change in y per +1 unit of xⱼ holding other features fixed'.
  • Choose accurately between MSE (predicts conditional mean, outlier-sensitive), MAE (predicts conditional median, robust), and Huber Loss.
  • Compare Closed-Form OLS ((XᵀX)⁻¹Xᵀy / SVD) vs. Batch / Mini-Batch / Stochastic Gradient Descent.
  • Evaluate regression models using RMSE, MAE, R², Adjusted R² (penalizing useless features!), and safe MAPE.
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
ŷ = wᵀx + bSay aloud:“Linear Prediction”
Plain-English Meaning
Multiply each feature xⱼ by its learned slope wⱼ, add them up, and shift by baseline intercept b.
Everyday Example
Price = $200 × SqFt + $50,000.
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Before building deep neural networks, master the cleanest supervised algorithm in existence: Linear Regression. Draw the best straight line (or hyperplane) through noisy data by minimizing a Loss Function — either in 1 shot via OLS/SVD or iteratively via Gradient Descent!

1. Residuals & The 3 Regression Loss Functions (MSE vs. MAE vs. Huber)

Everyday Story First (Zero Math Yet!)

Every prediction has a vertical gap called a Residual eᵢ = yᵢ − ŷᵢ. How should we penalize residuals? If we square them (MSE), one extreme data-entry typo ($2,000k) explodes into a million-times-bigger penalty and hijacks your whole line! Drag the outlier slider below to see MSE, MAE, and Huber Loss (quadratic near 0 for smooth gradients, linear in the tails for outlier immunity!) compete live!

MSE (e² · outlier sensitive)MAE (|e| · robust)Huber (best of both!)Prediction Residual e = y − ŷ (0 = exact hit)
Figure 5.2 — MSE vs. MAE vs. Huber Loss: MSE grows quadratically (hijacked by outliers), MAE grows linearly (calm under outliers, corner at 0), and Huber smoothly combines both!

When to Pick Each Regression Loss

  • MSE / RMSE: Clean Gaussian noise, big mistakes are genuinely catastrophic (e.g., structural safety, financial risk).
  • MAE: Heavy outliers or skewed targets where you want the conditional median.
  • Huber Loss (δ\delta): Best of both worlds — behaves like smooth 12e2\frac{1}{2}e^2 when ∣e∣≤δ|e| \le \delta and robust linear δ(∣e∣−12δ)\delta(|e| - \frac{1}{2}\delta) when ∣e∣>δ|e| > \delta!
Hands-On Mini-Lab · Drag 1 Mansion Outlier & Watch MSE Get Hijacked!

Four normal homes cost [$200k, $220k, $240k, $260k]. Drag the 5th home's price up to $2,000k and watch which loss function stays calm!

MSE Optimal (= Mean)
$284k
Pulled wildly upward!
MAE Optimal (= Median)
$240k
100% immune to outlier!
Huber Loss (Smooth)
$253k
Smooth + outlier-resistant!
Try It YourselfWarm-Up

True values are y = [10, 20, 30] and predictions are ŷ = [12, 18, 36]. Compute both MAE and MSE.

2. Closed-Form OLS vs. Batch / Mini-Batch / Stochastic GD

Everyday Story First (Zero Math Yet!)

To find the exact bottom of the MSE bowl, you have two routes:

  1. Closed-Form OLS (w = (XᵀX)⁻¹Xᵀy / SVD): Teleports straight to the exact bottom in 1 step! Awesome for d < 10,000 features, crashes at O(d3)O(d^3) when d = 1,000,000!
  2. Gradient Descent: Walks downhill step-by-step via w ← w − η · ∇L — scales effortlessly to billions of rows & parameters!
Batch GDAll N rows per step✓ Smooth exact gradient• Too slow for 10M rowsMini-Batch GDB = 32–512 rows/step✓ GPU-fast + stable (Default!)• Small tuning of batch BStochastic (SGD)1 single row per step✓ Escapes shallow traps• Noisy zigzag updates
Figure 5.3 — Batch vs. Mini-Batch vs. Stochastic Gradient Descent: Batch is smooth but slow on 10M rows; Mini-Batch balances fast GPU vectorization with helpful escaping noise.

The Exact Vectorized Gradient of MSE

L(w,b)=1n∑i=1n(y^i−yi)2  ⟹  ∇wL=2nX⊤(y^−y),∇bL=2n∑i=1n(y^i−yi)\mathcal{L}(\mathbf{w}, b) = \frac{1}{n} \sum_{i=1}^n (\hat{y}_i - y_i)^2 \quad\implies\quad \nabla_{\mathbf{w}} \mathcal{L} = \frac{2}{n} X^\top (\hat{\mathbf{y}} - \mathbf{y}), \qquad \nabla_b \mathcal{L} = \frac{2}{n} \sum_{i=1}^n (\hat{y}_i - y_i)

Formula Anatomy · Click Any Colored Piece to Decode It
R² & Adjusted R²: R² = 1 − (SS_res / SS_tot)

Why R² can be NEGATIVE on test data — and why Adjusted R² penalizes useless features!

Your Model's Squared Error

Total leftover squared mistake made by YOUR regression line.

In our example: Small SS_res = tight fit!
Put it together with real numbers: If your model's Test SS_res is LARGER than Dummy SS_tot, R² = 1 − (>1) < 0 (strictly negative — worse than predicting the average)!
Pause & Check · Quick Intuition Pulse

Pause & Check: Can R² on a held-out TEST set ever be NEGATIVE?

3. Regression Diagnostics & Assumptions

Everyday Story First (Zero Math Yet!)

Before trusting Linear Regression coefficients, always plot Residuals (y − ŷ) vs. Predictions (ŷ)! If the residuals look like a random cloud centered at 0, your linear model nailed the pattern. If they form a U-shape, you missed a non-linear curve (add polynomial/log terms!); if they form a megaphone/funnel, variance grows with ŷ (heteroscedasticity — try log1p(y)!).

eᵢ = yᵢ − ŷᵢŷ = wx + b
Figure 5.1 — Ordinary Least Squares (OLS): minimizes the sum of SQUARED vertical distances (residuals eᵢ = yᵢ − ŷᵢ) from every data point to the line.

4 Quick OLS Assumptions to Know for Interviews

  1. Linearity between features and target (fix: add x², interactions, or trees).
  2. Independence of errors (violated in time-series autocorrelation).
  3. Homoscedasticity (constant residual spread across predictions).
  4. No perfect multicollinearity (fix: drop duplicate columns or use Ridge in Chapter 6!).
“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.

Because MAPE=1n∑∣yi−y^iyi∣\text{MAPE} = \frac{1}{n}\sum \left|\frac{y_i - \hat{y}_i}{y_i}\right| divides by yᵢ! If a single store sells 0 units today, MAPE divides by 0 and explodes to ∞! Always guard with eps or use WAPE (Σ|y − ŷ| / Σ|y|) or sMAPE!

Interactive Visual Lab
Lab Challenge: Tune slope w & intercept b (or click Run 25 Gradient Descent Steps) in the Linear Regression Deep Lab until MSE drops below 0.25!
Interactive Animation • Linear Regression & Gradient Descent

Watch Gradient Descent Tilt & Slide the Line Down the MSE Bowl

Left: live fitted line & crimson residual errors. Right: real-time MSE descent curve!

MSE = 50.020
Fitted Line ŷ = wx + b & ResidualsMSE Loss vs. Gradient Descent Step
0%
Step 0/25
Live parameters: w = 0.20, b = 0.40 — notice how large vertical residual springs pull the line rapidly in early steps, then settle gently at the OLS optimum (w ≈ 1.88, b ≈ 0.99)!
Intuition Takeaway: MSE targets the conditional mean (outlier-sensitive), MAE targets the median (robust), Huber smoothly blends both; use OLS/SVD for small d and Mini-Batch GD at scale, and track Adjusted R² / Val RMSE!
Where This Powers Real ML, Deep Learning & Generative AI

Dynamic Pricing & Demand Forecasting

Fast linear/Huber models establish interpretable elasticity baselines (price → units sold) before layering GBDTs.

CUPED Variance Reduction in A/B Testing

Meta, Netflix, and Booking run OLS regression of post-experiment metrics on pre-experiment covariates to slash A/B test runtimes by 50%!

Delivery ETA & Latency Prediction

Huber loss prevents rare traffic accidents or network stalls from pulling normal delivery estimates upward.

Neural Network Training Loop

Mini-Batch Gradient Descent on MSE is the exact same forward → loss → backward → step loop powering PyTorch!

Production NumPy & PyTorch Code Patterns
import numpy as np

# Batch Gradient Descent for Linear Regression from scratch (vectorized!)
rng = np.random.default_rng(42)
X = rng.normal(size=(300, 2))
y = 3.5 * X[:, 0] - 1.2 * X[:, 1] + 5.0 + rng.normal(scale=0.5, size=300)

w, b, lr = np.zeros(2), 0.0, 0.1
for step in range(200):
    err = (X @ w + b) - y
    w -= lr * (2.0 / len(X)) * (X.T @ err)
    b -= lr * (2.0 / len(X)) * float(np.sum(err))

print(f"Learned w={np.round(w, 3)} (true [3.5, -1.2]), b={b:.3f} (true 5.0)")
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Claiming R² is always between 0 and 1.
Best Practice: On unseen Test sets (or without an intercept), R² can be strictly NEGATIVE whenever your model loses to predicting the constant mean!
Trap #2: Comparing two models with different numbers of features using raw Training R².
Best Practice: Adding ANY random column increases Training R² — always compare Validation RMSE or Adjusted R²!
Trap #3: Using np.linalg.inv(X.T @ X) @ X.T @ y when X has collinear columns.
Best Practice: Use SVD-based np.linalg.lstsq(X, y, rcond=None) or Ridge (+λI)!
Chapter Mastery Check (+65 XP)
Score: 0 / 5
11. Which loss function is uniquely minimized by the conditional MEDIAN?
22. What happens to Training R² when you add 5 columns of pure random Gaussian noise to OLS?
33. When is Huber Loss preferred over both MSE and MAE?
44. Can Test-Set R² be negative?
55. Why do ML practitioners use Mini-Batch GD instead of Full-Batch GD on 50 million rows?

Apply What You Learned — Solve Matching Coding Problems