Curriculum02. Supervised LearningLesson 1 of 7

Linear Regression & Ordinary Least Squares

Deriving the normal equations, minimizing vertical residuals, and evaluating continuous fit.

22 min readBeginnerModule 02
01 // CORE INTUITION

Core Intuition: Balancing Vertical Springs

Imagine each observed data point (x(i),y(i))(x^{(i)}, y^{(i)}) nailed to a wooden board, connected to a rigid metal rod by a vertical elastic spring. Every spring pulls the rod up or down toward its nail.

When you release the rod, it settles at the exact angle and height where the total elastic potential energy of all springs is minimized. Because spring energy grows with the square of extension, a spring stretched twice as far pulls four times harder.

Takeaway:Ordinary Least Squares finds the unique line where all vertical spring forces balance to zero.
02 // THE PROBLEM IT SOLVES

The Problem It Solves: Continuous Prediction

Many engineering problems require predicting a continuous number rather than a category: server latency from request payload size, housing price from square footage, or energy demand from ambient temperature.

Lookup tables fail because they cannot interpolate between unseen inputs, and handcrafted threshold rules break whenever trends shift. Linear regression replaces brittle rules with a smooth parametric function y^=wx+b\hat{y} = w x + b learned directly from historical pairs.

Takeaway:Use linear regression when the target variable is continuous and scales approximately linearly with input features.
03 // STEP-BY-STEP MECHANISM

Step-by-Step Mechanism: Measuring Residuals

For each observation ii, the model predicts y^(i)=wx(i)+b\hat{y}^{(i)} = w x^{(i)} + b. The vertical gap ei=y(i)−y^(i)e_i = y^{(i)} - \hat{y}^{(i)} is the residual error.

Summing raw residuals fails because positive and negative errors cancel out. Taking the mean of squared residuals produces a smooth, strictly convex bowl J(w,b)J(w, b) with a single global minimum. Setting partial derivatives ∂J/∂w=0\partial J / \partial w = 0 and ∂J/∂b=0\partial J / \partial b = 0 yields the exact optimal slope and intercept in one closed-form step.

Takeaway:Squaring residuals eliminates sign cancellation and guarantees a single convex minimum.
04 // INTERACTIVE SANDBOX

Interactive Sandbox: Fit vs. Exact OLS

Drag the slope (ww) and intercept (bb) sliders in the visualizer to observe how vertical residual bars expand and shrink. Watch the Mean Squared Error (MSE) and R2R^2 scoreboard update in real time.

Click "Snap to OLS Optimum" to compute the exact analytical solution via computeOLS and compare your manual fit against the global minimum.

Ordinary Least Squares Engine
ŷ = 0.90x + 30MSE: 29R²: 0.996Exact OLS Optimum

Adjust slope (ww) and intercept (bb) or snap to the closed-form normal equation solution. Vertical coral segments show residuals (y−y^y - \hat{y}).

SLOPE (w)0.90
INTERCEPT (b)30
01753500180360Input feature xTarget y
Observed (x, y)
Model fit ŷ
Exact OLS optimum
Residual (y - ŷ)
Takeaway:Any deviation from the OLS parameters strictly increases MSE and lowers R2R^2.
05 // MATHEMATICAL FORMULATION

Mathematical Formulation: The Normal Equations

In vector notation, the Mean Squared Error objective is J(θ)=1m∥Xθ−y∥22J(\boldsymbol{\theta}) = \frac{1}{m} \|\mathbf{X}\boldsymbol{\theta} - \mathbf{y}\|_2^2, where mm is the number of training examples. Taking the matrix gradient ∇θJ=2mXT(Xθ−y)=0\nabla_{\boldsymbol{\theta}} J = \frac{2}{m} \mathbf{X}^T (\mathbf{X}\boldsymbol{\theta} - \mathbf{y}) = \mathbf{0} produces the normal equations directly without iterative stepping.

PRIMARY OBJECTIVE FORMULATION
Variable & Symbol Definitions
θ^\hat{\boldsymbol{\theta}}Optimal parameter vector [b,w1,…,wd]T[b, w_1, \dots, w_d]^T minimizing squared error
X\mathbf{X}Design matrix of shape (m,d+1)(m, d+1) with a leading column of 11s for the bias term
XT\mathbf{X}^TMatrix transpose of X\mathbf{X}, shape (d+1,m)(d+1, m)
(XTX)−1(\mathbf{X}^T \mathbf{X})^{-1}Inverse of the (d+1)×(d+1)(d+1) \times (d+1) feature covariance-like Gram matrix
y\mathbf{y}Observed ground-truth target vector of shape (m,1)(m, 1)
Takeaway:The normal equations project y\mathbf{y} orthogonally onto the column space of X\mathbf{X}.
06 // KEY ASSUMPTIONS

