Empirical Risk Minimization
Suppose you want to build a spam filter. You have ten thousand emails labeled spam or not-spam. You cannot possibly evaluate a candidate classifier on every email ever sent. The true, unknown distribution of future emails is inaccessible. All you have is your sample. Empirical Risk Minimization (ERM) tells you what to do with that sample. Pick the model that performs best, on average, over your actual data. Then treat that as a stand-in for performance on unseen data. This idea is so pervasive that it is easy to miss how much it is doing. Nearly every time you fit a model by minimizing average loss, you are performing ERM. This includes least squares regression, logistic regression, and neural networks trained with cross-entropy. ERM is the operational bridge between The Loss Function, which measures how wrong a single prediction is, and Learning as Optimization, which turns learning into a search problem. That problem becomes solvable by calculus and gradient methods. Without ERM, "learning from data" is a vague aspiration. With it, learning becomes minimizing a concrete, computable function. But ERM is not free of assumptions. Understanding exactly what justifies it — and when it breaks — is the heart of statistical learning theory. The empirical average of losses is a random quantity, built from a finite sample. What we truly care about, though, is the expected loss over the entire population. ERM's validity rests on a law-of-large-numbers argument. With enough independent samples, the empirical average concentrates around the true expectation. This same reasoning, pushed further, explains why unconstrained ERM can catastrophically overfit. It also sets up the entire machinery of generalization bounds. This article makes the ERM principle precise. It walks through the algorithmic recipe used to apply it in practice. It gives an honest accounting of why it works, how well, and where it fails. It closes by pointing toward the ideas that patch its weaknesses — regularization, complexity control, and the formal PAC framework.
- ERM replaces the unknown true risk (expected loss over the data distribution) with the empirical risk (average loss over a finite training sample).
- Formally, ERM selects the hypothesis minimizing over a hypothesis class .
- Its justification is statistical: by the law of large numbers, empirical risk converges to true risk as sample size grows.
- ERM is computationally tractable: it turns learning into an optimization problem solvable by gradient descent, convex solvers, or closed-form algebra.
- Unrestricted ERM overfits — a rich enough can drive empirical risk to zero while true risk stays high.
- Controlling the gap between empirical and true risk motivates regularization, PAC learning, and the bias-complexity tradeoff.
Empirical Risk Minimization learns by minimizing average loss on a finite sample as a computable proxy for minimizing expected loss over the whole, unobservable data distribution.
The idea
Let be the space of inputs and the space of labels, and suppose data pairs are drawn i.i.d. from some fixed but unknown distribution over . Given a hypothesis (or, in regression/probabilistic settings, or a distribution) and a loss function quantifying prediction error, the quantity we actually want to minimize is the true risk (also called generalization error or expected risk):
This is an expectation over the entire population — every email that could ever be sent, every image that could ever be photographed. It is not computable, because is unknown and infinite (or effectively so). What we have instead is a training sample drawn i.i.d. from . The empirical risk is the average loss on this sample:
The Empirical Risk Minimization principle says: given a hypothesis class (linear models, decision trees, neural networks of a given architecture, etc.), choose
The word "empirical" is doing real epistemological work here — it flags that is a statistic, a random variable that depends on which particular sample we happened to draw. Two different samples of the same size from the same distribution will generally yield two different empirical risks, and two different minimizers . ERM is only sensible as a strategy because, under reasonable conditions, is an unbiased and concentrating estimator of for every fixed : , and by concentration inequalities the empirical average is unlikely to deviate far from this expectation once is moderately large. This is precisely what licenses treating "minimize training loss" as a reasonable surrogate for "minimize true risk," and it connects ERM directly to the broader logic of Learning as Optimization: once risk is replaced by a finite sum, learning becomes a tractable optimization problem over the parameters defining .
How it works
In practice, ERM is not applied to an abstract hypothesis class directly; it is applied to a parameterized family , (e.g., weights of a linear model or a neural network). The learning problem becomes a finite-dimensional optimization:
where the bracketed regularization term is optional — pure ERM omits it, but nearly every practical deployment includes it as a hedge against the overfitting failure mode discussed below. The generic ERM recipe has four steps: define the loss, form the empirical risk as a sum over the sample, choose an optimizer suited to that sum's structure (closed-form, convex solver, or stochastic gradient descent), and evaluate on held-out data to check that minimizing training loss actually reduced risk on unseen data. ``` ALGORITHM: Empirical Risk Minimization (generic, gradient-based) INPUT: training sample S = {(x_1, y_1), ..., (x_n, y_n)} hypothesis family h_theta parameterized by theta loss function ell(prediction, label) learning rate schedule eta_t, number of steps T (optional) regularizer Omega(theta), coefficient lambda INITIALIZE theta_0 (e.g., small random values, or zeros for convex ell) DEFINE empirical_risk(theta): return (1/n) sum_{i=1}^{n} ell(h_theta(x_i), y_i) [+ lambda Omega(theta)] FOR t = 0, 1, ..., T-1:
# compute gradient of empirical risk w.r.t. theta
# (full batch, or mini-batch estimate over a random subset B of S) g_t = (1/|B|) sum_{(x,y) in B} grad_theta ell(h_{theta_t}(x), y) [+ lambda grad Omega(theta_t)] theta_{t+1} = theta_t - eta_t * g_t RETURN theta_T
# Model selection wrapper (choosing among hypothesis classes / regularization strengths) SPLIT data into S_train, S_val FOR each candidate (H_k, lambda_k) in a set of configurations: theta_k = ERM(S_train, H_k, lambda_k) # inner training loop above score_k = empirical_risk_on(S_val, theta_k) # unbiased estimate on unseen data CHOOSE k = argmin_k score_k RETURN theta_{k}, refit optionally on S_train + S_val ``` Two structural points about this pseudocode deserve emphasis. First, the inner loop is exactly gradient descent (or SGD) applied to a function that happens to be an average over data points — this is why ERM turns statistics into an optimization problem tractable by the standard machinery of calculus. Second, the outer model-selection wrapper is not optional cosmetic advice: it exists because the training-set empirical risk of the chosen hypothesis is a biased (optimistic) estimate of its true risk, precisely because the choice was made to minimize that same quantity. A separate validation split (or cross-validation) is needed to get an honest read on generalization, foreshadowing the Bias-Complexity Tradeoff.
Complexity & correctness
Computational complexity. ERM's cost splits into per-step cost and number of steps. For a single gradient evaluation over the full sample, computing costs , where is the cost of computing for one example (for a linear model in dimensions, ; for a neural network, is the cost of one forward-backward pass). Full-batch gradient descent for iterations therefore costs . Mini-batch stochastic gradient descent with batch size reduces the per-step cost to , trading off gradient variance against per-step speed — the standard reason SGD dominates in large- settings, since it makes progress without ever touching the full dataset in one step. For special cases, ERM is exactly solvable: ordinary least squares ERM with squared loss has a closed-form solution , computable in via normal equations, or via QR without forming explicitly. Space complexity is to store the design matrix (or if streaming mini-batches from disk).
Convexity and solvability. When is convex in for every fixed — true for squared loss with linear , and for logistic/hinge loss with linear — the empirical risk is a sum of convex functions, hence convex. This guarantees that any local minimum found by gradient descent is a global minimum, and convex optimization theory gives explicit convergence rates (e.g., for gradient descent on smooth convex functions, for subgradient methods on non-smooth ones like hinge loss). For non-convex (deep networks), ERM training only guarantees convergence to a stationary point, and correctness of the optimization is a separate, weaker claim than correctness of the learning — a stationary point of empirical risk need not be a good solution.
Statistical correctness — why minimizing is justified at all. The real theoretical content of ERM is not the optimization; it's the argument that a small implies a small . Fix any single hypothesis . Since are i.i.d., the losses are i.i.d. random variables with mean , so by the (weak) Law of Large Numbers,
If the loss is bounded, , Hoeffding's inequality sharpens this to a finite-sample, exponential concentration bound: for any ,
This says empirical risk is a good estimate of true risk for a fixed h chosen in advance. But ERM does not fix in advance — it searches over and picks the empirically best one, which means the bound above cannot be applied directly to : the act of selecting the minimizer correlates the choice of with the sample, invalidating the naive argument (this is the same trap that makes training-set accuracy optimistic). The fix is a uniform convergence bound over the whole class, via a union bound (for finite ) or VC-dimension / Rademacher complexity arguments (for infinite ):
If this uniform bound holds, then in particular it holds for , and one can show
where is the best possible hypothesis in the class. This chain of inequalities is the crux: it shows ERM's output is nearly as good as the best hypothesis in the class, with excess risk controlled by the uniform convergence rate. This is exactly the machinery formalized by PAC Learning, and the rate depends critically on the complexity of (e.g., VC dimension), which is why controlling that complexity — via Regularization Theory or restricting — is unavoidable, not optional, once is rich.
Honest tradeoff. ERM alone gives no guarantee if is unrestricted: with enough capacity, can be driven to zero (e.g., a lookup table memorizing the sample) while stays at the level of random guessing, because a memorizing hypothesis generalizes to nothing outside the sample. The theory above only bites when 's complexity is controlled relative to — this is precisely the content of the Bias-Complexity Tradeoff.
Worked example
Consider a tiny 1-D regression problem: predicting a house's price (in n = 6h_\theta(x) = \theta_0 + \theta_1 x\ell(h(x),y) = (h(x)-y)^2$.
| size | price | |
|---|---|---|
| 1 | 0.8 | 1.5 |
| 2 | 1.0 | 2.0 |
| 3 | 1.5 | 2.4 |
| 4 | 2.0 | 3.1 |
| 5 | 2.5 | 3.6 |
| 6 | 3.0 | 4.0 |
Step 1 — form the empirical risk. With :
This is convex quadratic in , so ERM here is exactly solvable via the normal equations, no iterative solver needed.
Step 2 — closed-form minimization. Compute sufficient statistics: , . The least-squares slope and intercept are
Carrying out the arithmetic (deviations : ; : ):
So , and .
Step 3 — evaluate empirical risk at the minimizer. Plugging back in gives predictions against actual ; squared errors are roughly , averaging to .
Step 4 — the generalization question. This small is not automatically the true risk. If size is measured with noise, or if the true relationship is mildly nonlinear (say prices actually follow ), a linear ERM fit will have systematically higher risk on new houses than suggests, because the linear class cannot represent the curvature — an instance of the bias term in the bias-complexity decomposition. Conversely, if we had instead fit a degree-5 polynomial through these same 6 points (7 parameters, 6 constraints — heavily overparameterized), would drop to nearly zero by interpolating every point, while true risk on new houses would likely be worse than the simple line, since the curve would oscillate wildly between the sparse training points. This second scenario — near-zero empirical risk, high true risk — is the canonical ERM overfitting failure, and it is why the uniform-convergence argument above is essential: with 7 free parameters and 6 data points, 's effective complexity is too large relative to for the concentration guarantees to bite.
| Model | (train) | Expected on new houses (qualitative) |
|---|---|---|
| Linear (2 params) | ≈ 0.013 | Low-moderate; slight bias if truth is curved |
| Degree-5 polynomial (7 params) | ≈ 0 (interpolates) | High; wild extrapolation between points |
| Constant (1 param) | ≈ 0.60 | High; systematic underfit |
Common pitfalls & traps
| Pitfall | Why it happens | Consequence |
|---|---|---|
| Treating training loss as the final answer | Confusing with | Overestimating deployed performance; silent failure in production |
| Using the same data to select and evaluate a model | No held-out split; "peeking" at test data during tuning | Optimistic, biased performance estimates; a form of data leakage |
| Unrestricted, very flexible with small | Rich hypothesis class can memorize noise | Zero train loss, poor true risk (classic overfitting) |
| Ignoring class imbalance in the loss average | Empirical risk averages equally over examples regardless of class rarity | Model ignores minority class; average loss looks fine while minority recall collapses |
| Non-i.i.d. or distribution-shifted data | Samples correlated in time, or train/deploy distributions differ | LLN/concentration arguments no longer apply; is not a valid estimate of deployment |
| Non-convex loss surfaces treated like convex ones | Deep nets: gradient descent only guarantees stationary points | Different runs/seeds converge to different solutions with different true risk |
Pioneers & history
The formal articulation of ERM as a learning principle, with rigorous guarantees on when it succeeds, is largely due to the Soviet/Russian statistician Vladimir Vapnik, working with Alexey Chervonenkis, whose VC-dimension theory turned "does minimizing training error generalize?" into a precisely answerable mathematical question. Their work built on and extended earlier statistical ideas — the method of least squares itself traces to Gauss and Legendre, and the general framework of estimating parameters by minimizing a sample-based criterion connects to Fisher's development of maximum likelihood estimation, which is itself an instance of ERM under log-loss.
Origins · 1 minVladimir Naumovich Vapnik and how this was discovered
Vapnik, working at the Institute of Control Sciences in Moscow and later at AT&T Bell Labs, co-developed the VC (Vapnik–Chervonenkis) theory of statistical learning in the 1960s–70s, providing the first rigorous finite-sample guarantees for when minimizing empirical risk over a hypothesis class controls true risk. This theory, combined with his later work on the Support Vector Machine, established ERM not merely as a heuristic but as a mathematically justified inference principle with quantifiable generalization guarantees, laying direct groundwork for PAC learning theory.
Where this matters
ERM is the operating principle underneath essentially all supervised machine learning in production today. Training a logistic regression spam filter, fitting a gradient-boosted tree for credit scoring, or backpropagating through a deep convolutional network for image classification are all, at their core, instances of minimizing an empirical average of a loss function over a training set — differing only in the hypothesis class, the loss, and the optimizer. Large-scale systems at companies running recommendation engines, ad-click prediction, fraud detection, and speech recognition all train models by ERM with mini-batch stochastic gradient descent, precisely because the empirical-risk-as-a-sum structure is what makes stochastic gradient estimates (computed on small batches) unbiased estimators of the full-batch gradient. Frameworks like scikit-learn, PyTorch, and TensorFlow are, in large part, engineering infrastructure for defining losses and hypothesis classes and then solving the resulting ERM optimization efficiently at scale. Understanding ERM's statistical justification — and its failure mode without complexity control — is also the conceptual prerequisite for understanding why practitioners add weight decay, dropout, early stopping, and explicit regularization terms, all of which are direct responses to the fact that pure ERM overfits once the hypothesis class is rich enough, motivating Regularization Theory as ERM's necessary complement.
Ask the tutor: How does the VC dimension of a hypothesis class quantitatively determine the sample size needed for ERM's generalization guarantee to hold?
Is ERM the same thing as maximum likelihood estimation?
They are closely related but not identical in general. Maximum likelihood estimation (MLE) chooses parameters maximizing the likelihood of the observed data under an assumed probabilistic model, which is algebraically equivalent to minimizing the average negative log-likelihood — a specific loss function. So MLE is a special case of ERM where the loss is the negative log-likelihood. ERM as a principle is more general: it accommodates any loss function, including ones with no direct probabilistic interpretation, such as the hinge loss used in support vector machines or 0-1 loss for classification error. Every MLE problem is an ERM problem, but not every ERM problem corresponds to a coherent probabilistic likelihood.
Does ERM require the hypothesis class to be convex or the loss to be convex?
No — ERM as a principle (minimize average loss) is defined regardless of convexity. What convexity buys you is a computational guarantee: if the loss is convex in the parameters, the empirical risk is a sum of convex functions and hence convex, so gradient-based optimizers are guaranteed to find the global minimum. For non-convex settings, such as deep neural networks, ERM is still the learning principle being applied, but the optimization step only guarantees convergence to a stationary point (local minimum or saddle), not the global ERM solution. In practice, this gap is often tolerable because many stationary points of deep networks generalize well, but it means the theoretical guarantees connecting ERM to generalization become harder to state cleanly.
Why does minimizing training loss sometimes make test performance worse?
This happens when the hypothesis class is expressive enough to fit noise in the training sample rather than genuine structure. Empirical risk only measures fit to the specific sample drawn; nothing in the ERM objective distinguishes "signal" that generalizes from "noise" that is idiosyncratic to that sample. If has enough capacity, ERM will happily exploit noise to drive toward zero, producing a hypothesis exquisitely tuned to the training points but arbitrary elsewhere. This is overfitting, and it is exactly why generalization theory studies the gap as a function of hypothesis-class complexity, motivating regularization and capacity control.
How does regularization fit into the ERM framework?
Regularization modifies the ERM objective by adding a penalty term that discourages complex hypotheses, giving the regularized empirical risk minimization objective . This can be understood as a computationally convenient way to implicitly restrict the effective hypothesis class — for example, an penalty shrinks the effective search to hypotheses with small parameter norm, which behaves like a smaller-capacity class in the generalization bounds. Regularization directly addresses the weakness identified by the uniform convergence analysis: it trades a (typically small) increase in empirical risk for a (hopefully larger) decrease in the generalization gap, improving true risk.
What role does sample size n play in whether ERM is trustworthy?
Sample size enters directly into the concentration bounds that justify ERM: Hoeffding-type bounds shrink the probability of large empirical-vs-true risk deviation exponentially in , and uniform convergence bounds over a hypothesis class typically require to grow at least linearly (often more) in the class's complexity measure, such as VC dimension, to keep the generalization gap small. Practically, this means a hypothesis class that is safe for ERM with a million examples may badly overfit with only a hundred. This is the quantitative content behind the informal advice "more data reduces overfitting," and it explains why the same model architecture can behave very differently depending on dataset size.
Can ERM be applied to unsupervised learning, or is it strictly for supervised problems?
ERM's core mechanics — minimize an average of a per-example loss over a sample — extend beyond supervised learning. Autoencoders minimize average reconstruction loss, an unsupervised instance of ERM where the "label" is the input itself. Clustering objectives like k-means minimize average within-cluster squared distance, another ERM-flavored average-loss criterion, though without a probabilistic over labeled pairs the risk-theoretic language is adapted rather than applied verbatim. The unifying thread is that any learning problem expressible as minimizing a finite-sample average of a per-example cost function inherits both the practical optimization toolkit and the generalization concerns of classical ERM.
Is a zero training loss always a sign of a problem?
Not necessarily — it depends on the noise level in the data and the capacity of the hypothesis class relative to the sample size. If the true relationship between inputs and outputs is genuinely noiseless and the hypothesis class matches the true function class, driving training loss to zero can be entirely appropriate and consistent with low true risk. The danger arises specifically when zero training loss is achieved by a hypothesis class flexible enough to also fit pure noise, since that flexibility offers no way to distinguish "explained signal" from "memorized noise" using training loss alone — which is why validation performance, not training loss, is the trustworthy diagnostic.