The Loss Function

A spam filter must decide, for every email, whether a mistake costs a false alarm or a missed threat. Both are errors, but they are not the same error. A good learning system must be told this distinction in a language a computer can optimize. That language is the loss function: a precise numerical score. It tells the algorithm exactly how bad a particular prediction is for a particular example. Without it, "learning" has no direction — gradient descent has nothing to descend. Every supervised machine learning system, from linear regression to the largest neural networks, is built on the same skeleton. Choose a model, choose a loss function, and minimize the average loss over data. The model architecture gets the attention, but the loss function is what actually defines the task. Change the loss and the same neural network becomes a classifier, a regressor, a ranker, or a generative model. This is why the loss function deserves to be understood as its own object of study. It is distinct from the optimizer that minimizes it and the model that it evaluates. This article isolates the per-example loss function: a function that takes one prediction and one true label. It returns a single real number measuring error. This is the atomic unit from which training objectives are built. Later ideas — Empirical Risk Minimization, regularized objectives, and Convex Functions and Convex Sets — all start by summing or averaging these per-example numbers. Getting this piece exactly right is foundational to everything downstream. By the end of this article you will be able to write down the loss function for a regression task and a classification task. You will be able to explain precisely why squared error and cross-entropy are the "correct" choices for their respective settings. You will trace a numeric example step by step. You will also recognize the common bugs that silently corrupt training — from sign errors to loss functions that reward the wrong thing entirely.

Key takeaways
  • A loss function assigns a single number to one (prediction, true label) pair, measuring how wrong that prediction is.
  • Loss functions encode the task: regression, classification, and ranking each demand a different mathematical shape of error.
  • Squared error is the natural loss under Gaussian noise assumptions; cross-entropy is the natural loss under a categorical/Bernoulli likelihood.
  • A well-designed loss is differentiable (or subdifferentiable) almost everywhere, so gradient-based optimizers can use it.
  • The per-example loss is later averaged over a dataset to form the training objective — the bridge to Empirical Risk Minimization.
  • Poor loss choice (not poor architecture) is one of the most common silent failure modes in real ML systems.
The core insight

A loss function turns the vague goal "be right" into a precise, differentiable number that an optimizer can actually minimize.

The idea

A loss function ℓ(y^,y)\ell(\hat{y}, y) is a map from a predicted output y^\hat{y} and a true label yy to a non-negative real number, ℓ:Y×Y→R≥0\ell: \mathcal{Y} \times \mathcal{Y} \to \mathbb{R}_{\ge 0}, satisfying ℓ(y,y)=0\ell(y, y) = 0 (a perfect prediction incurs zero penalty) and, informally, ℓ\ell increases as y^\hat{y} moves farther from yy in whatever sense is meaningful for the task. This is deliberately called the per-example or pointwise loss to distinguish it from the cost function or objective function, which aggregates the per-example loss over an entire dataset (typically by averaging), and from the risk, which is the expectation of the loss over the true data-generating distribution. This article treats the atomic building block; the aggregation step belongs to Empirical Risk Minimization. The loss function is where task semantics enter the mathematics. Building on Learning as Optimization — the idea that training is the search for parameters minimizing some numerical objective — the loss function is precisely the thing being minimized pointwise. A regression task cares about the magnitude of a numeric error, so its loss should grow with the distance ∣y^−y∣|\hat y - y|. A classification task cares about whether a predicted probability assigns enough mass to the correct class, so its loss should punish confident wrong answers severely and reward confident correct answers with near-zero cost. The functional form of ℓ\ell is not arbitrary decoration; it is derived, in the cleanest cases, from a probabilistic model of how the labels are generated — an idea called the maximum likelihood connection, developed below. Two properties matter enormously in practice, beyond just "small when correct, large when wrong." First, differentiability: gradient-based optimizers need ∂ℓ/∂y^\partial \ell / \partial \hat y to exist (or a usable subgradient) almost everywhere, since this gradient is what backpropagates into model parameters. Second, curvature and scale: a loss that is too flat gives vanishing gradients and slow learning; a loss that is too steep near outliers can make training unstable. These two properties — differentiability and well-behaved curvature — are exactly the concerns that motivate the later study of Convex Functions and Convex Sets, where guarantees about unique minima and well-conditioned optimization become precise.

How it works

The mechanism of "using" a loss function is simple to state and important to internalize step by step, because every training loop in every ML library repeats this exact sequence for every example (or batch of examples) it sees.

Step 1 — Forward pass. Given input xx, the model with current parameters θ\theta produces a prediction y^=fθ(x)\hat y = f_\theta(x). For regression this is a real number (or vector); for classification this is typically a probability distribution over classes.

