Module A · Lecture 02

Machine Learning Foundations Recap

Before we build a single neuron, we recall what "learning from data" formally means — and the one tradeoff that governs every model you will ever train.

⏱ ~55 min 🧩 Builds on: Lecture 1 🎯 CO1
🧭 Why we're learning this now

Before we design a single neuron or write a single line of training code, we need shared vocabulary: what does "learning" mean in a way precise enough to build machinery around? This lecture is that vocabulary — train/test splits, overfitting, bias and variance — and every later lecture will assume you have it.

  • Distinguish machine learning from explicit programming, and supervised, unsupervised and reinforcement learning from each other with concrete examples.
  • Describe the general ML pipeline: data → features → model → loss → optimization → evaluation.
  • Explain why data is split into train/validation/test sets, and what each split is for.
  • Recognize underfitting and overfitting visually and diagnose them from training/test error patterns.
  • State the bias-variance decomposition of expected test error and compute it for a small numeric example.
  • Preview L1/L2 regularization as a tool for controlling model complexity.

1. What Is Machine Learning?

Classical programming means writing explicit rules: a human decides the logic, the computer executes it. Machine learning inverts this. We show the computer many examples of inputs and their correct outputs, and ask it to learn a function \(f\) that maps new, unseen inputs to correct outputs — without a human ever writing down the rule explicitly. Formally, given a dataset of examples, we search over a family of candidate functions (a "hypothesis space") for the member that best explains the data and, crucially, generalizes to data it has not seen.

Machine learning problems are usually grouped into three families:

Three families of learning
  • Supervised learning. Every training example comes with a correct label. Example: given photos labeled "cat" or "dog", learn to classify new photos. Example: given house features and sale prices, learn to predict the price of a new house.
  • Unsupervised learning. No labels are given — the goal is to find structure in the data itself. Example: group customers into segments by purchasing behavior (clustering, Lecture 21). Example: compress images into a smaller representation without being told what's "important" (autoencoders, Lectures 23–24).
  • Reinforcement learning. An agent takes actions in an environment and receives rewards or penalties, learning a policy that maximizes long-run reward. Example: a game-playing agent that learns from wins and losses rather than labeled "correct moves."

Almost everything in this course — from Lecture 3's perceptron through Lecture 20's Transformers — is supervised learning. Lectures 21–24 return to unsupervised methods.

2. The General ML Pipeline

Nearly every supervised learning system, no matter how complex, is built from the same six stages:

StageWhat happens
1. DataCollect labeled examples representative of the problem you want to solve.
2. FeaturesTurn raw data (pixels, text, sensor readings) into a numeric representation the model can consume.
3. ModelChoose a family of functions with adjustable parameters — a line, a decision tree, or (starting Lecture 3) a network of neurons.
4. LossDefine a number that measures how wrong the model's current predictions are.
5. OptimizationAdjust the model's parameters to make the loss smaller, usually by some form of gradient descent.
6. EvaluationMeasure how well the trained model performs on data it never trained on.
Where this course is headed

We are introducing "loss" and "evaluation" informally here just so the pipeline makes sense as a whole. Loss functions are formalized rigorously in Lecture 6 (cross-entropy, probability), and evaluation metrics get their own full treatment in Lecture 10. Optimization is the subject of Lectures 7–9.

3. Train / Validation / Test Splits

A model that has simply memorized its training data is useless — we care about performance on new, unseen inputs, a property called generalization. To measure generalization honestly, we never evaluate a model on the same data it was trained on. Instead we partition the available data into three disjoint sets:

  • Training set — the data the model's parameters are actually fit to.
  • Validation set — held-out data used to tune choices the training process itself doesn't optimize (hyperparameters: learning rate, network size, regularization strength) and to decide when to stop training.
  • Test set — touched exactly once, at the very end, to report an unbiased estimate of real-world performance. If you tune anything based on the test set, it silently becomes a second validation set and its number is no longer trustworthy.

A common split for moderate-sized datasets is roughly 70/15/15 or 80/10/10 (train/validation/test), though the right proportions depend on how much data you have overall.

4. Underfitting, Good Fit, and Overfitting

Every model has some amount of capacity — its ability to represent complicated functions. Too little capacity, and the model cannot capture the real pattern in the data (underfitting). Too much capacity relative to the amount of data, and the model starts fitting the noise in the training set instead of the underlying trend (overfitting). Both hurt generalization, for opposite reasons. The figures below show the same 11 noisy data points fit by three models of increasing complexity: a straight line, a smooth quadratic, and a high-degree polynomial that wiggles through nearly every point.

