Lesson 3.2foundation3 h⚡ live demo

Linear regression

Least squares three ways: algebra, geometry and probability

Linear regression is the first model you can derive completely — closed form, gradient descent and maximum likelihood all give the same answer — and the last model you will ever fully understand. It is also a single neural-network layer with no activation (4.1 From perceptron to MLP; universal approximation), the inner loop of ridge regression (3.6 Regularization and generalization) and LoRA (8.2 Fine-tuning and PEFT), and the "linear probe" used to read concepts out of LLM activations (8.11 Interpretability: what is happening inside). Every derivation here is reused.

You'll be able to

  • Write the linear model in matrix form and derive the normal equations from the gradient of the MSE
  • Explain least squares as projection onto the column space of X and read the orthogonality condition
  • Derive the gradient-descent update, state when it converges, and explain why feature scaling speeds it up
  • Show that MSE is maximum likelihood under Gaussian noise and say what that assumption implies
  • Extend the model with polynomial/basis features and diagnose a fit with residual plots and R²
  • Implement the closed form and gradient descent in NumPy and check them against scikit-learn

Key ideas

  1. Linear regression predicts ŷ = Xw; the MSE is a convex quadratic bowl with a unique minimum when X has full column rank.
  2. Setting the gradient (2/n) Xᵀ(Xw − y) to zero gives the normal equations XᵀX w = Xᵀy; solve with lstsq, never with an explicit inverse.
  3. Geometrically, ŷ is the projection of y onto the column space of X; residuals are orthogonal to every feature and sum to zero.
Show 5 more key ideas
  1. Gradient descent converges on this problem for η < 2/λ_max; standardizing features makes the bowl round and descent fast.
  2. MSE is maximum likelihood under Gaussian noise; heavy-tailed noise calls for MAE or Huber loss.
  3. Linear means linear in the parameters: polynomial and basis features keep the math and add capacity.
  4. Diagnose fits with residual plots and report RMSE in the target's units next to R² = 1 − SSE/SST.
  5. The gradient form Xᵀ(ŷ − y) is reused unchanged by logistic regression and by every neural network's output layer.

Suggested path through this lesson