Step 2 — Evaluate the loss. Combine the prediction y^\hat y with the true label yy using the chosen loss function to get a single scalar ℓ(y^,y)\ell(\hat y, y). This number is the entire signal the optimizer receives about how well this one example was handled.

Step 3 — Compute the gradient. Differentiate ℓ\ell with respect to the model's parameters via the chain rule: ∇θℓ=∂ℓ∂y^⋅∂y^∂θ\nabla_\theta \ell = \dfrac{\partial \ell}{\partial \hat y}\cdot \dfrac{\partial \hat y}{\partial \theta}. The first factor comes entirely from the choice of loss function; the second comes entirely from the model architecture. This factorization is exactly why loss and architecture are independent design choices.

Step 4 — Accumulate and update. Sum or average ℓ\ell (and its gradient) across a batch of examples, then take an optimization step (e.g. gradient descent) that adjusts θ\theta to reduce the loss. Below is a generic training loop pseudocode showing exactly where the per-example loss function is plugged in — it is a single function call, deliberately decoupled from the model and the optimizer. ``` function TRAIN(model, data, loss_fn, learning_rate, epochs): for epoch in 1..epochs: total_loss = 0 for (x, y) in data: y_hat = model.forward(x) # Step 1: prediction L = loss_fn(y_hat, y) # Step 2: per-example loss total_loss += L grad_yhat = loss_fn.gradient(y_hat, y) # dL/dy_hat grad_theta = model.backward(grad_yhat) # chain rule through model model.params -= learning_rate * grad_theta # Step 4: update report(epoch, total_loss / len(data)) return model

# Two concrete instantiations of loss_fn: function SQUARED_ERROR(y_hat, y): return (y_hat - y) ** 2 function SQUARED_ERROR_GRADIENT(y_hat, y): return 2 * (y_hat - y) function CROSS_ENTROPY(y_hat_probs, y_true_class):

# y_hat_probs is a probability vector, y_true_class is an index p = y_hat_probs[y_true_class] p = clip(p, epsilon, 1 - epsilon) # avoid log(0): edge case return -log(p) function CROSS_ENTROPY_GRADIENT(y_hat_probs, y_true_class): grad = copy(y_hat_probs) grad[y_true_class] -= 1 # softmax + cross-entropy simplification return grad ``` Two edge cases are worth flagging directly in the pseudocode's design. The `clip` in `CROSS_ENTROPY` guards against log⁡(0)=−∞\log(0) = -\infty, which occurs whenever the model assigns exactly zero probability to the true class — a real numerical hazard, not a theoretical curiosity. And the gradient simplification `grad[y_true_class] -= 1` is not arbitrary; it is the well-known closed form that results when cross-entropy loss is composed with a softmax output layer, collapsing what would otherwise be a more complex Jacobian into a single subtraction. The diagram below shows the two most common per-example losses as functions of the residual (for regression) or as functions of the predicted probability of the true class (for classification), making visible exactly why each is shaped the way it is.

Figure
Squared error grows quadratically with residual; cross-entropy explodes as predicted probability of the true class approaches zero
Squared Error Loss ℓ(ŷ,y) = (ŷ − y)² residual (ŷ − y) loss min at ŷ = y Cross-Entropy Loss ℓ = −log(p) p = predicted prob. of true class loss loss → 0 as p → 1 loss → ∞ as p → 0 Symmetric, quadratic penalty — good for continuous targets under Gaussian noise. Steep, one-sided penalty — punishes confident wrong classification harshly.

Complexity & correctness

Time complexity. Evaluating a per-example loss is essentially O(1)O(1) in the dimensionality of the output for scalar-output tasks like squared error, and O(K)O(K) for a KK-class cross-entropy loss (since it involves a sum or lookup over KK class probabilities, and typically a preceding softmax that costs O(K)O(K) to normalize). Computing its gradient with respect to y^\hat y costs the same order, O(1)O(1) or O(K)O(K), because differentiating a simple closed-form expression like (y^−y)2(\hat y - y)^2 or −log⁡py-\log p_y does not introduce new asymptotic cost. Crucially, evaluating the loss and its gradient is never the bottleneck in a training loop — the forward and backward passes through the model itself (a neural network with millions of parameters, say) dominate total cost, which is typically O(P)O(P) per example where PP is the parameter count. The loss function contributes a negligible additive term.

Space complexity. Storing a per-example loss value requires O(1)O(1) space (a scalar), and its gradient with respect to the output requires O(d)O(d) space where dd is the output dimension (e.g. O(K)O(K) for a KK-way classification gradient vector). This is dwarfed by the space needed to store the model's activations for backpropagation, which scales with network depth and width.

