Maximum Likelihood

Maximum likelihood fits parameters by making the observed data most probable; for classifiers it becomes negative log-likelihood, cross-entropy, and a KL fit to the empirical distribution.

Intermediate · Undergraduate mathematics · about 18 minutes

Reading map and next steps

Intuition

The idea in plain words, before the symbols.

You observed data. Among all parameter settings your model allows, which one makes that exact data look least surprising?

Maximum likelihood answers by holding the observations fixed and moving the model parameters. A parameter setting is good when it assigns high probability, or high density for continuous data, to the values that actually appeared.

For a biased coin, if you saw 14 heads in 20 flips, the most likely head probability is not found by asking which coin is "fair." It is found by asking which value of θ\theta makes the sequence with 14 heads and 6 tails most plausible. The answer is θ^=14/20\hat\theta=14/20.

This same idea scales into deep learning. A classifier assigns probabilities to labels. A language model assigns probabilities to next tokens. Training by maximum likelihood means increasing the probability assigned to the observed labels or tokens. The negative log of that likelihood is the loss the optimizer actually minimizes.

One limit matters: likelihood is a score of parameters after the data are fixed. It is not, by itself, a posterior probability that a parameter is true. Bayesian inference adds a prior and normalizes over parameter values; maximum likelihood just finds the parameter value with the highest data score.

Study prompts for this section: Intuition
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Mathematics

Definitions, assumptions and the derivation.

Let X1,…,XnX_1,\dots,X_n be observed values treated as independent draws from a fixed parametric model family pθ(x)p_\theta(x). The model family and parameter space are chosen before fitting; maximum likelihood only moves θ\theta inside that family. All logarithms below are natural logarithms, so losses are measured in nats.

The likelihood is a function of the parameter:

L(θ)=∏i=1npθ(xi).L(\theta)=\prod_{i=1}^n p_\theta(x_i).

The data values are fixed inside this expression. The variable being optimized is θ\theta. Because products of many probabilities become tiny, we usually maximize log likelihood:

ℓ(θ)=log⁡L(θ)=∑i=1nlog⁡pθ(xi).\ell(\theta)=\log L(\theta)=\sum_{i=1}^n \log p_\theta(x_i).

Equivalently, training minimizes average negative log-likelihood:

LNLL(θ)=−1n∑i=1nlog⁡pθ(xi).\mathcal L_{\mathrm{NLL}}(\theta)=-\frac{1}{n}\sum_{i=1}^n \log p_\theta(x_i).

For a Bernoulli model with xi∈{0,1}x_i\in\{0,1\}, parameter space θ∈[0,1]\theta\in[0,1], and Pθ(X=1)=θP_\theta(X=1)=\theta, suppose ss observations are 11 and f=n−sf=n-s are 00. For an ordered sequence,

L(θ)=θs(1−θ)f,L(\theta)=\theta^s(1-\theta)^f,

and

ℓ(θ)=slog⁡θ+flog⁡(1−θ).\ell(\theta)=s\log\theta+f\log(1-\theta).

If the data record only the count ss rather than the ordered sequence, the likelihood also has a binomial coefficient (ns)\binom n s. That factor does not depend on θ\theta, so it does not change the MLE.

On the open interval 0<θ<10<\theta<1, the derivative is

dℓdθ=sθ−f1−θ.\frac{d\ell}{d\theta}=\frac{s}{\theta}-\frac{f}{1-\theta}.

When 0<s<n0<s<n, setting it to zero gives

θ^MLE=sn.\hat\theta_{\mathrm{MLE}}=\frac{s}{n}.

When s=0s=0 or s=ns=n, there is no interior critical point. On the closed interval [0,1][0,1], the MLE is the boundary value θ^MLE=0\hat\theta_{\mathrm{MLE}}=0 or θ^MLE=1\hat\theta_{\mathrm{MLE}}=1. On the open interval (0,1)(0,1), the maximum is not attained; the likelihood only approaches its supremum at the boundary. The demo displays θ∈[0.01,0.99]\theta\in[0.01,0.99] to avoid infinities from log⁡0\log 0.

This is not a coincidence. The MLE for this Bernoulli family is the empirical frequency because the best one-parameter Bernoulli distribution matches the observed mass on 11 and 00.

Now write the empirical distribution as

p^(1)=sn,p^(0)=fn.\hat p(1)=\frac{s}{n},\qquad \hat p(0)=\frac{f}{n}.

