Foundations/A Machine-Learning Refresher

Lesson 2.22,478 words

A Machine-Learning Refresher

The statistical framework the networks live in: data drawn from an unknown distribution, a loss to minimize, and the central question of generalization: will it work on data we have not seen? We set up empirical risk, capacity, the bias–variance tradeoff, and maximum likelihood.

╌╌╌╌

A learning algorithm has one job: perform well on data it was not trained on. Risk, capacity, regularization, and validation are all machinery in service of that single goal. This lesson sets up the statistical frame the networks inhabit.

The supervised learning setup

Data is generated by a fixed but unknown distribution over inputs and targets . We never observe ; we observe only a finite i.i.d. sample,

The i.i.d. assumption carries the whole theory. It splits into two clauses, each providing a distinct guarantee:

  • Identically distributed: train and test share one , so fitting the past is informative about the future at all.
  • Independent: no example leaks information about another beyond , so the law of large numbers applies and the sample average converges to the expectation. This is what makes empirical risk a faithful stand-in for true risk.

Break the identically-distributed clause and the guarantees evaporate. The optimizer is not at fault; it minimized exactly the risk it was given, on exactly the distribution it saw; simply moved. This failure mode is distribution shift:

Train distributionTest distributionSymptom
daytime photographsnight photographsobject detector misses in low light
movie reviewsclinical notessentiment classifier mislabels
pre-shock marketpost-shock marketpricing model misprices

The i.i.d. assumption is a modelling choice, not a law of nature; we measure the gap it opens once we have the tools, under robustness.

Risk is what we actually care about and exactly what we cannot compute — it is an expectation over a distribution we do not have. So we substitute the average over the data we do have.

Empirical risk minimization (ERM) is the strategy of choosing to make small and hoping follows. The gap between the two, between training performance and reality, is the central problem of the subject.1

Generalization, overfitting, underfitting

Split the data: train on one part, estimate the risk on a held-out test set the model never touched. Two numbers result (training error and test error), and their relationship sorts every model into one of three regimes.

Training error falls with capacity; generalization error is U-shaped — the gap between them is overfitting.
  • Underfitting (left): the model lacks the capacity to capture the pattern, so both errors are high. The remedy is a bigger model or better features.
  • Overfitting (right): the model has memorized noise specific to the training sample. Training error is tiny but test error has climbed: the generalization gap has opened.
  • The sweet spot sits where generalization error bottoms out.

For example, fit the same seven noisy points with a line, a cubic, and a degree-9 curve: the three regimes are unmistakable. The line is too rigid to follow the trend; the high-degree curve contorts to pass through every point, noise included, and will lurch wildly between them.

The same data fit three ways: underfit (too rigid a line), a good fit, and overfit (a high-degree curve chasing every noisy point).

Capacity sets what can go wrong, not what will. The no-free-lunch theorem makes this precise: averaged over all data-generating distributions, every learning algorithm has the same expected test error: there is no universally best model. Real problems are not drawn uniformly from all worlds (images have local structure, language has grammar), and a model wins exactly when its inductive bias matches the structure present.2

The curse of dimensionality

Structure is not optional: in high dimensions, naive learning is defeated by geometry before capacity is even in question. The curse of dimensionality is a cluster of effects tracing to one fact — volume grows exponentially with dimension. Partition each axis of the -dimensional unit cube into bins:

To keep even one example per cell (the density nearest-neighbour quietly assumes), the sample size must grow as . No dataset does, so the consequences cascade:

EffectStatementWhat fails
Empty spacea fixed sample fills a vanishing fraction of cellslocal density estimates
Distance concentration as nearest neighbour is barely nearer than the farthest
Sample requirementexamples for fixed coverage grow as brute-force tabulation, kernel density

Smoothness-based methods (points close together have similar labels) fail because in high dimensions almost nothing is close to anything.3

The curse of dimensionality: binning each axis, the number of cells to populate grows exponentially, from a handful in 1D to far too many in 3D.

This is the rigorous reason for inductive bias: if you cannot fill the space, you must assume a shape for it and let that prior do the work the data cannot. Every deep-learning prior is the same move: trade dense coverage for a structural assumption:

PriorStructural assumptionMechanism
smoothnessnearby inputs nearby outputs penalty, small weights
localityfeatures depend on local patchesconvolution, weight sharing
temporal structurethe same map applies at each steprecurrence
manifold hypothesisdata clusters near a low-dimensional surfacethe assumption deep nets exploit most

From this angle deep learning is the search for priors that make high-dimensional problems tractable.

The bias–variance tradeoff

Why is generalization error U-shaped? Decompose it. For squared-error regression, the expected test error at a point, averaged over all the training sets we could have drawn, splits into three pieces:

TermFormulaMeaningCause
Biaserror from wrong assumptions, on averagemodel too simple — underfitting
Variancesensitivity to the particular samplemodel too flexible — overfitting
Noiseirreducible — label noise in the data, not the model

Picture a dartboard: each dot is the model fit on a different sample, the bullseye is the truth. Bias is how far the cluster sits from center; variance is how spread out it is.

Bias vs. variance as dart throws: each dot is a model trained on a different sample, and low bias with low variance (top-left) is the goal.

Capacity trades one for the other: simple models are high-bias / low-variance (underfit), complex models are low-bias / high-variance (overfit). The classical U-curve is bias falling and variance rising, summed.

The U-curve decomposed: bias-squared falls with capacity while variance rises; their sum (plus fixed noise) is the U-shaped test error, and its minimum is the tradeoff's sweet spot.

(Deep networks complicate this picture; we revisit double descentlater, but the tradeoff is the right first picture.)

Point estimation made precise

The dartboard is the theory of point estimation. Fed a random dataset , a learning algorithm returns an estimator , itself a random quantity. Four properties quantify its quality:

PropertyDefinitionReads on the dartboard as
Biasoffset of the cluster from the bullseye
Unbiasedcluster centred on the bullseye
Variancespread of the cluster
Consistent as cluster tightens onto centre with more darts

Bias and variance are the dartboard's two axes; the decomposition drawn earlier is a one-line consequence.

Low error is not low bias. An unbiased estimator can be terrible if its variance is large, and a biased estimator can have strictly lower MSE than the best unbiased one. This is precisely the trade regularization makes: accept a little bias for a large drop in variance.

Where the loss comes from: maximum likelihood

We used as if handed down from above. Most losses are maximum likelihood estimation in disguise. Model the conditional and make the data as probable as possible:

The turns an underflow-prone product into a stable sum, and maximizing likelihood becomes minimizing the negative log-likelihood. The task chooses the output distribution; the NLL is the familiar loss:

TaskNLL loss
regressionmean squared error
binary classificationbinary cross-entropy
multiclasscross-entropy
countPoisson NLL

The regression row is a short derivation. Model , substitute the Gaussian density, and drop -independent constants:

Summed over the data, NLL is the mean squared error — never arbitrary, but the maximum-likelihood loss under Gaussian noise. Cross-entropy has a second reading: minimizing it minimizes the Kullback–Leibler divergence from the model to the data,

and since the first term is -independent, driving cross-entropy down is pulling the model's distribution toward the true one. Maximum likelihood is distribution-matching.4

We minimize cross-entropy rather than raw 0/1 error for two reasons: it is the statistically principled objective, and, unlike the piecewise-constant 0/1 error (whose gradient is zero almost everywhere), it is smooth, so descent has a slope.

Priors as regularization: MAP versus MLE

MLE asks which parameters make the data most probable, and with high capacity and little data the answer is often absurd: the degree-9 polynomial threading every noisy point is the MLE. The Bayesian fix encodes prior beliefs and maximizes the posterior :

The log-prior is the regularizer. Put a zero-mean Gaussian prior on the weights, , so up to a constant , and the MAP objective becomes

The second term reproduces regularization (weight decay) with strength : a confident prior (small ) penalizes hard; the limit recovers plain MLE. Each penalty corresponds to a prior:

PenaltyPrior NameEffect
Gaussian / weight decay / ridgeshrinks weights toward
Laplace / lassodrives weights to exactly (sparse)
noneuniform (improper)plain MLEno shrinkage

Every weight penalty is a prior, and every prior is a weight penalty.5 We develop the mechanics, and why small weights generalize, under regularization.

Hyperparameters and the validation set

Capacity, learning rate, and regularization strength are hyperparameters, chosen by you, not learned by the optimizer. Tuning them on the test set contaminates the one honest estimate of risk, so split the data three ways:6

SplitTunesTouched
trainparameters (by the optimizer)every step
validationhyperparameters (by you)each model-selection round
testnothing — estimates final riskexactly once, at the end
The three-way data split. Parameters are fit on train, hyperparameters chosen on validation, and the test set (touched once) gives the honest risk estimate.

The discipline matters: most worked in the notebook, failed in production failures trace to a validation set quietly used as a test set, tuned against until the number stopped being honest. When data is scarce, -fold cross-validation recovers it: partition into folds, train times each holding out a different fold, average the scores, for a less noisy estimate at the compute.

How much the gap can be: generalization bounds

The validation set measures the generalization gap; learning theory bounds it in advance. Every such bound has the same shape:

where measures capacity (VC dimension, Rademacher complexity — formal cousins of polynomial degree) and is the sample size.

Classical bounds are famously loose for modern networks, whose capacity exceeds yet which generalize anyway — a subtlety we take up under generalization theory.