Correctness — why these specific forms are "right," not arbitrary. The deepest justification for a loss function's shape comes from statistics, via the maximum likelihood principle. Suppose we model the true label yy as generated from a distribution parameterized by the model's prediction: y∼p(y∣y^)y \sim p(y \mid \hat y). Maximizing the likelihood of the observed data is equivalent to minimizing the negative log-likelihood, and it turns out that this negative log-likelihood, computed per example, is the loss function. Concretely: if we assume regression targets are corrupted by additive Gaussian noise, y=y^+εy = \hat y + \varepsilon with ε∼N(0,σ2)\varepsilon \sim \mathcal{N}(0, \sigma^2), then

p(y∣y^)=12πσ2exp⁡(−(y−y^)22σ2).p(y \mid \hat y) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left(-\frac{(y-\hat y)^2}{2\sigma^2}\right).

Taking the negative log and discarding additive constants independent of y^\hat y gives

−log⁡p(y∣y^)=(y−y^)22σ2+const,-\log p(y\mid \hat y) = \frac{(y - \hat y)^2}{2\sigma^2} + \text{const},

which is exactly squared error up to a positive scaling constant. This is not a coincidence: squared error loss is the maximum-likelihood-correct loss precisely when the noise is Gaussian, and this derivation is the honest justification for its ubiquity, not mere convention. Similarly, if yy is a categorical label and y^\hat y is a predicted probability vector (say from a softmax layer) modeling yy as drawn from a categorical distribution, then the negative log-likelihood of the observed class is

−log⁡p(y∣y^)=−log⁡y^true class,-\log p(y \mid \hat y) = -\log \hat y_{\text{true class}},

which is exactly the cross-entropy loss written in the pseudocode above. Cross-entropy is the maximum-likelihood-correct loss for categorical outcomes. This derivation also explains the shape in the figure: as the assigned probability to the true class shrinks toward zero, the model is claiming an event is nearly impossible when it in fact occurred, and the likelihood principle correctly assigns this an unboundedly large penalty. A second correctness concern is calibration of the minimum: any admissible loss must satisfy ℓ(y,y)=0\ell(y, y) = 0 (or at least be minimized at y^=y\hat y = y), otherwise the optimizer is being steered toward the wrong target. Both squared error and cross-entropy satisfy this: squared error is trivially zero at y^=y\hat y = y, and cross-entropy is minimized (over the simplex of probability vectors, for a fixed true class) exactly when all probability mass is placed on the true class, which follows from Jensen's inequality applied to the concavity of log⁡\log.

Honest tradeoffs. Squared error is sensitive to outliers — because the penalty grows quadratically, a single badly-mispredicted example can dominate the gradient of an entire batch, motivating robust alternatives like absolute error or Huber loss (a hybrid that is quadratic near zero and linear for large residuals, sacrificing pure maximum-likelihood correctness for robustness). Cross-entropy assumes the model actually outputs a valid probability distribution; if the underlying model architecture doesn't produce a properly normalized softmax output, the "loss" no longer corresponds to any coherent likelihood and its gradients can behave unpredictably. Choosing a loss is therefore always an implicit statistical modeling choice, and getting it wrong for the noise/label structure of real data is a genuine, not merely cosmetic, error.

Worked example

Consider a tiny 3-class classifier (classes: cat, dog, bird) that, for one particular email... no — for one particular image, outputs the following softmax probabilities, and suppose the true label is dog.

ClassPredicted probability y^i\hat y_i
cat0.10
dog0.70
bird0.20

Step 1 — apply cross-entropy. The true class index is "dog," with predicted probability p=0.70p = 0.70.

ℓ=−log⁡(0.70)≈0.3567\ell = -\log(0.70) \approx 0.3567

Step 2 — compute the gradient w.r.t. the softmax output, using the simplified rule `grad[true_class] -= 1`:

Classy^i\hat y_iGradient ∂ℓ/∂y^i\partial \ell/\partial \hat y_i
cat0.100.10
dog0.700.70 − 1 = −0.30
bird0.200.20

Notice the gradient is negative for the true class (dog) and positive for the wrong classes — this is exactly the direction the optimizer needs: increase y^dog\hat y_{\text{dog}}, decrease the others. This is a direct numeric check that the gradient formula is correctly signed, not merely algebraically simplified.

Step 3 — contrast with a worse prediction. Suppose instead the model had been much less confident and, worse, wrong-leaning: y^=(0.60,0.05,0.35)\hat y = (0.60, 0.05, 0.35) for (cat, dog, bird), true label still dog.