In this finite discrete setting, the average NLL is the cross-entropy from the empirical distribution to the model distribution:

LNLL(θ)=H(p^,pθ).\mathcal L_{\mathrm{NLL}}(\theta)=H(\hat p,p_\theta).
H(p^,pθ)=−∑x∈{0,1}p^(x)log⁡pθ(x).H(\hat p,p_\theta)=-\sum_{x\in\{0,1\}}\hat p(x)\log p_\theta(x).

And cross-entropy decomposes as

H(p^,pθ)=H(p^)+KL(p^∥pθ).H(\hat p,p_\theta)=H(\hat p)+\mathrm{KL}(\hat p\|p_\theta).

Here the empirical entropy is

H(p^)=−∑xp^(x)log⁡p^(x),H(\hat p)=-\sum_x \hat p(x)\log\hat p(x),

and the forward KL mismatch is

KL(p^∥pθ)=∑xp^(x)log⁡p^(x)pθ(x).\mathrm{KL}(\hat p\|p_\theta)=\sum_x \hat p(x)\log\frac{\hat p(x)}{p_\theta(x)}.

The sums are over x∈{0,1}x\in\{0,1\}. Terms with p^(x)=0\hat p(x)=0 contribute 00. If p^(x)>0\hat p(x)>0 but pθ(x)=0p_\theta(x)=0, the NLL and KL are infinite.

Since H(p^)H(\hat p) does not depend on θ\theta, maximum likelihood is equivalent here to minimizing the KL mismatch. If the model family cannot represent the empirical distribution exactly, MLE chooses the member of the family with the smallest mismatch inside that family.

The derivative of the average Bernoulli NLL with respect to θ\theta is

dLdθ=−p^θ+1−p^1−θ.\frac{d\mathcal L}{d\theta}=-\frac{\hat p}{\theta}+\frac{1-\hat p}{1-\theta}.

If θ\theta is produced by a logit aa with θ=σ(a)\theta=\sigma(a), then the chain rule gives

dLda=θ−p^.\frac{d\mathcal L}{da}=\theta-\hat p.

The demo reports this logit gradient. It is not the slope of the plotted curve with respect to θ\theta.

For neural classifiers, pθ(y∣x)p_\theta(y\mid x) is conditional on the input. The dataset objective is

−1n∑i=1nlog⁡pθ(yi∣xi).-\frac{1}{n}\sum_{i=1}^n \log p_\theta(y_i\mid x_i).

For language models, yiy_i is the next token at a position. The mechanism is the same: assign high probability to observed data, take logs, average, then use gradients to move parameters.

For continuous models, pθ(x)p_\theta(x) is a density rather than a probability mass. The likelihood scores density at the observed points; the probability of any exact point can be zero even while the likelihood density is high. Likelihood comparisons are meaningful within the same model and measurement units. The finite-sample objective is an empirical average of log density; a KL interpretation is clean when comparing expected NLL under a data-generating density to model densities with respect to the same base measure.

A three-toss example

Take the ordered sequence x=[1,1,0]x=[1,1,0], so L(θ)=θ2(1−θ)L(\theta)=\theta^2(1-\theta). Two candidates give L(1/2)=1/8L(1/2)=1/8 and L(3/4)=9/64L(3/4)=9/64; since 9/64>8/649/64>8/64, θ=3/4\theta=3/4 makes these data more probable, and because log⁡\log keeps the order of positive numbers, ℓ\ell and the negative log-likelihood rank the two the same way. The derivative ℓ′(θ)=2/θ−1/(1−θ)=(2−3θ)/(θ(1−θ))\ell'(\theta)=2/\theta-1/(1-\theta)=(2-3\theta)/\big(\theta(1-\theta)\big) vanishes at θ^=2/3\hat\theta=2/3, and ℓ′′(θ)=−2/θ2−1/(1−θ)2<0\ell''(\theta)=-2/\theta^2-1/(1-\theta)^2<0 on (0,1)(0,1), so this is the only maximum, with L(2/3)=4/27L(2/3)=4/27. Recording only the count s=2s=2 multiplies every value by (32)=3\binom32=3 and leaves the maximum where it is.

The likelihood is not a probability distribution over θ\theta:

∫01θ2(1−θ) dθ=13−14=112≠1.\int_0^1\theta^2(1-\theta)\,d\theta=\frac13-\frac14=\frac1{12}\ne1 .

