Maximum Likelihood and Cross-Entropy Loss
Suppose you train a spam filter and it outputs "0.999 spam" for an email that turns out to be legitimate. Should this mistake cost the same as predicting "0.51 spam" for the same wrong email? Almost every practical classifier answers no. The mathematical reason traces back to a single principle: choose the parameters that make the observed labels most probable under the model. This principle is called maximum likelihood estimation (MLE). When applied to a model that outputs class probabilities via the Logistic Regression and the Sigmoid function, it produces exactly the cross-entropy loss. Every deep learning framework minimizes this loss by default. This derivation matters because cross-entropy is not an arbitrary "penalize wrong answers" heuristic bolted onto neural networks. It is the unique loss (up to scaling) that falls out of treating each label as a draw from a Bernoulli distribution. It comes from asking for the parameters most consistent with the data. Understanding this connection explains why cross-entropy loss is convex in the logits for logistic regression. It also explains why it punishes confident wrong predictions so severely. And it explains why it pairs naturally with the sigmoid and softmax activation functions rather than, say, mean squared error. The big picture is a two-step recipe used throughout statistics and machine learning. First, write down a probabilistic model of how labels are generated given inputs and parameters. Second, turn "maximize the likelihood of the data" into "minimize the negative log-likelihood." This negative log-likelihood becomes your training loss. This recipe generalizes far beyond binary classification. It is the same lens used to derive squared error from Gaussian noise assumptions. It also reappears when studying Naive Bayes Classifiers and other generative models. This article delivers a complete derivation of binary cross-entropy from the Bernoulli likelihood. It includes a worked numerical trace showing the loss landscape in action. It also includes a diagram of the computational graph connecting logits to loss. Finally, it offers an honest discussion of when this framework breaks (label noise, class imbalance). It also discusses how alternatives like exponential loss in AdaBoost and Exponential Loss make different modeling choices.
- Cross-entropy loss is the negative log-likelihood of a Bernoulli (or categorical) model of the labels.
- Maximum likelihood estimation picks parameters that maximize the probability of the observed data.
- Taking logs turns a product of probabilities into a sum, and flipping the sign turns maximization into minimization.
- The sigmoid output is interpreted as , making the Bernoulli assumption natural.
- Cross-entropy is convex in the logits for logistic regression, guaranteeing a unique global minimum.
- The same recipe (assume a noise model, take negative log-likelihood) generalizes to regression, softmax classification, and beyond.
Minimizing cross-entropy loss is exactly maximizing the likelihood of the labels under a Bernoulli model whose success probability is the model's sigmoid output.
The idea
Maximum likelihood estimation is a general principle for fitting probabilistic models: given data and a family of distributions indexed by parameters , choose to maximize the probability (density) of having observed exactly that data. Formally, if the data points are independent and identically distributed given , the likelihood function is
and MLE solves . In binary classification we model each label as a Bernoulli random variable whose success probability depends on the input through the model. Logistic regression defines this probability using the sigmoid of a linear score (the logit) :
Because is Bernoulli, its probability mass function can be written compactly for both outcomes at once:
Check this: if the exponent on vanishes and the expression reduces to ; if it reduces to . This single-formula trick is what lets us differentiate one expression instead of branching on cases. Assuming the training examples are independent given the inputs, the likelihood of the entire dataset is the product of these individual Bernoulli probabilities. Cross-entropy loss is defined as the negative logarithm of this likelihood, averaged (or summed) over the dataset — turning the maximization of a product into the minimization of a sum, which is both numerically stable and analytically convenient.
How it works
The derivation proceeds in five mechanical but important steps. Each step is a standard MLE manipulation that recurs throughout statistical learning theory.
Step 1 — Write the per-example likelihood. For example with true label and model prediction :
Step 2 — Form the joint likelihood over the dataset. Assuming conditional independence of labels given inputs and parameters:
Step 3 — Take the logarithm (log-likelihood). The logarithm is strictly increasing, so it preserves the location of the maximum while converting the product into a sum:
Step 4 — Negate and average to get a loss to minimize. Optimization libraries minimize by convention, and averaging (rather than summing) keeps the loss scale independent of dataset size:
This is exactly binary cross-entropy loss.
Step 5 — Differentiate and optimize. Because and , the chain rule yields a remarkably clean gradient with respect to the logit:
The gradient with respect to the weights follows from :
This is passed to an iterative optimizer such as gradient descent or a quasi-Newton method. ``` Algorithm: Fit logistic regression by maximum likelihood (cross-entropy minimization) Input: training pairs {(x_i, y_i)}, i = 1..n, learning rate eta, iterations T Output: weights w, bias b 1. Initialize w <- 0 (or small random values), b <- 0 2. for t = 1 to T: 3. z_i <- w^T x_i + b for all i // compute logits 4. yhat_i <- sigmoid(z_i) for all i // Bernoulli success prob. 5. J <- -(1/n) sum_i [ y_i log(yhat_i) + (1 - y_i) log(1 - yhat_i) ] 6. grad_z_i <- yhat_i - y_i for all i // dJ/dz_i 7. grad_w <- (1/n) sum_i grad_z_i x_i 8. grad_b <- (1/n) sum_i grad_z_i 9. w <- w - eta grad_w 10. b <- b - eta grad_b 11. return w, b ``` Two edge cases the pseudocode must respect in a real implementation: (a) if is exactly or due to floating point saturation, or overflows to , so production code clips into or fuses the sigmoid and log into a single numerically stable "log-sum-exp" formula; (b) the loop must handle (no data) by refusing to divide, though this is a degenerate input that should be rejected upstream.
Complexity & correctness
Time complexity. Each forward pass over examples with -dimensional features costs : computing all logits takes per example. The backward pass (gradient computation) reuses the same residuals and also costs to accumulate . If gradient descent runs for iterations, total time is . This is the same asymptotic cost as fitting linear regression by least squares via gradient descent — the probabilistic reinterpretation changes the loss function, not the per-step arithmetic cost.
Space complexity. Storing the dataset requires ; the parameters require ; intermediate logits and predictions require . Mini-batch variants reduce the per-step memory footprint to for batch size , trading more iterations for lower peak memory — the standard time/space tradeoff in large-scale learning.
Correctness argument. There are two things to verify: that minimizing is equivalent to maximizing likelihood, and that this minimization problem is well-behaved (has a unique solution reachable by gradient descent). Equivalence. The logarithm is a strictly monotonically increasing function, so for any two parameter settings ,
Hence , and dividing by the constant to average does not change the location of the minimizer. This proves as defined is minimized at exactly the MLE. Convexity. Write the loss for one example as a function of the logit :
Its second derivative with respect to is
for every , regardless of (this uses and the fact that the -dependence drops out after differentiating twice — a short calculation confirms the cross terms cancel). Since is an affine function of , and is convex in , the composition is convex in (convexity is preserved under affine pre-composition). A convex function bounded below and differentiable has the property that every stationary point (where the gradient is zero) is a global minimum — so gradient descent, run with a suitable step size, cannot get stuck in a bad local minimum. This is a much stronger correctness guarantee than is available for the non-convex loss surfaces of deep networks.
Honest tradeoffs. Convexity relies on the model being logistic regression specifically; once is produced by a deep network with nonlinear hidden layers, the same cross-entropy loss composed with the network is generally non-convex in the network's weights, even though it remains convex in the final logit. Cross-entropy also assumes labels are correctly Bernoulli-distributed given ; mislabeled data or heavy class imbalance violates this assumption and can make the MLE solution behave poorly (see pitfalls below). Finally, cross-entropy heavily penalizes confident wrong predictions ( blows up near ), which is a feature for calibrated probability estimates but a liability if a small fraction of labels are simply noise.
Worked example
Consider a 1-D toy dataset with a single feature (already centered/scaled) and label , and suppose the model has converged to , . We evaluate the loss on four training points to see cross-entropy in action.
| per-example loss | ||||
|---|---|---|---|---|
| 1.0 | 1 | 1.5 | 0.8176 | |
| -0.5 | 0 | -1.5 | 0.1824 | |
| 2.0 | 1 | 3.5 | 0.9707 | |
| -1.0 | 1 | -2.5 | 0.0759 |
Step through row 4 by hand, since it is the interesting case (a confident wrong-direction prediction). With , . Then
The true label is , but the model assigns it only a chance of being class 1 — a confidently wrong prediction. Its loss is
roughly 13 times larger than the loss on the correctly-and-confidently-classified point (row 3, loss ). This asymmetry is exactly the point of cross-entropy: because it is of a probability, loss grows without bound as for a positive example, so the objective aggressively pushes the optimizer to fix confident mistakes, while giving diminishing returns for making already-correct, already-confident predictions even more confident. Averaging the four losses gives the batch cross-entropy:
A gradient step would use for each row — note row 4 contributes , by far the largest-magnitude residual, so it dominates the gradient direction and pulls to correct this point on the next iteration. This is the mechanism by which cross-entropy "focuses" learning on the hardest current mistakes.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Numerical overflow in | Sigmoid saturates to exactly or in floating point for large | Use a fused, numerically stable "sigmoid cross-entropy from logits" formula instead of computing then separately |
| Confusing cross-entropy with KL divergence | Both involve ; people forget cross-entropy also contains the (fixed) entropy of the true distribution | Recall ; minimizing cross-entropy over is equivalent to minimizing KL since is constant |
| Using cross-entropy with hard 0/1 targets and MSE-style intuition | Assuming loss behaves like squared error near the optimum | Remember the loss is unbounded above near ; label smoothing is often used to soften this |
| Ignoring class imbalance | MLE with unweighted cross-entropy is biased toward the majority class when classes are skewed | Use class weights or a weighted log-likelihood reflecting a non-uniform prior |
| Treating output as calibrated probability without checking | Cross-entropy training encourages calibration only asymptotically with enough data and correct model class | Verify with a reliability diagram / calibration curve on held-out data |
| Applying softmax cross-entropy for multi-label problems | Softmax assumes mutually exclusive classes (a categorical, not independent Bernoullis) | Use independent per-class binary cross-entropy (sigmoid outputs) for multi-label tasks |
Pioneers & history
Origins · 1 minRonald A. Fisher and how this was discovered
Ronald Fisher formalized maximum likelihood estimation as a general method of statistical inference in the 1920s, building on earlier ideas from Gauss and Laplace. He proved foundational properties of MLE — consistency, efficiency, and asymptotic normality under regularity conditions — that make it the default estimation principle across statistics and machine learning today. His work on likelihood, alongside contributions to experimental design and analysis of variance, established much of the mathematical vocabulary (likelihood, sufficiency, information) still used in deriving loss functions.
Where this matters
Cross-entropy loss (or its multi-class generalization, softmax cross-entropy) is the default training objective for essentially every modern classifier: image classification networks, spam and fraud detectors, medical diagnosis models, and the token-prediction objective at the heart of large language models is itself a categorical cross-entropy over the vocabulary at each position. Search ranking systems and recommendation engines use binary cross-entropy to model click/no-click and like/dislike events as Bernoulli outcomes. Speech recognition systems historically trained acoustic models with cross-entropy before sequence-level objectives were layered on top. The same likelihood-based derivation underlies logistic regression in epidemiology and social science, where interpretable coefficients from MLE fits are reported directly as odds ratios. Any system that needs a calibrated probability — not just a class label — leans on the fact that cross-entropy-trained sigmoid/softmax outputs approximate under the MLE framework, which is why it is preferred over margin-based losses (like the hinge loss in SVMs) when probability estimates, not just decisions, are required downstream.
Ask the tutor: Can you show how this same maximum-likelihood recipe derives mean squared error from a Gaussian noise assumption in linear regression?
Is cross-entropy loss the same thing as log loss?
Yes — "log loss," "logistic loss," and "binary cross-entropy" all refer to the same quantity in the binary classification setting: the negative log-likelihood of Bernoulli-distributed labels under a sigmoid model. The terminology varies by community (statistics tends to say "log loss" or "deviance," while machine learning and information theory favor "cross-entropy"), but the formula is identical. For multi-class problems the analogous quantity is categorical cross-entropy with a softmax output, again equal to the negative log-likelihood of a categorical distribution.
How does cross-entropy relate to KL divergence and entropy?
Cross-entropy between the true label distribution and the model's predicted distribution decomposes as , where is the entropy of the true labels and is the Kullback–Leibler divergence measuring how much differs from . Since the true labels are fixed data, is a constant with respect to the model's parameters. Minimizing cross-entropy over the model is therefore exactly equivalent to minimizing the KL divergence from the model's predictions to the true label distribution — pushing predicted probabilities toward the empirical ones.
Why not just use mean squared error (MSE) for classification instead of cross-entropy?
MSE on sigmoid outputs produces a non-convex loss surface in the logits and, more importantly, its gradient vanishes when the sigmoid saturates near or — even if the prediction is badly wrong. Cross-entropy's gradient with respect to the logit is simply , which stays large exactly when the prediction is confidently incorrect, so learning continues to make rapid progress on hard mistakes. MSE also does not correspond to any standard probabilistic likelihood for binary labels, so it lacks the MLE justification and calibration properties cross-entropy enjoys.
Does this derivation extend to more than two classes?
Yes. Replace the Bernoulli distribution with a categorical (multinoulli) distribution over classes, and replace the sigmoid with the softmax function, . The same MLE argument gives categorical cross-entropy, , and the gradient with respect to the logits has the same clean form . This is the loss used to train virtually all multi-class deep classifiers and the token-prediction heads of language models.
What assumptions does this derivation silently rely on, and when do they fail?
The derivation assumes labels are conditionally independent given the inputs and correctly Bernoulli/categorical distributed with the modeled probability — i.e., no systematic label noise and no missing structure like correlated labels within a batch. It also assumes every example is equally informative; with severe class imbalance, unweighted MLE can be dominated by the majority class. When labels are noisy (a nontrivial fraction randomly flipped), the pure cross-entropy MLE can overfit to noise because it demands near-certainty on every training point; techniques like label smoothing or robust losses relax this to guard against exactly this failure.
How does this connect to Naive Bayes and AdaBoost?
Naive Bayes Classifiers also use maximum likelihood, but they model the joint distribution by assuming feature independence given the class, then apply Bayes' rule to get — a "generative" approach, versus logistic regression's "discriminative" direct modeling of . AdaBoost and Exponential Loss instead starts from a different loss (the exponential loss) rather than a Bernoulli log-likelihood, which produces a distinct set of update rules and a different notion of "margin" being maximized. Comparing the three highlights how the choice of underlying probabilistic (or margin-based) model determines the resulting loss function and optimization behavior.