Key Assumptions: Gauss-Markov Conditions

OLS is the Best Linear Unbiased Estimator (BLUE) only when four structural assumptions hold:

1. Linearity: The true mean of yy is a linear combination of the features (or engineered polynomial basis features). 2. Zero Conditional Mean: Noise has zero expectation given inputs, E[ϵ∣X]=0\mathbb{E}[\epsilon \mid \mathbf{X}] = 0. 3. Homoscedasticity: Noise variance Var(ϵi)\text{Var}(\epsilon_i) stays constant across all input magnitudes. 4. No Perfect Multicollinearity: Columns of X\mathbf{X} are linearly independent so XTX\mathbf{X}^T\mathbf{X} remains invertible.

Takeaway:Always inspect a residual-vs-fitted plot to check for curvature or fanning variance.
07 // COMMON PITFALLS

Common Pitfalls: High-Leverage Outliers

Because OLS penalizes errors quadratically (ei2e_i^2), points far from the feature mean xˉ\bar{x} exert disproportionate torque on the fitted line. A single corrupted sensor reading at an extreme xx value can tilt the entire slope away from the true trend.

Similarly, duplicate or near-collinear features (such as temperature in both Celsius and Fahrenheit) make XTX\mathbf{X}^T\mathbf{X} singular or numerically unstable, causing weights to explode with opposite signs.

Algorithmic Checkpoint

Suppose one training point sits far to the right on the x-axis with a large vertical error. How does OLS respond compared to Mean Absolute Error (L1)?

Takeaway:Use Huber loss or Ridge (L2L_2) regularization when outliers or collinear features are present.
08 // COMPLEXITY

Computational Complexity: Closed-Form Limits

Solving the normal equations (XTX)−1XTy(\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^T\mathbf{y} requires O(d2m)O(d^2 m) operations to multiply XTX\mathbf{X}^T\mathbf{X} and O(d3)O(d^3) operations to invert the (d+1)×(d+1)(d+1) \times (d+1) matrix, with O(md+d2)O(md + d^2) memory.

When feature count dd is small (d<10,000d < 10{,}000), the closed-form solver finishes in milliseconds. For high-dimensional data (d≥105d \ge 10^5), matrix inversion becomes prohibitive, and iterative gradient descent (O(kmd)O(k m d) for kk epochs) is far faster. Prediction at inference time takes only O(d)O(d) operations.

Takeaway:Closed-form OLS scales linearly with samples mm but cubically with features dd.
09 // REAL-WORLD USE

Real-World Use: Elasticity & Baselines

In production engineering, linear regression serves two critical roles. First, it powers econometric and capacity-planning models where each weight wjw_j directly quantifies marginal impact (for example, milliseconds of tail latency added per kilobyte of payload).

Second, it acts as the mandatory baseline benchmark for any regression pipeline. If a complex gradient-boosted tree or neural network cannot outperform regularized linear regression on out-of-sample validation error, the added complexity is unjustified.

Takeaway:Always benchmark complex regressors against an interpretable linear baseline first.
10 // PRODUCTION CODE

Production Code: NumPy & scikit-learn

In practice, use SVD-based least squares (np.linalg.lstsq or sklearn.linear_model.LinearRegression) rather than explicitly inverting XTX\mathbf{X}^T\mathbf{X}, because SVD stays numerically stable even when features are nearly collinear.

Production Implementation
import numpy as np

def fit_ols(X: np.ndarray, y: np.ndarray) -> np.ndarray:
    # Prepend a bias column of 1s to the feature matrix
    X_b = np.c_[np.ones((X.shape[0], 1)), X]
    # Solve min ||X_b @ theta - y||_2 via SVD (numerically stable)
    theta, _, _, _ = np.linalg.lstsq(X_b, y, rcond=None)
    return theta

X = np.array([[1.0], [2.0], [3.0], [4.0]])
y = np.array([3.1, 4.9, 7.2, 8.9])
theta = fit_ols(X, y)  # [intercept, slope]
print(f"Intercept: {theta[0]:.3f}, Slope: {theta[1]:.3f}")
Implementation Walkthrough:

First, np.c_[np.ones(...), X] adds the intercept column so the bias term bb is learned alongside slope ww. Next, np.linalg.lstsq computes the minimum-norm least squares solution using Singular Value Decomposition instead of direct matrix inversion, avoiding division-by-zero crashes on collinear columns. In scikit-learn, LinearRegression wraps LAPACK dgelsd under the hood and exposes learned parameters via .intercept_ and .coef_.

Takeaway:Prefer SVD-based lstsq over naive np.linalg.inv(X.T @ X) in production code.