↓ Skip to main content
  1. Engineering Notes & Articles/

How Do Machines "Learn"? — Statistical Learning Theory & Empirical Risk Minimization

Machine Learning Fundamentals - This article is part of a series.
Part 1: This Article

1. The Core Problem: Why Explicit Programming Breaks Down
#

Classical software engineering relies on explicit rules. If you want to convert Celsius to Fahrenheit or route an HTTP packet, you write a deterministic function $f(x)$ derived from known physical laws or human-designed specifications.

That paradigm collapses when the mapping between input and output is either too complex to articulate or corrupted by stochastic noise. Consider classifying a 128×128 grayscale image of a handwritten digit, predicting equipment failure from multi-channel sensor drift, or distinguishing spam from legitimate email. You cannot write a clean sequence of if-else statements to capture all valid variations of the digit “4” across lighting, stroke thickness, and rotation.

Machine learning flips the workflow. Instead of hand-crafting the function $f$, we provide data generated by an unknown process and design an algorithm that searches for an approximation of $f$.

To move beyond metaphors about “artificial brains,” we need a rigorous definition of what learning actually means. Tom Mitchell (1997) formalized it cleanly:

“A computer program is said to learn from experience $E$ with respect to some class of tasks $T$ and performance measure $P$, if its performance at tasks in $T$, as measured by $P$, improves with experience $E$.”

While Mitchell’s $(T, P, E)$ framework defines the engineering specification of a learning system, it does not tell us how to guarantee that a system trained on finite data will work on unseen inputs. Answering that question requires Statistical Learning Theory, pioneered largely by Vladimir Vapnik and Alexey Chervonenkis.


2. Conceptual Intuition: Memorization vs. Generalization
#

Imagine a student preparing for a physics exam using a practice set of 20 solved problems.

If the student builds a lookup table memorizing every exact question and its corresponding numerical answer, their score on the practice set will be 100%. Yet on the real exam—where the phrasing and initial conditions change—they will fail completely. Memorization achieves zero error on past observations while learning nothing about the underlying mechanics.

A learning machine faces the exact same dilemma:

  • We only ever observe a finite, noisy sample of the world (the training set).
  • We care exclusively about performance on unseen future data drawn from the same underlying process.

In statistical learning, this gap between past performance and future performance is the central object of study. Learning is not the act of fitting data; it is the act of generalizing from finite data under uncertainty.


Underfitting vs. overfitting and empirical risk vs. true risk

Figure 1. Left: polynomial fits of degree 1, 3, and 15 on 20 noisy samples. Right: empirical risk keeps falling with capacity while true risk rebounds above the Bayes noise floor.

3. Mathematical Formulation: True Risk vs. Empirical Risk
#

The Statistical Setup
#

Formalize the learning environment with four components:

  1. Input space $\mathcal{X}$ (e.g., $\mathbb{R}^d$, representing feature vectors) and output space $\mathcal{Y}$ (e.g., $\mathbb{R}$ for regression, or $\{0, 1\}$ for binary classification).
  2. An unknown joint probability distribution $P(X, Y)$ over $\mathcal{X} \times \mathcal{Y}$. This distribution encodes both the true relationship between inputs and outputs and any irreducible measurement noise. Crucially, the learning algorithm never sees $P(X, Y)$ directly.
  3. A training dataset $S = \{(x_1, y_1), (x_2, y_2), \dots, (x_n, y_n)\}$, assumed to be drawn independently and identically distributed (i.i.d.) from $P(X, Y)$.
  4. A hypothesis space $\mathcal{H}$, which is the set of candidate functions $h: \mathcal{X} \to \mathcal{Y}$ that the algorithm is allowed to consider (for instance, the set of all linear functions, or the set of all decision trees of depth 5).

To quantify how wrong a prediction $h(x)$ is compared to the ground truth $y$, we define a non-negative loss function:

$$L: \mathcal{Y} \times \mathcal{Y} \to \mathbb{R}_{\ge 0}$$

