Learning as Optimization
Suppose you want to predict house prices from square footage, or classify emails as spam. In each case you have examples, and you want a rule that generalizes to new cases you have never seen. This is a strange kind of problem: you are not told the correct rule, only evidence about what it should output. Machine learning turns this puzzle into something concrete and solvable. It does this by reframing "find a good rule" as "minimize a number." This reframing is the single most important idea in the field. Learning becomes minimization of an objective function over a space of candidate rules. Once framed this way, the entire machinery of calculus, numerical optimization, and statistics becomes available. Gradient descent, convexity, regularization, and generalization bounds all make sense only because someone first decided to phrase learning this way. Nearly every model trained today, from linear regression to billion-parameter neural networks, is fit by the same basic recipe. Define a hypothesis class, define a loss that scores predictions against reality, and search for parameters that make that loss small. This framing matters in real systems because it separates concerns cleanly. The choice of hypothesis class (linear model, decision tree, neural network) is a modeling decision. The choice of loss function encodes what kind of mistake is costly. The choice of optimizer is an engineering decision about how to search efficiently. Because these are separable, practitioners can swap a loss function without touching the model architecture. They can also swap the optimizer without touching the loss. Each piece can be reasoned about independently. This article builds the framework from the ground up. It covers what a hypothesis class is, what an objective function is, and how minimizing it relates to the data-generating process. It also explains why this optimization view is both powerful and imperfect. It sets up the vocabulary — Empirical Risk Minimization, The Loss Function, generalization — that the rest of learning theory depends on.
- Supervised learning is recast as: choose parameters minimizing an objective function over training data.
- A hypothesis class is the set of candidate functions; a loss function scores how wrong a prediction is.
- The training objective (empirical risk) is a proxy for the true goal (expected risk on unseen data).
- Gradient-based search exploits calculus to find good parameters without checking every possibility.
- Minimizing training error perfectly can hurt generalization — this is the core tension in learning theory.
- The same optimization skeleton underlies linear regression, logistic regression, SVMs, and deep networks.
Learning means choosing, from a family of candidate functions, the one that minimizes an average loss over observed data — using that minimization as a computable stand-in for the true, unobservable goal of predicting well on new data.
The idea
In supervised learning we are given a training set of pairs
where each is an input (a feature vector) and each is the desired output (a label or numeric target). We assume these pairs are drawn independently from some fixed but unknown probability distribution . This distribution encodes the true relationship between inputs and outputs, including any inherent noise. We pick a hypothesis class , a family of candidate functions indexed by a parameter vector . For linear regression, is all functions of the form . For a neural network, is all functions computable by a fixed architecture as ranges over its weights. The hypothesis class is a modeling choice: it determines what kinds of patterns the learner can even represent, independent of how it will search for the best one. We then need a way to say how good a particular is. A loss function measures the cost of predicting when the true answer is . Small loss means a good prediction; large loss means a bad one. Common choices include squared error for regression, and cross-entropy for classification. The loss function is where domain knowledge about the cost of being wrong enters the picture — predicting a stock price too high by 1, and the loss function is the place to encode that asymmetry. The quantity we actually want to minimize is the expected risk (also called the true or population risk):
This is the average loss the model would incur over the entire population of possible inputs, weighted by how likely they are. It is exactly what we care about — how well the model performs on new, unseen data — but it is unobservable, since we do not know and cannot average over infinitely many examples. Instead we compute the empirical risk:
the average loss over the training set we actually have. Learning is then defined as the optimization problem
This principle — minimize empirical risk as a proxy for expected risk — is called Empirical Risk Minimization, and it is the foundation on which almost all of supervised learning theory is built. The gap between and is the generalization gap, and controlling it is the central concern of learning theory.
How it works
Turning "learning" into "minimize " is only useful if we can actually solve the minimization. The standard approach is iterative numerical optimization: start from some initial parameters, repeatedly compute how the objective changes as parameters change, and step in the direction that decreases it. This is gradient descent, and essentially all model training — linear regression via normal equations aside — reduces to a variant of it. The mechanism relies on the objective being differentiable (or having a usable subgradient) in . At each step, we compute the gradient , a vector pointing in the direction of steepest increase of the empirical risk. Moving a small step in the opposite direction decreases the risk, at least locally, as guaranteed by the first-order Taylor expansion of around the current point. Repeating this many times, with a suitably chosen step size (learning rate), converges toward a minimum — a global one if is convex in , a local (but often good enough) one otherwise. In practice, computing the exact gradient over all training points at every step is expensive when is large. Stochastic gradient descent (SGD) replaces the full gradient with an estimate computed on a small random subset (a mini-batch), trading a small amount of noise for a large reduction in per-step cost. Because the mini-batch gradient is an unbiased estimator of the full gradient (its expectation over random batches equals the true gradient), the noisy steps still make progress on average. ``` ALGORITHM: Learning as Empirical Risk Minimization via (Stochastic) Gradient Descent INPUT: D # training set {(x_1,y_1), ..., (x_n,y_n)} f_theta # hypothesis class, parameterized by theta loss # per-example loss function ell(pred, y) eta # learning rate (step size) batch_size # size of mini-batch (batch_size = n gives full-batch GD) max_iters # stopping bound INITIALIZE: theta <- theta_0 # e.g. small random values FOR t = 1 TO max_iters: B <- sample batch_size examples uniformly at random from D
# (without replacement within an epoch) grad <- 0 FOR (x_i, y_i) IN B: pred_i <- f_theta(x_i) grad <- grad + gradient_wrt_theta( loss(pred_i, y_i) ) grad <- grad / batch_size # average gradient over the batch theta <- theta - eta * grad # descent step IF stopping_criterion_met(theta, grad): # e.g. ||grad|| < epsilon, or BREAK # validation loss stops improving RETURN theta ``` Every design choice in the recipe maps onto a concept students will meet repeatedly: `f_theta` is the hypothesis class, `loss` is the objective per example, the averaged `grad` computation is exactly , and the stopping criterion is where concerns about generalization (not just training loss) start to enter, typically via a held-out validation set.
Complexity & correctness
Time complexity. Suppose each gradient evaluation on a single example costs time, where is the number of parameters (this is a reasonable estimate for linear models and is roughly the cost of a forward-and-backward pass for many networks, up to architecture-dependent factors). Full-batch gradient descent costs per iteration since it touches all examples; over iterations that is . Stochastic or mini-batch gradient descent costs per step for batch size , so over steps — independent of per step, which is exactly why SGD scales to enormous datasets where full-batch descent is infeasible. The tradeoff is that SGD needs more iterations to reach a comparable accuracy (its per-step progress is noisier), but each iteration is cheaper, and in practice the net effect is almost always a win for large .
Space complexity. Both variants require space to store the parameters and gradient. Full-batch descent may also need if the whole dataset is held in memory simultaneously (mini-batch methods avoid this by streaming batches from disk).
Convergence rate (why it works, quantitatively). If is convex and -smooth (its gradient is -Lipschitz), gradient descent with step size satisfies
so the optimality gap shrinks as . If is additionally -strongly convex, convergence is linear (geometric): the gap shrinks as , i.e. exponentially fast in . These rates come directly from the descent lemma (a consequence of Taylor's theorem with the Lipschitz-gradient bound) applied inductively at each step — this is the calculus reasoning that justifies "just follow the gradient" rather than merely asserting it works.
Correctness argument for the framing itself. Why should minimizing over the training set say anything about , the risk on unseen data? This is where the Law of Large Numbers enters: for a fixed , is a sample average of i.i.d. random variables with mean , so as by the law of large numbers, and concentration inequalities (Hoeffding, for bounded losses) give explicit finite-sample bounds on with high probability. The subtlety is that is not fixed — it is chosen after seeing the data, specifically to make small, which can make an optimistic (biased-low) estimate of . This is exactly the overfitting phenomenon, and bounding the resulting generalization gap uniformly over the whole hypothesis class (via tools like VC dimension or Rademacher complexity) is the subject that later builds directly on this framing.
Honest tradeoffs.
- Convexity is a luxury: linear regression with squared loss and logistic regression with cross-entropy are convex in , guaranteeing global convergence, but neural network losses are non-convex, so gradient descent only guarantees a stationary point, not a global minimum — though in practice, for large overparameterized networks, most stationary points found in this way tend to generalize surprisingly well.
- A smaller loss on training data is not the goal; the goal is small risk on new data. Empirical risk minimization can be actively harmful if the hypothesis class is too expressive relative to , since the optimizer will happily exploit noise in the training set — the motivation for regularization, which augments with a penalty term to discourage overly complex solutions.
- The choice of loss function is not neutral: squared error is sensitive to outliers, 0/1 loss is not differentiable (hence rarely optimized directly), and different surrogate losses lead to different optimization landscapes and different trained models even for the same underlying task.
Worked example
Consider a tiny regression problem: predicting exam score from hours studied , hypothesis class (a line through the origin, one parameter for simplicity), and squared loss . Training set:
| (hours) | (score) |
|---|---|
| 1 | 2 |
| 2 | 3 |
| 3 | 7 |
Empirical risk:
Gradient:
Set to zero for the closed-form optimum (possible here since the model is linear and the loss is convex):
Now trace gradient descent starting at with learning rate , using the full gradient each step (full-batch, since is tiny):
| Step | Gradient | ||
|---|---|---|---|
| 0 | 0.000 | ||
| 1 | 0.967 | ||
| 2 | 1.483 | ||
| 3 | 1.757 | ||
| 4 | 1.904 | ||
| 5 | 1.981 |
Notice is climbing monotonically toward , with the step size shrinking each time because the gradient magnitude shrinks as approaches the minimizer — exactly the geometric convergence predicted for a strongly-convex quadratic objective. After a few dozen more steps would settle within numerical precision of , and would approach its minimum value. This tiny trace illustrates the whole pipeline: the hypothesis class () fixed what could be represented, the loss (squared error) fixed what "wrong" meant, and gradient descent searched for the value minimizing the empirical risk — arriving, up to numerical precision, at the same answer the closed-form normal equation gives, confirming the optimizer is behaving correctly.
Common pitfalls & traps
| Pitfall | Why it happens | Consequence |
|---|---|---|
| Confusing empirical risk with true risk | Training loss is computable, true risk is not, and it's tempting to treat them as equal | Overfitting: model looks great on training data, fails on new data |
| Using a non-differentiable loss without a workaround | 0/1 classification loss has zero gradient almost everywhere | Gradient descent makes no progress; need a differentiable surrogate (e.g. cross-entropy, hinge) |
| Picking a learning rate too large | Step size not matched to the curvature () of the objective | Divergence or oscillation instead of convergence |
| Ignoring non-convexity of the hypothesis class | Assuming neural network training behaves like convex linear regression | Optimizer converges to a poor local/saddle point; results depend on initialization |
| Evaluating "convergence" only on training loss | Stopping criterion checks alone | Misses the point where validation loss starts increasing (overfitting begins) |
| Treating the hypothesis class as infinitely flexible | Believing a bigger model is strictly better since it can fit training data better | Empirical risk goes to zero while true risk gets worse — classic overfitting failure |
Pioneers & history
The optimization view of learning did not arrive all at once; it crystallized from threads in statistics, control theory, and computer science over roughly a century.
Origins · 1 minAndrey Kolmogorov and how this was discovered
Kolmogorov's 1933 axiomatization of probability gave a rigorous meaning to "expected value under a distribution," the very object () that expected risk formalizes. Without a precise notion of expectation over an unknown distribution, the entire framing of learning as risk minimization would lack mathematical footing.
Vapnik, together with Alexey Chervonenkis, developed the theory (VC theory) that explains precisely when minimizing empirical risk is a sound strategy for minimizing expected risk, introducing measures of hypothesis-class complexity (VC dimension) that bound the generalization gap uniformly over .
Where this matters
Every major machine learning framework — from `scikit-learn`'s linear models to PyTorch and TensorFlow's neural network training loops — is built directly on this loop: define parameters, define a loss, compute gradients, step. Recommendation systems at streaming and e-commerce platforms fit collaborative-filtering models by minimizing a reconstruction loss over billions of user-item interactions using exactly the mini-batch stochastic gradient descent skeleton shown above. Large language models are trained by minimizing a cross-entropy loss (next-token prediction error) over enormous text corpora, using variants of stochastic gradient descent (Adam, and its relatives) at a scale of trillions of tokens and billions of parameters — the core loop is unchanged from the one-dimensional worked example above, only the dimensionality and the optimizer's bookkeeping have grown. Beyond pure ML, this optimization framing underlies A/B testing analysis (which model of user behavior minimizes prediction error on holdout data), computer vision pipelines (loss functions tailored to bounding-box overlap or pixel-level segmentation accuracy), and reinforcement learning (where policies are optimized to minimize expected negative reward, a direct generalization of expected risk). Anywhere a system needs to "learn" a mapping from data rather than have it hand-coded, some version of this recipe — hypothesis class, loss, empirical risk, gradient-based search — is doing the work underneath.
Ask the tutor: How does adding a regularization term change the shape of the optimization landscape and the resulting generalization guarantees?
Why do we need a hypothesis class at all — why not just search over "all functions"?
Searching over literally all functions from inputs to outputs is both computationally impossible (the space is infinite-dimensional and unstructured) and statistically hopeless: without restricting the space of candidates, a learner could fit training data perfectly by memorization while learning nothing generalizable, since there is no constraint tying its behavior at unseen points to its behavior at seen points. Restricting to a hypothesis class , such as linear functions or a bounded-depth neural network, injects an assumption ("the true relationship is approximately of this form") that makes the search tractable and gives the model a reason to generalize: nearby inputs get related outputs because the class itself enforces smoothness or structure.
Is squared error always the right loss function to minimize?
No. Squared error is a common default for regression because it is smooth, convex, and connects to Gaussian noise assumptions via maximum likelihood, but it is highly sensitive to outliers since errors are squared. For classification, squared error is a poor choice; cross-entropy (log loss) is preferred because it directly corresponds to maximizing the likelihood of the correct class under a probabilistic model and produces better-behaved gradients. The choice of loss function should reflect the true cost structure of mistakes in the application — for example, asymmetric losses are used when false negatives and false positives have very different real-world costs, such as in medical diagnosis.
What does it mean for the empirical risk to be convex, and why does it matter?
A function is convex if the line segment between any two points on its graph lies on or above the graph — intuitively, it has a single "bowl" shape with no other local dips. When is convex in (as with linear regression under squared loss or logistic regression under cross-entropy), any local minimum found by gradient descent is guaranteed to be the global minimum, so the optimizer cannot get stuck in a worse solution. Most deep learning objectives are non-convex, so this guarantee disappears, but gradient descent still tends to find good, if not provably optimal, solutions in practice.
How is regularization related to this optimization framing?
Regularization modifies the objective from pure empirical risk to a penalized version , where the penalty discourages complexity (e.g., large parameter magnitudes via an penalty). This changes what "minimizing the objective" means: the optimizer now trades off fitting the training data against keeping the model simple, which directly targets the overfitting problem inherent in raw empirical risk minimization. Regularization is a natural extension of the optimization framing rather than a departure from it — it is still gradient descent on a (slightly different) objective function.
Does this framing apply to unsupervised learning too?
Yes, with modification. Unsupervised methods like k-means clustering or autoencoders still minimize an objective (within-cluster distance, or reconstruction error) over a hypothesis class (cluster assignments, or encoder-decoder parameters), but there is no labeled to compare against — the "loss" is defined purely in terms of structure in itself, such as how well data points can be reconstructed or grouped. The optimization skeleton (hypothesis class, objective, gradient-based or combinatorial search) carries over even though the specific objective differs from supervised risk.
What happens if the hypothesis class does not contain a good approximation to the true relationship?
This is called approximation error (or bias): even the best possible within may have high expected risk, because no function in is close to the true relationship between and . This is distinct from the generalization gap, which is about the difference between empirical and expected risk for a fixed . Total error decomposes roughly into approximation error (choice of ) plus estimation/generalization error (finite , optimization) — a decomposition that motivates choosing a hypothesis class expressive enough to have low bias but not so expressive that it cannot be reliably estimated from the available data.
Why does gradient descent work even though it only uses local information (the gradient) rather than the whole shape of the function?
Gradient descent is justified by the first-order Taylor approximation: near the current point , the function looks approximately linear, and moving a small step opposite the gradient is guaranteed to decrease a linear approximation of the function, hence (for a small enough step and smooth enough function) the actual function too. This local-improvement guarantee, repeated many times, is enough to reach a minimum for convex functions, and a stationary point for non-convex ones — global information about the function's overall shape is not needed for each individual step, only for understanding what kind of point the process will ultimately converge to.