ℓ=−log⁡(0.05)≈2.996\ell = -\log(0.05) \approx 2.996

Compare 0.35670.3567 versus 2.9962.996 — roughly an 8.4× larger loss for a prediction that assigned only 5% instead of 70% probability to the correct answer. This steep, non-linear blow-up as p→0p \to 0 is the direct numerical illustration of the curve in the figure above, and it is exactly the behavior we derived from the maximum-likelihood argument: confidently wrong predictions are punished disproportionately, which is precisely the intended incentive during training.

Step 4 — regression comparison, same data flavor. Now suppose a regression model predicts a house price y^=310,000\hat y = 310{,}000 against a true price y=300,000y = 300{,}000.

ℓ=(y^−y)2=(10,000)2=1.0×108\ell = (\hat y - y)^2 = (10{,}000)^2 = 1.0 \times 10^8

The raw magnitude looks enormous compared to the cross-entropy numbers above (order 11), which is exactly why in practice regression losses are often reported after normalizing (e.g., dividing by y2y^2 scale, or taking the square root to get RMSE in original units). This is a genuine practical pitfall: comparing raw loss magnitudes across tasks or across differently-scaled targets is meaningless, and only relative changes within a fixed task and fixed label scale are directly interpretable.

Common pitfalls & traps

PitfallWhat goes wrongFix
Using squared error for classificationTreats class labels as if they were ordered real numbers, producing weak, poorly-shaped gradients near decision boundariesUse cross-entropy (or another likelihood-based classification loss) so gradients correctly reflect probability mass
Forgetting to clip probabilities before `log``log(0)` produces −∞-\infty or `NaN`, silently corrupting an entire training runClip predicted probabilities to [ϵ,1−ϵ][\epsilon, 1-\epsilon] before taking the log
Sign error in the gradientOptimizer accidentally ascends the loss instead of descending, and training diverges or loss increases every stepNumerically verify gradient sign against a finite-difference check on a toy example
Mismatched loss and output activationE.g., feeding un-normalized logits directly into a probability-based cross-entropy formula instead of using the combined logits-based formulaUse a numerically stable fused implementation (e.g. log-softmax + NLL) rather than composing raw softmax and log separately
Comparing raw loss values across differently-scaled tasksConcluding "model A is better" purely because its loss number is smaller, when the label scales differNormalize losses (e.g. report RMSE, or per-class-balanced accuracy) before cross-task comparison
Ignoring class imbalance in cross-entropyA model that always predicts the majority class gets low average loss despite being useless on minority classesUse class-weighted loss or evaluate with balanced metrics, not just average loss

Pioneers & history

The modern loss function synthesizes ideas from statistics, decision theory, and optimization that predate machine learning by decades. Its rigorous justification via maximum likelihood traces to the foundations of mathematical statistics, and its practical use inside iterative learning algorithms was cemented once gradient-based training of neural networks became standard.

Origins · 1 minRonald A. Fisher and how this was discovered
RA
Ronald A. Fisher
1890–1962 · Founder of maximum likelihood estimation, the statistical principle that justifies squared error and cross-entropy as "correct" losses under Gaussian and categorical noise models respectively

History
1805
— Legendre publishes the method of least squares, the earliest form of squared-error loss minimization.
1912
— Fisher formalizes maximum likelihood estimation, providing the statistical justification for negative-log-likelihood losses.
1943
— McCulloch and Pitts propose the first mathematical neuron model, an early precursor to differentiable prediction functions.
1986
— Rumelhart, Hinton, and Williams popularize backpropagation, making gradient-based minimization of arbitrary differentiable losses practical at scale.
2010
s — Deep learning systems standardize cross-entropy and its variants (focal loss, label smoothing) as default losses for large-scale classification.

Where this matters

Every production machine learning system embeds a loss function choice as a first-class design decision, often more consequential than the choice of model architecture. Recommendation systems at companies like Netflix or Spotify use ranking-aware losses (e.g., pairwise or listwise losses) rather than plain cross-entropy, because the task is "rank items well," not "classify each item independently." Autonomous driving perception stacks use specialized regression losses (like the Huber loss mentioned earlier) for bounding-box coordinates, precisely because squared error is too sensitive to rare, large localization errors caused by sensor noise. Large language models are trained almost entirely with per-token cross-entropy loss against the next word, which is exactly the categorical maximum-likelihood loss derived above, applied at massive scale. Medical diagnosis classifiers frequently use class-weighted or focal loss variants specifically because false negatives (missed disease) and false positives carry wildly different real-world costs, and the loss function is the only place in the entire training pipeline where this asymmetry can be encoded. Understanding the loss function precisely — not just as "the thing minimized" but as an explicit statistical and task-specific design choice — is a prerequisite for reasoning correctly about Empirical Risk Minimization, the framework that formalizes how per-example losses aggregate into a training objective, and about the geometric guarantees studied in Convex Functions and Convex Sets that determine whether that objective can be reliably minimized at all.