Common choices include squared error $L(h(x), y) = (h(x) - y)^2$ for regression and $0\text{-}1$ loss $L(h(x), y) = \mathbb{I}[h(x) \neq y]$ for classification.

True Risk (Expected Risk)
#

The ultimate goal of learning is to pick a hypothesis $h \in \mathcal{H}$ that minimizes the True Risk (or expected risk)—the expected loss over the entire unknown distribution $P(X, Y)$:

$$R(h) = \mathbb{E}_{(x, y) \sim P}\big[ L(h(x), y) \big] = \int_{\mathcal{X} \times \mathcal{Y}} L(h(x), y) \, dP(x, y)$$

There is an immediate roadblock: $R(h)$ cannot be computed, because $P(X, Y)$ is unknown.

Empirical Risk Minimization (ERM)
#

Since we cannot integrate over $P(X, Y)$, we replace the theoretical expectation with the sample average over our finite training set $S$. This quantity is the Empirical Risk:

$$\hat{R}_n(h) = \frac{1}{n} \sum_{i=1}^{n} L(h(x_i), y_i)$$

The Empirical Risk Minimization (ERM) principle (Vapnik, 1999) selects the hypothesis that minimizes this observable proxy:

$$\hat{h}_{\text{ERM}} = \arg\min_{h \in \mathcal{H}} \hat{R}_n(h)$$

When Does ERM Fail?
#

By the Law of Large Numbers, for any single fixed hypothesis $h$, $\hat{R}_n(h) \to R(h)$ as $n \to \infty$. However, ERM does not evaluate a single fixed hypothesis—it searches across an entire space $\mathcal{H}$ to find the lowest training error.

If $\mathcal{H}$ is unrestricted (containing every possible function from $\mathcal{X}$ to $\mathcal{Y}$), ERM will simply construct a lookup table:

$$h_{\text{mem}}(x) = \begin{cases} y_i & \text{if } x = x_i \in S \\ 0 & \text{otherwise} \end{cases}$$

Here, $\hat{R}_n(h_{\text{mem}}) = 0$, yet $R(h_{\text{mem}})$ is catastrophic on unseen points. For ERM to be statistically consistent, $\hat{R}_n(h)$ must converge to $R(h)$ uniformly across all $h \in \mathcal{H}$:

$$\lim_{n \to \infty} P\left( \sup_{h \in \mathcal{H}} \left\vert{} R(h) - \hat{R}_n(h) \right\vert{} > \epsilon \right) = 0$$

Vapnik and Chervonenkis proved that uniform convergence is guaranteed if and only if the “capacity” (complexity) of $\mathcal{H}$ is bounded—formalized for binary classifiers by a finite VC dimension.

Decomposing Total Error
#

Restricting $\mathcal{H}$ introduces a fundamental tension. Let $h^*$ be the Bayes optimal predictor (the best possible function across all measurable functions, achieving the irreducible error floor $R(h^*)$), and let $h_{\mathcal{H}}^* = \arg\min_{h \in \mathcal{H}} R(h)$ be the best possible function inside our restricted hypothesis space $\mathcal{H}$.

The excess risk of our learned model $\hat{h}_{\text{ERM}}$ decomposes cleanly into two terms (Shalev-Shwartz & Ben-David, 2014):

$$R(\hat{h}_{\text{ERM}}) - R(h^*) = \underbrace{\big( R(h_{\mathcal{H}}^*) - R(h^*) \big)}_{\text{Approximation Error}} + \underbrace{\big( R(\hat{h}_{\text{ERM}}) - R(h_{\mathcal{H}}^*) \big)}_{\text{Estimation Error}}$$
  • Approximation Error: How far the best model in $\mathcal{H}$ is from the true underlying reality. Choosing a restrictive $\mathcal{H}$ (e.g., fitting a straight line to a sine wave) inflates this term.
  • Estimation Error: How much worse our ERM solution is compared to the best model inside $\mathcal{H}$, purely due to having finite, noisy samples. Choosing an overly rich $\mathcal{H}$ inflates this term because ERM chases sample noise.

4. The Four Learning Paradigms
#

