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.

Key takeaways
  • 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 y^\hat{y} is interpreted as P(y=1∣x)P(y=1 \mid x), 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.
The core insight

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 θ\theta, choose θ\theta to maximize the probability (density) of having observed exactly that data. Formally, if the data points x1,…,xnx_1, \dots, x_n are independent and identically distributed given θ\theta, the likelihood function is

L(θ)=∏i=1np(xi∣θ),L(\theta) = \prod_{i=1}^n p(x_i \mid \theta),

and MLE solves θ^=arg⁡max⁡θL(θ)\hat{\theta} = \arg\max_\theta L(\theta). In binary classification we model each label yi∈{0,1}y_i \in \{0, 1\} as a Bernoulli random variable whose success probability depends on the input xix_i through the model. Logistic regression defines this probability using the sigmoid of a linear score (the logit) zi=w⊤xi+bz_i = w^\top x_i + b:

y^i=σ(zi)=11+e−zi,P(yi=1∣xi;w,b)=y^i.\hat{y}_i = \sigma(z_i) = \frac{1}{1 + e^{-z_i}}, \qquad P(y_i = 1 \mid x_i; w, b) = \hat{y}_i.

Because yiy_i is Bernoulli, its probability mass function can be written compactly for both outcomes at once:

P(yi∣xi)=y^i yi(1−y^i)1−yi.P(y_i \mid x_i) = \hat{y}_i^{\,y_i} (1 - \hat{y}_i)^{1 - y_i}.

Check this: if yi=1y_i = 1 the exponent on (1−y^i)(1-\hat y_i) vanishes and the expression reduces to y^i\hat y_i; if yi=0y_i = 0 it reduces to 1−y^i1 - \hat y_i. 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 ii with true label yiy_i and model prediction y^i=σ(zi)\hat y_i = \sigma(z_i):

P(yi∣xi;w,b)=y^i yi(1−y^i)1−yi.P(y_i \mid x_i; w, b) = \hat{y}_i^{\,y_i}(1-\hat{y}_i)^{1-y_i}.

Step 2 — Form the joint likelihood over the dataset. Assuming conditional independence of labels given inputs and parameters:

L(w,b)=∏i=1ny^i yi(1−y^i)1−yi.L(w, b) = \prod_{i=1}^n \hat{y}_i^{\,y_i}(1-\hat{y}_i)^{1-y_i}.

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:

ℓ(w,b)=log⁡L(w,b)=∑i=1n[yilog⁡y^i+(1−yi)log⁡(1−y^i)].\ell(w, b) = \log L(w,b) = \sum_{i=1}^n \Big[ y_i \log \hat{y}_i + (1-y_i)\log(1-\hat{y}_i) \Big].

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:

J(w,b)=−1n∑i=1n[yilog⁡y^i+(1−yi)log⁡(1−y^i)].J(w,b) = -\frac{1}{n}\sum_{i=1}^n \Big[ y_i \log \hat{y}_i + (1-y_i)\log(1-\hat{y}_i) \Big].

This JJ is exactly binary cross-entropy loss.

Step 5 — Differentiate and optimize. Because y^i=σ(zi)\hat y_i = \sigma(z_i) and σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)(1-\sigma(z)), the chain rule yields a remarkably clean gradient with respect to the logit:

∂J∂zi=1n(y^i−yi).\frac{\partial J}{\partial z_i} = \frac{1}{n}\left( \hat{y}_i - y_i \right).

The gradient with respect to the weights follows from zi=w⊤xi+bz_i = w^\top x_i + b:

∇wJ=1n∑i=1n(y^i−yi) xi.\nabla_w J = \frac{1}{n}\sum_{i=1}^n (\hat{y}_i - y_i)\, x_i.

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 y^i\hat y_i is exactly 00 or 11 due to floating point saturation, log⁡y^i\log \hat y_i or log⁡(1−y^i)\log(1-\hat y_i) overflows to −∞-\infty, so production code clips y^i\hat y_i into [ϵ,1−ϵ][\epsilon, 1-\epsilon] or fuses the sigmoid and log into a single numerically stable "log-sum-exp" formula; (b) the loop must handle n=0n=0 (no data) by refusing to divide, though this is a degenerate input that should be rejected upstream.