Underfitting. A straight line is too simple to capture the hump in the data — high error on both training and test data.
Good fit. A smooth quadratic curve tracks the trend without chasing individual noisy points.
Overfitting. A high-degree polynomial passes almost exactly through every training point, but wiggles wildly between them — it has memorized noise, not learned the trend.
⚠ How to tell them apart in practice

You rarely get to see the curve like this with real, high-dimensional data. Instead you diagnose fitting problems from numbers: underfitting shows high error on both the training and validation sets. Overfitting shows low training error but high validation error — the gap between the two is the tell-tale sign.

5. The Bias-Variance Tradeoff

Underfitting and overfitting are two symptoms of one underlying tradeoff. If we imagine retraining the same model architecture on many different random samples of training data, its expected error on a new test point decomposes into three additive parts:

$$\mathbb{E}\big[(y-\hat f(x))^2\big] \;=\; \underbrace{\big(\mathbb{E}[\hat f(x)]-f(x)\big)^2}_{\text{Bias}^2} \;+\; \underbrace{\mathbb{E}\big[(\hat f(x)-\mathbb{E}[\hat f(x)])^2\big]}_{\text{Variance}} \;+\; \underbrace{\sigma^2}_{\text{Irreducible noise}}$$
Reading the three terms
  • Bias — error from the model family being too simple to represent the true function \(f(x)\), no matter how much data it sees. High bias ≈ underfitting.
  • Variance — how much the fitted model \(\hat f\) changes if you retrain it on a different random sample of training data. High variance ≈ overfitting: the model is unstable and overly sensitive to the specific noise in whatever data it happened to see.
  • Irreducible noise \(\sigma^2\) — randomness inherent in the data-generating process itself, which no model can ever eliminate.
Where does this decomposition actually come from?

This isn't an assumption to take on faith — it falls straight out of expectation algebra in two short steps. Write the true label as \(y=f(x)+\varepsilon\), where \(\varepsilon\) is random noise with \(\mathbb E[\varepsilon]=0\), \(\text{Var}(\varepsilon)=\sigma^2\), independent of the fitted model \(\hat f\) (which was trained on separate training data and never sees this test point's noise).

Step 1 — split off the irreducible noise. Substitute \(y=f(x)+\varepsilon\) and expand the square:

$$\mathbb E[(y-\hat f)^2]=\mathbb E[((f(x)-\hat f)+\varepsilon)^2]=\mathbb E[(f(x)-\hat f)^2]+2\,\mathbb E[(f(x)-\hat f)\varepsilon]+\mathbb E[\varepsilon^2]$$

Because \(\varepsilon\) is independent of \(\hat f\) and \(\mathbb E[\varepsilon]=0\), the cross term \(\mathbb E[(f(x)-\hat f)\varepsilon]\) factors into \(\mathbb E[f(x)-\hat f]\cdot\mathbb E[\varepsilon]\), which is exactly 0. And \(\mathbb E[\varepsilon^2]=\text{Var}(\varepsilon)=\sigma^2\) (since \(\mathbb E[\varepsilon]=0\)). That leaves \(\mathbb E[(y-\hat f)^2]=\mathbb E[(f(x)-\hat f)^2]+\sigma^2\).

Step 2 — split the remaining term into bias² and variance. Add and subtract \(\mathbb E[\hat f]\) inside the square, then expand exactly the same way:

$$\mathbb E[(f(x)-\hat f)^2]=\mathbb E\big[\big((f(x)-\mathbb E[\hat f])+(\mathbb E[\hat f]-\hat f)\big)^2\big]=(f(x)-\mathbb E[\hat f])^2+2(f(x)-\mathbb E[\hat f])\underbrace{\mathbb E[\mathbb E[\hat f]-\hat f]}_{=\,0}+\mathbb E[(\hat f-\mathbb E[\hat f])^2]$$

The middle term vanishes again, because \(\mathbb E[\mathbb E[\hat f]-\hat f]=\mathbb E[\hat f]-\mathbb E[\hat f]=0\) by definition — leaving exactly \(\text{Bias}^2+\text{Variance}\). Chain the two steps together and the full decomposition falls out: \(\mathbb E[(y-\hat f)^2]=\text{Bias}^2+\text{Variance}+\sigma^2\) — nothing was assumed beyond \(y=f(x)+\varepsilon\) and ordinary expectation algebra.

Simple models (a straight line) tend to have high bias and low variance. Complex models (a high-degree polynomial, or later, a very large neural network) tend to have low bias and high variance. The best generalizing model sits at the sweet spot that minimizes the sum of all three terms — not the model with the lowest training error, and not the simplest model either.

🔢 Worked example: computing bias² + variance by hand