So L(2/3)=4/27L(2/3)=4/27 is the probability of the observed sequence when θ=2/3\theta=2/3, not the probability that θ=2/3\theta=2/3. Change only the data, to x=[1,0,0,0]x=[1,0,0,0]: now L(θ)=θ(1−θ)3L(\theta)=\theta(1-\theta)^3, the maximum moves to θ^=1/4\hat\theta=1/4 and L(1/4)=27/256L(1/4)=27/256. The fitting principle is the same; the data changed.

For long sequences, compute ℓ(θ)=slog⁡θ+flog⁡(1−θ)\ell(\theta)=s\log\theta+f\log(1-\theta) directly rather than as the log of the product. A product of many probabilities is too small for floating point: with 1,1001{,}100 tosses at θ=1/2\theta=1/2, L=2−1100L=2^{-1100} rounds to 00 in double precision, while ℓ=−1100log⁡2≈−762.46\ell=-1100\log2\approx-762.46 is an ordinary number.

Study prompts for this section: Mathematics
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Code

The same calculation as runnable code, in the notation of the derivation.

import numpy as np

# Observed Bernoulli data: 1=head/success, 0=tail/failure.
# Shape: y is (n,), theta is a scalar.
y = np.array([1, 1, 0, 1, 1, 0, 1, 0, 1, 1,
              1, 0, 1, 1, 0, 1, 0, 1, 1, 1])

n = y.size
s = int(y.sum())
f = n - s
p_hat = s / n

def bernoulli_nll(theta):
    theta = np.clip(theta, 1e-12, 1 - 1e-12)
    return float(-(s * np.log(theta) + f * np.log(1 - theta)) / n)

def binary_entropy(p):
    return float(sum(-value * np.log(value) for value in [p, 1 - p] if value > 0))

def bernoulli_kl(p, theta):
    theta = np.clip(theta, 1e-12, 1 - 1e-12)
    out = 0.0
    if p > 0:
        out += p * (np.log(p) - np.log(theta))
    if p < 1:
        out += (1 - p) * (np.log(1 - p) - np.log(1 - theta))
    return float(out)

grid = np.linspace(0.01, 0.99, 99)
theta_grid_mle = grid[np.argmin([bernoulli_nll(t) for t in grid])]

# Closed-form MLE for Bernoulli.
theta_mle = p_hat

empirical_entropy = binary_entropy(p_hat)
kl_at_theta_04 = bernoulli_kl(p_hat, 0.4)

assert abs(bernoulli_nll(0.4) - (empirical_entropy + kl_at_theta_04)) < 1e-12

print("successes / n:", s, "/", n)
print("empirical p_hat:", round(p_hat, 3))
print("closed-form MLE:", round(theta_mle, 3))
print("grid MLE:", round(theta_grid_mle, 3))
print("NLL at theta=0.4:", round(bernoulli_nll(0.4), 3))
print("H(p_hat):", round(empirical_entropy, 3))
print("KL(p_hat || theta=0.4):", round(kl_at_theta_04, 3))

The code mirrors the math: the observations determine the empirical distribution, the likelihood is a function of θ\theta, and the minimum average NLL occurs at θ=p^\theta=\hat p.

The second block checks the three-toss example in exact fractions with Python's standard library, then shows the product of 1,1001{,}100 probabilities underflowing to 00 while the sum of logs stays finite.

from fractions import Fraction as F
from math import comb, log, log1p


def likelihood(data, theta):
    """Probability of this exact ordered sequence of 0s and 1s."""
    s = sum(data)
    return theta**s * (1 - theta) ** (len(data) - s)


def log_likelihood(s, f, theta):
    """s log(theta) + f log(1 - theta), added term by term; 0 log 0 counts as 0."""
    head = 0.0 if s == 0 else -float("inf") if theta == 0 else s * log(theta)
    tail = 0.0 if f == 0 else -float("inf") if theta == 1 else f * log1p(-theta)
    return head + tail


x = [1, 1, 0]
assert likelihood(x, F(1, 2)) == F(1, 8) and likelihood(x, F(3, 4)) == F(9, 64)
assert likelihood(x, F(2, 3)) == F(4, 27)                  # the maximum, at the fraction of heads
assert F(1, 3) - F(1, 4) == F(1, 12)                       # integral of theta^2 (1 - theta) over [0, 1]
assert comb(3, 2) * likelihood(x, F(2, 3)) == F(4, 9)      # count data: scaled by 3, same maximum
assert likelihood([1, 0, 0, 0], F(1, 4)) == F(27, 256)