While the ERM framework above is typically introduced through supervised learning, virtually all modern machine learning paradigms are variations on what data is available and how the risk functional is defined:

Paradigm Observed Data Feedback / Signal Mathematical Objective Typical Examples
Supervised Learning Pairs $\{(x_i, y_i)\}_{i=1}^n$ Explicit ground-truth labels $y_i$ Minimize $\mathbb{E}[L(h(x), y)]$ Regression, image classification, sensor calibration
Unsupervised Learning Inputs $\{x_i\}_{i=1}^n$ None (intrinsic data geometry) Estimate $P(X)$ or low-dimensional latent structure $Z$ Clustering (K-Means, GMM), PCA, anomaly detection
Self-Supervised Learning Inputs $\{x_i\}_{i=1}^n$ Pseudo-labels carved out from $x_i$ itself Predict masked/future parts $P(x_{\text{target}} \mid x_{\text{context}})$ Next-token prediction (LLMs), Masked Autoencoders
Reinforcement Learning Trajectories $(s_t, a_t, r_t, s_{t+1})$ Delayed scalar rewards $r_t$ from environment interaction Maximize expected discounted return $\mathbb{E}\left[\sum_{t} \gamma^t r_t\right]$ Robotics control, game playing, RLHF post-training

Notice the structural shift in Self-Supervised Learning: it converts unlabeled data into a supervised ERM problem by hiding part of the input and forcing the model to reconstruct it. That single trick is what enables modern foundation models to learn from trillions of tokens without manual annotation.


5. The No Free Lunch Theorem & Inductive Bias
#

A recurring question in applied ML is: “Which algorithm is objectively the best?”

David Wolpert (1996) provided a definitive mathematical answer with the No Free Lunch (NFL) Theorem for supervised learning. Formally, if we average generalization performance uniformly over all possible target distributions $P(Y \mid X)$, then every learning algorithm achieves the exact same off-training-set error—no better than random guessing.

Why does this hold? Because for any dataset $S$ of size $n$, there exist infinitely many functions that agree perfectly on $S$ while disagreeing arbitrarily everywhere outside $S$. If every possible function in the universe were equally likely to occur in nature, past data would carry zero information about unseen points.

The practical takeaway is profound: learning is impossible without assumptions.

Those assumptions are encoded in your choice of hypothesis space $\mathcal{H}$ and optimization procedure, collectively known as Inductive Bias:

  • Linear models assume outputs change monotonically and additively with inputs.
  • Smooth kernel methods assume nearby points in $\mathcal{X}$ share similar outputs in $\mathcal{Y}$.
  • Convolutional networks assume spatial translation invariance in images.

An algorithm outperforms another on real-world data only to the degree that its inductive bias aligns with the actual physical or statistical structure of the problem domain.


6. Minimal Implementation: Observing ERM vs. True Risk in NumPy
#

Because we control the simulation below, we have god-mode access to the true data-generating distribution $P(X, Y)$: a noisy sine wave $y = \sin(\pi x) + \epsilon$ where $x \sim \text{Uniform}(-1, 1)$ and $\epsilon \sim \mathcal{N}(0, 0.25^2)$.

We draw only $n = 20$ training points and apply exact ERM across three polynomial hypothesis spaces of increasing complexity: $\mathcal{H}_1$ (degree 1), $\mathcal{H}_3$ (degree 3), and $\mathcal{H}_{15}$ (degree 15). We then evaluate True Risk using 100,000 fresh Monte Carlo samples from $P(X, Y)$.

import numpy as np

rng = np.random.default_rng(42)

def true_function(x: np.ndarray) -> np.ndarray:
    return np.sin(np.pi * x)

def sample_from_distribution(n: int, noise_std: float = 0.25):
    x = rng.uniform(-1.0, 1.0, size=n)
    y = true_function(x) + rng.normal(0.0, noise_std, size=n)
    return x, y

def vandermonde(x: np.ndarray, degree: int) -> np.ndarray:
    # Feature map phi(x) = [1, x, x^2, ..., x^degree]
    return np.vander(x, N=degree + 1, increasing=True)