A way to watch the gap is the learning curve: training and validation error versus training-set size. With few examples the model fits trivially (low training error, high validation error); as data accumulates, training error rises toward a floor and validation error falls toward it. Reading the curve diagnoses the bottleneck:

ShapeDiagnosisRemedy
persistent gap between the curveshigh variance — overfittingmore data, or regularize
high shared plateau, small gaphigh bias — underfittingmore capacity, richer features
both low, small gapwell-fitship it
A learning curve: as the training set grows, training error rises and validation error falls, and the shrinking gap is the generalization gap closing.

A model-selection workflow

In practice, the theory becomes a procedure:

Algorithm:ModelSelect(candidates,D)\textsc{ModelSelect}(\text{candidates}, \mathcal{D}) — fit, validate, seal
  1. 1
    split D\mathcal{D} into train / val / test; seal test
  2. 2
    for each hyperparameter setting hh do
  3. 3
    fit θh\theta_h on train by minimizing R^\hat R
  4. 4
    score R^val(θh)\hat R_{\text{val}}(\theta_h) on val
    never on test
  5. 5
    hargminhR^val(θh)h^\star \gets \arg\min_h \hat R_{\text{val}}(\theta_h)
  6. 6
    read learning + U-curves: gap \Rightarrow regularize/add data; plateau \Rightarrow add capacity
  7. 7
    report R^test(θh)\hat R_{\text{test}}(\theta_{h^\star})
    test touched exactly once

One capacity dial hides inside the loop itself. Early stopping (halting when validation error stops improving) is implicit capacity control: longer training expresses more of the model's range, so stopping early chooses a smaller effective capacity without changing the architecture. It is the cheapest regularizer there is, treated alongside the explicit ones.

Double descent and overparameterization

The U-curve is the right first picture and, for modern networks, an incomplete one. The last few years overturned the textbook expectation that more capacity than data must overfit.

Double descent. Belkin et al. (2019) and Nakkiran et al. (2019) documented that as capacity grows past the point where the model exactly fits (interpolates) the training set, test error, having risen through the classical overfitting regime, falls again — often below its first minimum. The single U becomes a U followed by a second descent, with a spike at the interpolation threshold where capacity just equals the number of examples. Model size, data size, and even training time each trace their own double-descent curve.

Benign overfitting. A network with far more parameters than examples can drive training loss to zero and still generalize, seemingly violating the bias–variance tradeoff. The resolution is that gradient descent on an overparameterized model does not pick just any zero-training-loss solution; it is implicitly biased toward low-norm, smooth ones (Bartlett et al., 2020). The effective capacity that governs generalization is set by this implicit regularization, not by the raw parameter count the classical bound uses — and that gap is why those bounds are so loose for deep networks. The bias–variance tradeoff still holds for the effective capacity; the parameter count simply stopped being a good proxy for it.78

With the framework in place (data, risk, capacity, the generalization gap, and the maximum-likelihood losses behind it), we turn to the models, starting with the linear model and its one fatal limitation.

Footnotes

  1. Goodfellow, Deep Learning, §5.1; §8.1.1 — empirical risk minimization: minimizing average training loss as a surrogate for the inaccessible true risk, and the generalization gap this surrogate opens.
  2. Goodfellow, Deep Learning, §5.2.1 — the No-Free-Lunch theorem: averaged over all data-generating distributions every learner ties, so performance comes entirely from an inductive bias matched to the problem.
  3. Goodfellow, Deep Learning, §5.11.1 — the curse of dimensionality and local-constancy priors: why volume growing as defeats neighbour-based smoothness assumptions in high dimensions.
  4. Goodfellow, Deep Learning, §5.5 — Maximum Likelihood Estimation: the NLL as the principled loss, its equivalence to minimizing from model to data, and its asymptotic efficiency.
  5. Goodfellow, Deep Learning, §5.6; §7.1 — MAP estimation and parameter norm penalties: a Gaussian weight prior reduces to weight decay, a Laplace prior to sparsity.
  6. Chollet, Deep Learning with Python, §4.2 — Evaluating models: the train / validation / test discipline, information leakage from tuning on the test set, and -fold cross-validation when data is scarce.
  7. Belkin, Hsu, Ma, Mandal (2019), Reconciling modern machine-learning practice and the classical bias–variance trade-off, PNAS 116; and Nakkiran, Kaplun, Bansal, Yang, Barak, Sutskever (2019), Deep Double Descent, arXiv:1912.02292 — test error descending a second time past the interpolation threshold.
  8. Bartlett, Long, Lugosi, Tsigler (2020), Benign overfitting in linear regression, PNAS 117 — overparameterized interpolators that generalize, explained by the implicit low-norm bias of the training procedure rather than raw parameter count.

╌╌ END ╌╌