# A long sequence: the product underflows to 0, the sum of logs does not.
print("product of 1,100 probabilities of 1/2:", 0.5**1100)
print("log-likelihood added term by term:", log_likelihood(550, 550, 0.5))
Study prompts for this section: Code
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Demo

Change an input, predict the result, and see which quantities respond.

ExploreChange one control at a time and name what responds.An optional observation guide follows the demo.

Explore Maximum Likelihood

Loading the interactive demo…

Observation guide

Optional and ungraded. Opening a guide saves nothing.

Choose what to inspect in Maximum Likelihood, then open its guide.

Choose the observed number of successes, then move the model parameter θ\theta. Before the likelihood curve appears, predict whether maximum likelihood should decrease θ\theta, leave it where it is, or increase it.

For i.i.d. Bernoulli observations, the order of the sequence does not affect the likelihood; the count of successes is the sufficient statistic.

The reveal shows the average negative log-likelihood curve, the MLE line, the entropy baseline, the KL mismatch, and the logit gradient. Moving θ\theta away from the empirical frequency increases the KL mismatch while the empirical entropy stays fixed.

The practice after the demo works the three-toss example by hand: what is fixed, two candidates, the maximum, what a likelihood is not, and a changed sequence.

Study prompts for this section: Demo
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Practice

One three-toss sequence by hand. Name what is fixed, compare two candidates, find the maximum, then change the data.

Loading the exercise…
In focus

Concept: Maximum Likelihood

What is the smallest example of Maximum Likelihood you can work through by hand, and what does it show?

BeforeDistributionsNextBayesian Inference
DetailsProbability

After the first pass

Go deeper

Optional material for a second reading. Sources are always shown; the other panels open from their headings or from these links, and closing one keeps what you wrote or revealed.
What to look for in each sectionChoose a section and what you expect to see in it, then read short advice.

Section by section

Choose what to look for in each section

Maximum likelihood fits parameters by making the observed data most probable; for classifiers it becomes negative log-likelihood, cross-entropy, and a KL fit to the empirical distribution.

Choose what to look for (no demo yet)01 / Intuition
Illustration of Bernoulli observations, a likelihood curve, and a model parameter moving toward the empirical optimum.
What to look for

Start with the picture, metaphor, or geometric mechanism.

Choose first

Choose what you expect to see in this section of Maximum Likelihood.

Questions to ask of the pictureChoose a part of the picture and what you expect, then read short advice.

Looking at the picture

Questions to ask of the picture

Maximum likelihood fits parameters by making the observed data most probable; for classifiers it becomes negative log-likelihood, cross-entropy, and a KL fit to the empirical distribution.

4 of 4 sections writtenNo live demo yet
Question

Which part of the picture should you look at first?

Choose first

Pick the part of the picture you expect to explain Maximum Likelihood.

Sources

References for this page

A reference shows where an idea comes from; it does not vouch for every step on this page.
book · 2016Deep LearningGoodfellow, Bengio, and Courville
Why it is cited

Grounds maximum likelihood as the standard objective behind many supervised and generative models.

Open source
paper · 1922On the mathematical foundations of theoretical statisticsFisher
Why it is cited

Philosophical Transactions of the Royal Society A 222, 309–368. Names and develops the method of maximum likelihood for estimating parameters, and distinguishes likelihood from probability.

Open source
What each claim rests on1 claim, each with its sources, where it appears on this page, and its caveats.

Claims and sources

Maximum likelihood fits parameters by making the observed data most probable; for classifiers it becomes negative log-likelihood, cross-entropy, and a KL fit to the empirical distribution.

Checked against the cited passages

The checks were made by this site, not by an independent reviewer.

Maximum likelihood treats observed data as fixed and fits parameters by maximizing the product of model probabilities, usually by maximizing summed log likelihood or minimizing negative log likelihood.
What the sources support

Goodfellow et al. present maximum likelihood in log space as a sum over examples and connect negative log likelihood to the supervised-learning objective used for probabilistic models.

Where to see it on this page
Equation 1
L(θ)=∏i=1npθ(xi).L(\theta)=\prod_{i=1}^n p_\theta(x_i).
Equation 2
ℓ(θ)=log⁡L(θ)=∑i=1nlog⁡pθ(xi).\ell(\theta)=\log L(\theta)=\sum_{i=1}^n \log p_\theta(x_i).
Caveat