def fit_erm(x_train: np.ndarray, y_train: np.ndarray, degree: int) -> np.ndarray:
    Phi = vandermonde(x_train, degree)
    # Exact ERM minimizer for squared loss
    weights, *_ = np.linalg.lstsq(Phi, y_train, rcond=None)
    return weights

def mse_loss(y_true: np.ndarray, y_pred: np.ndarray) -> float:
    return float(np.mean((y_true - y_pred) ** 2))

# 1. Finite training set S (n = 20)
x_train, y_train = sample_from_distribution(n=20)

# 2. Population approximation via 100,000 fresh i.i.d. samples
x_pop, y_pop = sample_from_distribution(n=100_000)

# Irreducible Bayes Optimal Risk: Var(epsilon) = 0.25^2 = 0.0625
bayes_risk = mse_loss(y_pop, true_function(x_pop))
print(f"Bayes Optimal Risk R(h*): {bayes_risk:.4f}\n")

for degree in [1, 3, 15]:
    w = fit_erm(x_train, y_train, degree)
    emp_risk = mse_loss(y_train, vandermonde(x_train, degree) @ w)
    true_risk = mse_loss(y_pop, vandermonde(x_pop, degree) @ w)
    gap = true_risk - emp_risk
    print(
        f"H_{degree:<2} | "
        f"Empirical Risk: {emp_risk:.4f} | "
        f"True Risk: {true_risk:.4f} | "
        f"Generalization Gap: {gap:+.4f}"
    )

Interpreting the Behavior
#

When you run this experiment, three distinct regimes emerge immediately:

  1. $\mathcal{H}_1$ (Degree 1 — High Approximation Error): Both empirical risk and true risk remain high (around 0.25–0.30). A straight line cannot bend to represent $\sin(\pi x)$, regardless of how much data you feed it.
  2. $\mathcal{H}_3$ (Degree 3 — Aligned Inductive Bias): Because the Taylor expansion of $\sin(\pi x)$ on $[-1, 1]$ is closely approximated by a cubic polynomial, both empirical risk and true risk approach the Bayes floor (~0.0625), with a tight generalization gap.
  3. $\mathcal{H}_{15}$ (Degree 15 — High Estimation Error): Empirical risk drops below the Bayes optimal noise floor (< 0.0625) because the polynomial weaves directly through random Gaussian noise. Meanwhile, the true risk explodes orders of magnitude higher due to violent oscillations between training samples and near the domain boundaries.

The core lesson of Statistical Learning Theory is right there in the numbers: minimizing training loss blindly does not solve the learning problem.


7. Limitations & Bridge to Part 2
#

So far, we treated the loss function $L(h(x), y)$ as an arbitrary black box—assuming squared error without justifying why squared error makes sense, or why it fails catastrophically when predicting class probabilities.

In Part 2: Linear Models & The Anatomy of Objective Functions, we will strip away that assumption. By approaching learning through probability theory (Maximum Likelihood Estimation and Maximum A Posteriori) and information theory (KL Divergence), we will prove mathematically why Gaussian noise gives rise to Mean Squared Error, why Bernoulli outcomes give rise to Binary Cross-Entropy, and how objective functions dictate the geometry of what a model learns.


References
#

  1. Mitchell, T. M. (1997). Machine Learning. McGraw-Hill. (Chapter 1: Formal definition of learning systems).
  2. Vapnik, V. N. (1999). “An Overview of Statistical Learning Theory.” IEEE Transactions on Neural Networks, 10(5), 988–999.
  3. Wolpert, D. H. (1996). “The Lack of A Priori Distinctions Between Learning Algorithms.” Neural Computation, 8(7), 1341–1390.
  4. Shalev-Shwartz, S., & Ben-David, S. (2014). Understanding Machine Learning: From Theory to Algorithms. Cambridge University Press. (Chapters 2–5: ERM, PAC learning, and error decomposition).
Machine Learning Fundamentals - This article is part of a series.
Part 1: This Article