Suppose the true value we're trying to predict at some test point is \(f(x)=4.0\), and irreducible noise is known to be \(\sigma^2=0.05\). We train the same model architecture on four different random training sets and get four different predictions at that point:

$$\hat y_1=3.6,\quad \hat y_2=4.5,\quad \hat y_3=3.9,\quad \hat y_4=4.2$$

Step 1 — mean prediction: $$\bar y=\frac{3.6+4.5+3.9+4.2}{4}=\frac{16.2}{4}=4.05$$

Step 2 — bias: $$\text{Bias}=\bar y-f(x)=4.05-4.0=0.05 \qquad \text{Bias}^2=0.0025$$

Step 3 — variance: average squared deviation of each prediction from the mean prediction:

$$\text{Var}=\frac{(3.6{-}4.05)^2+(4.5{-}4.05)^2+(3.9{-}4.05)^2+(4.2{-}4.05)^2}{4}=\frac{0.2025+0.2025+0.0225+0.0225}{4}=0.1125$$

Step 4 — total expected error: $$\text{Bias}^2+\text{Var}+\sigma^2 = 0.0025+0.1125+0.05=\mathbf{0.165}$$

Notice bias here is small (0.05) but variance is large (0.1125) — this model is closer to the overfitting end of the tradeoff: its predictions swing considerably depending on which training set it happened to see.

6. Regularization: A Quick Preview

If overfitting comes from a model having too much freedom relative to its data, one fix is to explicitly discourage that freedom during training. Regularization adds a penalty term to the loss that grows with the size of the model's weights, trading a little training accuracy for a model that generalizes better:

$$L_{\text{regularized}} = L_{\text{original}} + \lambda \cdot R(w)$$
  • L2 regularization (weight decay): \(R(w)=\sum_i w_i^2\) — penalizes large weights smoothly, shrinking all of them somewhat.
  • L1 regularization: \(R(w)=\sum_i |w_i|\) — tends to push many weights to exactly zero, producing sparse models.
  • \(\lambda\) is a hyperparameter controlling how strongly complexity is penalized — chosen using the validation set, never the test set.

We are only previewing this idea now. It resurfaces with real teeth in Lecture 23, where the "sparse autoencoder" enforces an L1-style penalty directly on hidden-layer activations rather than on weights.

7. Summary

Key takeaways
  • Machine learning replaces hand-written rules with a function learned from labeled (supervised), unlabeled (unsupervised), or reward-driven (reinforcement) data.
  • Every supervised model follows the same pipeline: data → features → model → loss → optimization → evaluation.
  • Train/validation/test splits exist to measure generalization honestly — never tune on the test set.
  • Underfitting (high bias) and overfitting (high variance) are the two failure modes of model capacity; the bias-variance decomposition makes this tradeoff precise and computable.
  • Regularization (L1/L2) is one of the main tools for controlling this tradeoff — a concept we will meet again, formalized differently, when we build sparse autoencoders in Lecture 23.

8. Code: Underfitting vs. Overfitting on Synthetic Data

The script below generates the same kind of noisy, hump-shaped synthetic dataset used in Section 4, fits a degree-1 (underfit), degree-2 (good fit), and degree-12 (overfit) polynomial regression with scikit-learn, and prints the training-set mean squared error for each — watch it fall as the degree increases, even as the fit visually gets worse on new data.

lecture-02-under-overfit.py
import numpy as np
from numpy.polynomial import polynomial as P
from sklearn.metrics import mean_squared_error

rng = np.random.default_rng(0)

# ---- synthetic data: a mild "hump" shape plus noise ----
X = np.linspace(0, 10, 11)
true_y = -0.15 * (X - 4.5) ** 2 + 4.5
y = true_y + rng.normal(0, 0.3, size=X.shape)

def fit_and_eval(degree):
    coefs = np.polyfit(X, y, degree)          # highest power first
    y_hat = np.polyval(coefs, X)
    mse = mean_squared_error(y, y_hat)
    return coefs, mse

print(f"{'Degree':<8}{'Model':<12}{'Train MSE':>10}")
for degree, name in [(1, "Underfit"), (2, "Good fit"), (12, "Overfit")]:
    _, mse = fit_and_eval(degree)
    print(f"{degree:<8}{name:<12}{mse:>10.4f}")

# A degree-12 polynomial on 11 points interpolates almost exactly (near-zero
# training error) but will swing wildly between the training x-values --
# exactly the "memorized noise" behaviour shown in the lecture figure.
# Try evaluating each fitted polynomial at a dense grid (e.g. np.linspace(0,10,200))
# and plotting it against X, y with matplotlib to see this directly.

⬇ Download lecture-02-under-overfit.py   More resources for this lecture →