Lesson 1 of 9
Ordinary Least Squares (OLS) Regression: Mathematical Mechanics & Assumptions
Ordinary Least Squares (OLS) is the cornerstone parametric regression algorithm. OLS finds the weight vector w that minimizes the sum of squared residuals: J(w) = ||y - Xw||². The closed-form analytical solution is the Normal Equation: w = (X^T X)^(-1) X^T y. Under the Gauss-Markov theorem, OLS is the Best Linear Unbiased Estimator (BLUE) if four core assumptions hold: linearity, strict exogeneity (E[ε|X]=0), spherical errors (homoscedasticity & no autocorrelation), and absence of perfect multicollinearity.
Analytical Normal Equation vs Gradient Descent in Scikit-Learn
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
# Generate synthetic linear data: y = 3.5 * x1 - 1.8 * x2 + 10.0 + noise
np.random.seed(42)
n = 500
X = np.random.uniform(0, 10, size=(n, 2))
true_w = np.array([3.5, -1.8])
true_intercept = 10.0
noise = np.random.normal(0, 1.0, size=n)
y = np.dot(X, true_w) + true_intercept + noise
# 1. CLOSED-FORM NORMAL EQUATION SOLVER FROM SCRATCH: w = (X^T X)^(-1) X^T y
# Prepend column of ones for intercept bias term
X_bias = np.column_stack([np.ones(n), X])
# Solve Normal Equation via Moore-Penrose pseudo-inverse for numerical stability
w_closed_form = np.linalg.pinv(X_bias.T @ X_bias) @ X_bias.T @ y
print("=== CLOSED-FORM NORMAL EQUATION SOLUTION ===")
print(f"Intercept (w0) : {w_closed_form[0]:.4f} (True: {true_intercept})")
print(f"Weights (w1, w2): {w_closed_form[1:].round(4)} (True: {true_w})")
# 2. SCIKIT-LEARN LINEAR REGRESSION ESTIMATOR
ols = LinearRegression(fit_intercept=True)
ols.fit(X, y)
print("\n=== SCIKIT-LEARN LINEAR REGRESSION ===")
print(f"Intercept : {ols.intercept_:.4f}")
print(f"Coefficients : {ols.coef_.round(4)}")
print(f"R^2 Score : {ols.score(X, y):.4f}")Pro Tip: When to Use SVD / Pseudo-Inverse vs Inversion
Never compute `np.linalg.inv(X.T @ X)` directly. If features have even mild collinearity, `X.T @ X` becomes ill-conditioned, and inversion produces huge numerical truncation errors. Always use `scipy.linalg.lstsq` or `np.linalg.pinv`, which uses Singular Value Decomposition (SVD) with singular value thresholding.
Simplest ML. y = mx + b. Minimize MSE.
Hands-On Challenge: Derive the Gradient of Squared Loss
Derive the matrix gradient `dJ/dw = -2 X^T (y - Xw)`. Implement Mini-Batch Stochastic Gradient Descent from scratch in NumPy, verifying that weights converge to the analytical OLS solution within 100 epochs.
Quick Quiz & Key Concept Checks
Common Pitfall: Extrapolating Beyond the Feature Support Domain
Linear regression makes unbounded predictions. If you train a model on house square footage from 800 to 4,000 sqft, predicting price for a 50,000 sqft stadium will produce wild, physically impossible values. Always check domain boundaries during inference.
Finished this lesson?