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²
Linear Regression predicts a continuous number by fitting the best straight line (or hyperplane) y = w^T x + b that minimizes prediction error.
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.
Linear Regression + Gradient Descent is the exact optimization skeleton of EVERY neural network and GLM!
Choosing MSE vs. Huber Loss in production pricing/ETA models prevents a handful of noisy outliers from skewing predictions for 99% of normal users.
Knowing why R² ALWAYS rises when you add pure random noise columns — and why Adjusted R² catches that — prevents shipping bloated, fake-improved models.
'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!
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?
- 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.
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)
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!
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 (): Best of both worlds — behaves like smooth when and robust linear when !
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!
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
To find the exact bottom of the MSE bowl, you have two routes:
- Closed-Form OLS (
w = (XᵀX)⁻¹Xᵀy/ SVD): Teleports straight to the exact bottom in 1 step! Awesome ford < 10,000features, crashes at whend = 1,000,000! - Gradient Descent: Walks downhill step-by-step via
w ← w − η · ∇L— scales effortlessly to billions of rows & parameters!
The Exact Vectorized Gradient of MSE
Why R² can be NEGATIVE on test data — and why Adjusted R² penalizes useless features!
Total leftover squared mistake made by YOUR regression line.
Pause & Check: Can R² on a held-out TEST set ever be NEGATIVE?
3. Regression Diagnostics & Assumptions
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)!).
4 Quick OLS Assumptions to Know for Interviews
- Linearity between features and target (fix: add
x², interactions, or trees). - Independence of errors (violated in time-series autocorrelation).
- Homoscedasticity (constant residual spread across predictions).
- No perfect multicollinearity (fix: drop duplicate columns or use Ridge in Chapter 6!).
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Because 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!
Watch Gradient Descent Tilt & Slide the Line Down the MSE Bowl
Left: live fitted line & crimson residual errors. Right: real-time MSE descent curve!
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!
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)")
np.linalg.inv(X.T @ X) @ X.T @ y when X has collinear columns.np.linalg.lstsq(X, y, rcond=None) or Ridge (+λI)!