Ask the tutor: How does averaging per-example loss over a dataset lead into Empirical Risk Minimization, and what assumptions does that averaging quietly rely on?

What is the difference between a loss function and a cost function?

A loss function, ℓ(y^,y)\ell(\hat y, y), measures the error on a single example — one prediction compared to one true label. A cost function (also called the objective or training objective) aggregates the loss over an entire dataset, typically by averaging: J(θ)=1N∑i=1Nℓ(fθ(xi),yi)J(\theta) = \frac{1}{N}\sum_{i=1}^N \ell(f_\theta(x_i), y_i). The loss function defines what "wrong" means pointwise; the cost function defines what the optimizer actually minimizes across all data. This aggregation step is exactly the subject of Empirical Risk Minimization, which formalizes why averaging per-example loss is a sensible proxy for true expected error.

Why not just use accuracy (percentage correct) as the loss function directly?

Accuracy is a step function of the model's parameters: it does not change smoothly as parameters shift slightly, and its gradient is zero almost everywhere and undefined at the jump points. Gradient-based optimizers, which need a smooth, differentiable signal to know which direction to adjust parameters, cannot use accuracy directly. Cross-entropy is used instead because it is a smooth, differentiable surrogate that shares the same overall minimum-error goal while providing a genuinely useful gradient everywhere. This gap between the true evaluation metric and the differentiable training loss is a fundamental and recurring theme across machine learning.

Is squared error ever the wrong choice for regression?

Yes. Squared error is optimal under the assumption that prediction errors are Gaussian-distributed and that large errors should be punished quadratically more than small ones. If the real data contains outliers, or if the true noise distribution is heavy-tailed, squared error over-penalizes rare large errors and can dominate the gradient, distorting training toward fitting outliers rather than the bulk of the data. In such cases, absolute error (which is linear in the residual, less sensitive to outliers) or Huber loss (quadratic near zero, linear far away) are more robust and often preferred choices.

Why does cross-entropy use a logarithm instead of, say, a linear penalty on (1 − p)?

The logarithm is not a stylistic choice; it falls directly out of the maximum likelihood derivation. If labels are modeled as draws from a categorical distribution with predicted probabilities y^\hat y, then the likelihood of the observed data is a product of predicted probabilities across independent examples, and taking the negative logarithm of that product converts it into a sum of −log⁡(y^i)-\log(\hat y_i) terms — exactly cross-entropy. Using a linear penalty like (1−p)(1-p) instead would not correspond to any valid probabilistic likelihood model and would lose the steep, principled penalty for confidently wrong predictions.

Can the same model be trained with different loss functions to do different tasks?

Yes, and this is precisely why loss functions are studied as an independent concept from model architecture. The same neural network backbone (say, a stack of fully connected layers) can be turned into a regressor by attaching squared error loss to a linear output, into a binary classifier by attaching binary cross-entropy to a sigmoid output, or into a multi-class classifier by attaching categorical cross-entropy to a softmax output. The architecture defines the space of functions being searched; the loss function defines what "good" means within that search, and swapping it changes the task entirely.

How does the loss function relate to convexity, covered later under Convex Functions and Convex Sets?

Some per-example losses, like squared error with respect to a linear model's parameters, are convex functions of the parameters — meaning they have a single global minimum with no misleading local dips. Others, like cross-entropy composed with a deep non-linear network, are not convex overall, even though the loss itself is convex in the model's output. Understanding exactly which piece of the pipeline is convex, and why that matters for optimization guarantees, is the focus of Convex Functions and Convex Sets; the per-example loss function is simply the first place convexity properties can start to appear or fail.

What happens if the loss function is not differentiable?

Some useful losses, like the hinge loss used in support vector machines (ℓ=max⁡(0,1−yy^)\ell = \max(0, 1 - y\hat y)), are not differentiable at every point but are still usable because they have a well-defined subgradient almost everywhere, which is sufficient for gradient-based optimization in practice. Losses with genuinely no usable gradient information anywhere (like plain accuracy, discussed above) cannot be used directly with gradient descent and instead require either a smooth surrogate loss or a fundamentally different, gradient-free optimization strategy.

Before this

Where this leads