Figure
From logits to Bernoulli likelihood to cross-entropy loss: the computational graph
input x w·x + b logit z z = wᵀx + b sigmoid σ(z) ŷ = P(y=1|x) Bernoulli PMF ŷ^y (1-ŷ)^(1-y) true label y y ∈ {0,1} -log likelihood = cross-entropy J Forward pass: x → z → ŷ → likelihood → loss J

Complexity & correctness

Time complexity. Each forward pass over nn examples with dd-dimensional features costs O(nd)O(nd): computing all logits zi=w⊤xi+bz_i = w^\top x_i + b takes O(d)O(d) per example. The backward pass (gradient computation) reuses the same y^i−yi\hat y_i - y_i residuals and also costs O(nd)O(nd) to accumulate ∇wJ\nabla_w J. If gradient descent runs for TT iterations, total time is O(Tnd)O(Tnd). 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 O(nd)O(nd); the parameters ww require O(d)O(d); intermediate logits and predictions require O(n)O(n). Mini-batch variants reduce the per-step memory footprint to O(bd)O(bd) for batch size b≪nb \ll n, 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 JJ 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 θ1,θ2\theta_1, \theta_2,

L(θ1)≥L(θ2)  ⟺  log⁡L(θ1)≥log⁡L(θ2)  ⟺  −log⁡L(θ1)≤−log⁡L(θ2).L(\theta_1) \geq L(\theta_2) \iff \log L(\theta_1) \geq \log L(\theta_2) \iff -\log L(\theta_1) \leq -\log L(\theta_2).

Hence arg⁡max⁡θL(θ)=arg⁡min⁡θ(−log⁡L(θ))\arg\max_\theta L(\theta) = \arg\min_\theta \big(-\log L(\theta)\big), and dividing by the constant nn to average does not change the location of the minimizer. This proves J(w,b)J(w,b) as defined is minimized at exactly the MLE. Convexity. Write the loss for one example as a function of the logit zz:

ϕ(z,y)=−ylog⁡σ(z)−(1−y)log⁡(1−σ(z)).\phi(z, y) = -y\log\sigma(z) - (1-y)\log(1-\sigma(z)).

Its second derivative with respect to zz is

ϕ′′(z,y)=σ(z)(1−σ(z))≥0\phi''(z, y) = \sigma(z)(1-\sigma(z)) \geq 0