This checks the likelihood objective, not a Bayesian posterior interpretation or a guarantee that the model family can represent the data-generating distribution.

StatusChecked against the cited passages.

Checked Goodfellow et al. chapters 5.5 and 5.6: section 5.5 defines theta_ML as argmax over theta of p_model(X;theta), decomposes i.i.d. data into a product over examples, then uses logs to turn the product into sum_i log p_model(x_i;theta). It also frames training as minimizing -E_data log p_model, NLL, or cross-entropy. Section 5.6 contrasts ML point estimates with Bayesian posterior distributions over theta.

Explain it without the pageWrite your own explanation before asking for feedback. Your draft and any hints stay while this page is open.

Practice · Maximum Likelihood

Try the idea in your own words

Maximum likelihood fits parameters by making the observed data most probable; for classifiers it becomes negative log-likelihood, cross-entropy, and a KL fit to the empirical distribution.

Concept · Selected for practice

Maximum Likelihood

What it rests on: Sources: Deep Learning; On the mathematical foundations of theoretical statistics

Context and links
Choose a task

Explain the mechanism

For Maximum Likelihood: What is the smallest example of Maximum Likelihood you can work through by hand, and what does it show? Explain your answer, including what changes, why, and which assumption matters.

No answer yet

A rough first thought is enough. Your draft stays when you change tasks.

Your draft stays on this page and is cleared when you leave or reload.

A little help · Explain

Open one hint at a time. These are suggestions, not your answer or a grade.

0 of 3 hints shown for this question.

    Clearing your answer keeps this help record. Outside help is your own report; this page cannot check it.

    Where am I stuck? (optional)
    Your own description, not an automatic diagnosis

    Choose one, or leave this unspecified. Select it again to clear it.

    Take your draft to a feedback conversation

    No AI feedback runs here. You can copy a prompt to use elsewhere; nothing is sent automatically. Review the text before sharing, and leave out private information.

    Write an attempt before copying a feedback prompt.

    A draft, or an AI reply to it, is not a test of what you have learned. To check that, try a different case later without help.

    Ask about this pagePick one item on this page and copy a prompt about it into an AI assistant you already use. Notes you write here stay in this browser.
    Ask about this pageClose
    ConceptMaximum LikelihoodSources: Deep Learning; On the mathematical foundations of theoretical statisticsassert abs(bernoulli_nll(0.4) - (empirical_entropy + kl_at_theta_04)) < 1e-12

    Your question

    Choose what your question is about

    Pick the idea, equation, source, code, claim, misconception or demo state you want to ask about. The prompt you copy includes it, so the answer can stay on that item.
    Next local actionNo local draft saved yet

    Open the draft below to save one note and next action in this browser.

    conceptProbability

    Maximum Likelihood

    Starting question

    What is the smallest example of Maximum Likelihood you can work through by hand, and what does it show?

    SourcesCheck the 2 cited sources listed under Sources.Notes can be saved for this item
    Points of view on this item

    Fixed prompts generated from this item. They are not comments from people or independent reviews.

    Learner’s first stepAsk what would make "Maximum Likelihood" feel predictable rather than familiar.
    Assumption

    The 2 cited sources must support this exact item, not just the surrounding topic.

    Source-checking summary

    Connect the definition to one equation, piece of code or demo before widening the discussion.

    Proposed experiment

    Change one input, then check that the same relationship holds in the mathematics, the code and the demo.

    Next action

    You can state the mechanism in your own words

    Evidence4 checks
    ObservationChecking for a saved observation
    ActionReady for one action
    PromptLearner prompt ready to copy
    Go to this item
    01ObservationChecking what this browser has saved
    02EvidenceChecking for a saved observation
    03SourcesCheck the 2 cited sources listed under Sources.
    04Next stepSave one next action
    Local action draftNo local draft saved yetOpen when you are ready to write one next action
    Local action draft

    This draft stays in this browser and is attached to this item only.

    No local draft saved.
    Evidence to inspect
    • What the 2 cited sources say about this exact item
    • The definition, its prerequisites, and a contrasting concept
    • The equation or code that makes the concept concrete
    • One demo state that shows what stays the same as the inputs change
    What would resolve this
    • You can state the mechanism in your own words
    • You can name the prerequisite that would clear up the confusion
    • You can predict how the result changes when one input changes
    Reference idconcept/concept-notebook/probability/maximum-likelihood concept:probability/maximum-likelihood