for every zz, regardless of yy (this uses σ′=σ(1−σ)\sigma' = \sigma(1-\sigma) and the fact that the yy-dependence drops out after differentiating twice — a short calculation confirms the cross terms cancel). Since z=w⊤x+bz = w^\top x + b is an affine function of ww, and ϕ\phi is convex in zz, the composition J(w,b)J(w,b) is convex in (w,b)(w,b) (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 y^\hat y 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 xx; 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 (log⁡\log blows up near 00), 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 xx (already centered/scaled) and label yy, and suppose the model has converged to w=2.0w = 2.0, b=−0.5b = -0.5. We evaluate the loss on four training points to see cross-entropy in action.

xix_iyiy_izi=2xi−0.5z_i = 2x_i - 0.5y^i=σ(zi)\hat y_i = \sigma(z_i)per-example loss −[yilog⁡y^i+(1−yi)log⁡(1−y^i)]-[y_i\log\hat y_i + (1-y_i)\log(1-\hat y_i)]
1.011.50.8176−log⁡(0.8176)=0.2014-\log(0.8176) = 0.2014
-0.50-1.50.1824−log⁡(1−0.1824)=−log⁡(0.8176)=0.2014-\log(1-0.1824) = -\log(0.8176) = 0.2014
2.013.50.9707−log⁡(0.9707)=0.0297-\log(0.9707) = 0.0297
-1.01-2.50.0759−log⁡(0.0759)=2.578-\log(0.0759) = 2.578

Step through row 4 by hand, since it is the interesting case (a confident wrong-direction prediction). With x4=−1.0x_4 = -1.0, z4=2(−1.0)−0.5=−2.5z_4 = 2(-1.0) - 0.5 = -2.5. Then

y^4=σ(−2.5)=11+e2.5≈11+12.182≈0.0759.\hat y_4 = \sigma(-2.5) = \frac{1}{1+e^{2.5}} \approx \frac{1}{1+12.182} \approx 0.0759.

The true label is y4=1y_4 = 1, but the model assigns it only a 7.6%7.6\% chance of being class 1 — a confidently wrong prediction. Its loss is

−log⁡(0.0759)≈2.578,-\log(0.0759) \approx 2.578,

roughly 13 times larger than the loss on the correctly-and-confidently-classified point (row 3, loss 0.02970.0297). This asymmetry is exactly the point of cross-entropy: because it is −log⁡-\log of a probability, loss grows without bound as y^→0\hat y \to 0 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:

J=0.2014+0.2014+0.0297+2.5784=3.01054≈0.7526.J = \frac{0.2014 + 0.2014 + 0.0297 + 2.578}{4} = \frac{3.0105}{4} \approx 0.7526.

A gradient step would use y^i−yi\hat y_i - y_i for each row — note row 4 contributes 0.0759−1=−0.92410.0759 - 1 = -0.9241, by far the largest-magnitude residual, so it dominates the gradient direction and pulls w,bw, b 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

PitfallWhy it happensFix
Numerical overflow in log⁡y^\log \hat ySigmoid saturates to exactly 0.00.0 or 1.01.0 in floating point for large ∣z∣\lvert z \rvertUse a fused, numerically stable "sigmoid cross-entropy from logits" formula instead of computing σ(z)\sigma(z) then log⁡\log separately
Confusing cross-entropy with KL divergenceBoth involve −∑plog⁡q-\sum p\log q; people forget cross-entropy also contains the (fixed) entropy of the true distributionRecall H(p,q)=H(p)+DKL(p∥q)H(p,q) = H(p) + D_{KL}(p\|q); minimizing cross-entropy over qq is equivalent to minimizing KL since H(p)H(p) is constant
Using cross-entropy with hard 0/1 targets and MSE-style intuitionAssuming loss behaves like squared error near the optimumRemember the loss is unbounded above near y^→0,y=1\hat y \to 0, y=1; label smoothing is often used to soften this
Ignoring class imbalanceMLE with unweighted cross-entropy is biased toward the majority class when classes are skewedUse class weights or a weighted log-likelihood reflecting a non-uniform prior
Treating output as calibrated probability without checkingCross-entropy training encourages calibration only asymptotically with enough data and correct model classVerify with a reliability diagram / calibration curve on held-out data
Applying softmax cross-entropy for multi-label problemsSoftmax 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
RA
Ronald A. Fisher
1890–1962 · Founder of modern statistical inference

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.

History
1922
Fisher formalizes maximum likelihood estimation and the concept of statistical "likelihood."
1943
McCulloch and Pitts propose an early mathematical model of a neuron with binary threshold outputs.
1958
Cox develops the logistic regression model for binary outcome data in biostatistics.
1986
Backpropagation popularized for training multi-layer networks, commonly paired with cross-entropy for classification.
2000
s–2010s: Cross-entropy loss becomes the standard default for training deep classifiers, including softmax cross-entropy in large-scale image and language models.

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 P(y∣x)P(y \mid x) 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 −[ylog⁡y^+(1−y)log⁡(1−y^)]-[y\log\hat y + (1-y)\log(1-\hat y)] 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 pp and the model's predicted distribution qq decomposes as H(p,q)=H(p)+DKL(p∥q)H(p, q) = H(p) + D_{KL}(p \parallel q), where H(p)H(p) is the entropy of the true labels and DKLD_{KL} is the Kullback–Leibler divergence measuring how much qq differs from pp. Since the true labels are fixed data, H(p)H(p) 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 00 or 11 — even if the prediction is badly wrong. Cross-entropy's gradient with respect to the logit is simply (y^−y)(\hat y - y), 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 KK classes, and replace the sigmoid with the softmax function, y^k=ezk/∑jezj\hat y_k = e^{z_k} / \sum_j e^{z_j}. The same MLE argument gives categorical cross-entropy, J=−1n∑i∑k1[yi=k]log⁡y^i,kJ = -\frac{1}{n}\sum_i \sum_k \mathbb{1}[y_i = k] \log \hat y_{i,k}, and the gradient with respect to the logits has the same clean form y^i,k−1[yi=k]\hat y_{i,k} - \mathbb{1}[y_i = k]. 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 P(x,y)P(x, y) by assuming feature independence given the class, then apply Bayes' rule to get P(y∣x)P(y \mid x) — a "generative" approach, versus logistic regression's "discriminative" direct modeling of P(y∣x)P(y \mid x). 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.

Before this

Where this leads