Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsProbability and Statistics

Maximum Likelihood Estimation

P1.D1050 min●●○ IntermediateReviewed Dec 1, 2026

Why this matters for machine learning

Fitting a model means choosing its parameters so that it explains the training data. Maximum likelihood is the principle behind the standard regression and classification losses: write the probability the model gives to the data, take the negative log, and minimize it.

  • Fitting a line to noisy points by minimizing mean squared error is maximum likelihood when the noise is Gaussian with a fixed spread. (P3.A2: Linear regression, coming soon)
  • Binary cross-entropy for logistic regression is the negative log-likelihood of Bernoulli labels, and training the model means maximizing that likelihood. (P3.A7: Logistic regression, coming soon)
  • Cross-entropy for a classifier with a softmax output is the negative log-likelihood of the true class. (P3.A8: Softmax regression, coming soon)
  • A language model is trained by maximizing the likelihood of each next token given the tokens before it, which is the average negative log-likelihood that pretraining reports. (P10.A1: What is a Large Language Model?, coming soon)
  • Adding a prior to the likelihood gives MAP estimation, where a prior that prefers small weights acts like a regularization penalty. (P1.D11: MAP estimation and priors)

Before this: Exponents and logarithms, Derivative rules, Common distributions, Expectation and variance, Joint, marginal and conditional probability

After this lesson you can

  • Define the likelihood of a data set as a function of the parameters (with the data fixed), explain why it is not a probability distribution over the parameters, and write it as a product for i.i.d. data
  • Take the log-likelihood and say why it is used (products underflow, sums are easier to differentiate, the log keeps the same maximizer), then derive the maximum-likelihood estimates for a coin (k/Nk/N), a Gaussian (sample mean and the 1/N1/N variance) and a categorical variable (counts divided by NN)
  • Show that maximizing the likelihood is minimizing the negative log-likelihood, and that this gives mean squared error for Gaussian noise with fixed σ\sigma, binary cross-entropy for Bernoulli outputs and cross-entropy for categorical outputs
  • State what maximum likelihood can get wrong: biased variance, an estimate of 00 or 11 from small data, a wrong model family, outliers, no closed form, and a likelihood with no maximum

A coin lands heads, heads, tails. Is it fair? Nobody can know for sure from three flips, but some biases explain the result better than others. A coin that lands heads 22 times in 33 is not strange, and a coin that is heads only 10%10\% of the time would rarely give this result. Is there a rule that picks the best bias, and does the same rule also fit a bell curve to data, a line to points, or a language model to text?

There is, and it is called maximum likelihood. Earlier lessons planted three seeds. P1.D2 multiplied densities at observed values, P1.D3 said that the negative log of a probability is a loss function, and P1.D5 wrote the probability of i.i.d. data as a product. This lesson combines them: choose the parameters that make the data you saw as probable as possible.

Data, a model family and the likelihood

Three ingredients are needed.

  • Data: NN observed values x1,…,xNx_1,\dots,x_N, assumed i.i.d. (P1.D5).
  • A model family: a distribution with a formula p(x∣θ)p(x\mid\boldsymbol\theta) and some unknown parameters θ\boldsymbol\theta. For a coin, θ\theta is the probability of heads. For a Gaussian (P1.D3), θ=(μ,σ)\boldsymbol\theta=(\mu,\sigma).
  • A question: which θ\boldsymbol\theta is best?

The formula p(x∣θ)p(x\mid\boldsymbol\theta) can be read in two ways. With θ\boldsymbol\theta fixed and xx free, it is a distribution that says how likely each outcome is. With the data xx fixed and θ\boldsymbol\theta free, it is a function that says how well each parameter value explains what was seen. That second reading is the likelihood:

Lik(θ)=p(x1,…,xN∣θ)=∏i=1Np(xi∣θ).\begin{aligned} \mathrm{Lik}(\boldsymbol\theta)&=p(x_1,\dots,x_N\mid\boldsymbol\theta)\\ &=\prod_{i=1}^{N}p(x_i\mid\boldsymbol\theta). \end{aligned}

The product comes from independence (P1.D5). Notation. Many books write L(θ)L(\theta) or L(θ)\mathcal{L}(\theta) for the likelihood. This course already uses LL and L\mathcal{L} for a loss (one example and the average), so the likelihood is written Lik\mathrm{Lik}, the log-likelihood LL\mathrm{LL} and the negative log-likelihood NLL\mathrm{NLL}.

ProbabilityLikelihood
parameters θ\boldsymbol\thetafixedvary
datavary over outcomesfixed (observed)
adds up to 11 overthe outcomesnothing in general

P1.D2 already computed two likelihoods. A fair die that shows 3,3,53,3,5 gives (16)3=0.0046\left(\frac16\right)^3=0.0046. Waiting times 0.50.5 and 11 under the exponential density λe−λx\lambda\mathrm{e}^{-\lambda x} with λ=1\lambda=1 give e−0.5⋅e−1=0.2231\mathrm{e}^{-0.5}\cdot\mathrm{e}^{-1}=0.2231. For continuous data this product is a product of densities, so it is not itself a probability, but it can still be compared between parameter values for the same data. Try λ=2\lambda=2: the product is 2e−1⋅2e−2=0.19912\mathrm{e}^{-1}\cdot2\mathrm{e}^{-2}=0.1991, lower than 0.22310.2231, so λ=1\lambda=1 explains these two waits better than λ=2\lambda=2. The best rate turns out to be λ^=43\hat\lambda=\frac43, with likelihood 0.24060.2406 (a Go-deeper box below derives it).

The coin has the same structure. After H, H, T, each candidate bias θ\theta gives the data the probability θ⋅θ⋅(1−θ)\theta\cdot\theta\cdot(1-\theta):

θ\thetaLik(θ)=θ2(1−θ)\mathrm{Lik}(\theta)=\theta^2(1-\theta)
0.50.50.1250.125
0.60.60.1440.144
2/32/30.14810.1481
0.80.80.1280.128
0.90.90.0810.081

The likelihood rises and then falls, with its top near 2/32/3. The next section shows that θ=2/3\theta=2/3 is exactly the best.

The coin: from a picture to a formula

Suppose kk of NN flips are heads. For any order of flips, the likelihood of the whole sequence is a product of kk factors θ\theta and N−kN-k factors 1−θ1-\theta:

Lik(θ)=θk(1−θ)N−k.\mathrm{Lik}(\theta)=\theta^{k}(1-\theta)^{N-k}.

(If only the count of heads is recorded, the binomial formula of P1.D3 adds a factor (Nk)\binom Nk. It does not depend on θ\theta, so it does not move the peak.) Use the widget to see the shape before doing any algebra.

Likelihood of a coin’s bias

00.20.40.60.8100.51θ

Vertical axis: Lik(θ) divided by its largest value, so the peak is always 1. The shaded area is what a density would need to make 1. peak θ̂ = k/N

data: 2 of 3
θ-hat = k/N = 0.667
Lik at the peak = 0.1481
Lik(θ) at the point = 0.125
ln Lik at the peak = −1.91
ln Lik(θ) = −2.079
area under Lik over θ ∈ [0, 1] = k!(N−k)!/(N+1)! = 0.0833 (a density would have 1)

2 heads in 3 flips. The peak is at θ̂ = k/N = 2/3 = 0.667, and the bump is narrower with more data: its width (roughly one standard deviation) is about √(θ̂(1−θ̂)/N) = 0.272. At θ = 0.5 the likelihood is 0.844 of its peak. The area under the likelihood over θ from 0 to 1 is 0.0833, not 1.

Drag on the plot, or focus the dot and use the arrow keys (Page Up and Page Down move 0.1; Home and End jump to 0 and 1).

The likelihood of a coin’s bias θ for k heads in N flips. The vertical axis shows the likelihood divided by its largest value (the real peak is about 1e−30 for 60 heads in 100 flips), or switch to the log-likelihood. The pink dashed line marks the peak at k/N; the blue dot is a point you move to try a bias. The shaded area is what a probability density would need to make 1. Presets: the H, H, T example, three heads in three flips, six in ten, and sixty in a hundred. The readouts give the exact peak value and the area under the likelihood.

What to try:

  • H, H, T. The peak is at 2/32/3. The likelihood there is 49⋅13=427=0.1481\frac49\cdot\frac13=\frac4{27}=0.1481, and at the fair-coin value 0.50.5 it is 0.1250.125.
  • More data. Switch between 66 in 1010 and 6060 in 100100: the peak stays at 0.60.6 but the bump gets much narrower. At θ=0.5\theta=0.5 the likelihood is 82%82\% of the peak with 1010 flips and 13%13\% of the peak with 100100 flips. More data rules out more biases.
  • Three heads in three. The peak is at the edge, θ=1\theta=1. Keep that in mind: it is the first warning sign of this lesson.
  • The area. For H, H, T the area under the curve is ∫01θ2(1−θ) dθ=13−14=112=0.0833\int_0^1\theta^2(1-\theta)\,d\theta=\frac13-\frac14=\frac1{12}=0.0833, not 11.

That last point is worth a pause. For a fixed θ\theta, the likelihoods of all 23=82^3=8 possible sequences add up to 11 (they are probabilities of outcomes). For fixed data, the likelihood over all θ\theta adds up to something else. The likelihood is not a probability distribution over θ\theta, and “the likelihood of θ=0.6\theta=0.6 is 0.1440.144” does not mean “θ=0.6\theta=0.6 has probability 14.4%14.4\%”. It means: if the bias were 0.60.6, the data would have had probability 0.1440.144.

Finding the peak with calculus

Take the log first (the next section explains why that is allowed):

LL(θ)=kln⁡θ+(N−k)ln⁡(1−θ).\mathrm{LL}(\theta)=k\ln\theta+(N-k)\ln(1-\theta).

At a maximum the derivative is zero (P1.C1, P1.C2):

d LLdθ=kθ−N−k1−θ=0.\frac{d\,\mathrm{LL}}{d\theta}=\frac{k}{\theta}-\frac{N-k}{1-\theta}=0.

Multiply through by θ(1−θ)\theta(1-\theta): k(1−θ)=(N−k)θk(1-\theta)=(N-k)\theta, so k=Nθk=N\theta and

θ^=kN.\hat\theta=\frac kN.

The hat means “estimate”. This is a maximum, not a minimum, because the second derivative −kθ2−N−k(1−θ)2-\frac{k}{\theta^2}-\frac{N-k}{(1-\theta)^2} is negative (the curve bends downward everywhere). For H, H, T, θ^=23\hat\theta=\frac23. The estimate is the fraction of heads, which is what intuition says. Maximum likelihood is a principle that gives the obvious answer here and a useful answer where intuition fails.

Why the log?

Almost nobody maximizes the likelihood itself. They maximize its logarithm, the log-likelihood

LL(θ)=ln⁡Lik(θ)=∑i=1Nln⁡p(xi∣θ),\mathrm{LL}(\boldsymbol\theta)=\ln\mathrm{Lik}(\boldsymbol\theta)=\sum_{i=1}^{N}\ln p(x_i\mid\boldsymbol\theta),

for three reasons, the first two from P1.A2 and P1.A3.

  1. The maximizer does not change. The log is an increasing function, so a bigger likelihood always has a bigger log. Whichever θ\boldsymbol\theta wins on one wins on the other. For the coin, θ=0.5, 2/3, 0.8\theta=0.5,\ 2/3,\ 0.8 have likelihoods 0.125, 0.1481, 0.1280.125,\ 0.1481,\ 0.128 and log-likelihoods −2.0794, −1.9095, −2.0557-2.0794,\ -1.9095,\ -2.0557: the same ranking.
  2. A product becomes a sum. Sums are far easier to differentiate than products: the derivative of a sum is the sum of the derivatives, one small piece per example. The coin derivative above would have been a mess without it.
  3. Products underflow. A computer stores a float with a smallest positive value of about 5×10−3245\times10^{-324}. Multiply 10001000 probabilities of 0.10.1 and the true product, 10−100010^{-1000}, is rounded to 0.0. The sum of the logs is 1000ln⁡0.1=−2302.5851000\ln0.1=-2302.585, an ordinary number. (When probabilities have to be added inside a log, as in a mixture, the stable trick is log-sum-exp, P1.G2.)

The log-likelihood of probabilities is never positive, since ln⁡p≤0\ln p\le0 when p≤1p\le1. For densities, which can exceed 11 (P1.D2), a log-likelihood can be positive. Its size also changes if the data are measured in different units, so compare log-likelihoods only for the same data.

The recipe, and the negative log-likelihood

Everything in this lesson follows one recipe.

  1. Choose a model family p(x∣θ)p(x\mid\boldsymbol\theta).
  2. Write the likelihood ∏ip(xi∣θ)\prod_i p(x_i\mid\boldsymbol\theta) and take its log.
  3. Find the θ\boldsymbol\theta that maximizes it: set the gradient to zero (P1.C5) if you can solve that, or climb numerically if you cannot.
  4. Check that it is a maximum, not a minimum or a saddle.

The answer is the maximum-likelihood estimate (MLE):

θ^=arg⁡max⁡θ Lik(θ)=arg⁡max⁡θ LL(θ)=arg⁡min⁡θ NLL(θ).\begin{aligned} \hat{\boldsymbol\theta}&=\arg\max_{\boldsymbol\theta}\ \mathrm{Lik}(\boldsymbol\theta)\\ &=\arg\max_{\boldsymbol\theta}\ \mathrm{LL}(\boldsymbol\theta)\\ &=\arg\min_{\boldsymbol\theta}\ \mathrm{NLL}(\boldsymbol\theta). \end{aligned}

The negative log-likelihood is NLL=−LL\mathrm{NLL}=-\mathrm{LL}. Optimization software minimizes, so a loss is written as an NLL, and minimizing it is the same as maximizing the likelihood. Because the NLL of NN examples grows with NN, training usually uses the average NLL, 1NNLL\frac1N\mathrm{NLL}. This is the number a framework reports as “the loss”: by default PyTorch’s cross-entropy losses average over the examples. Dividing by NN is a positive constant, so it does not change the argmax. A loss written as L\mathcal L in this course is such an average.

One more fact is used all the time. If θ^\hat\theta is the MLE of θ\theta, then g(θ^)g(\hat\theta) is the MLE of g(θ)g(\theta) for a one-to-one function gg (such as the square root of the variance): the MLE of a standard deviation is the square root of the MLE of the variance.

A Gaussian: slide it over the data

Now a model with two parameters. The data are real numbers and the family is the Gaussian p(x∣μ,σ)=1σ2πe−(x−μ)2/(2σ2)p(x\mid\mu,\sigma)=\frac{1}{\sigma\sqrt{2\pi}}\mathrm{e}^{-(x-\mu)^2/(2\sigma^2)} (P1.D3). Each data point gets a bar: the height of the curve above it. The likelihood is the product of the bars, and the log-likelihood is the sum of the logs of the bars. Slide the curve until that sum is as large as it can be.

Slide a Gaussian over the data

Six values: 2, 3, 3.5, 4.5, 5, 6. The curve is a Gaussian with centre μ and spread σ.

01234567800.20.40.60.8x

data point bar: density the curve gives that point sample mean x̄

012345678−40−20μ

now best μ for this σ (the sample mean) LL = log-likelihood

μ = 2.5
σ = 1
log-likelihood LL = sum of the 6 log-bars = −17.51
likelihood = product of the bars = 2.48e−8
average NLL = −LL/N = 2.919
sample mean x̄ = 4
σ-hat (divide by N) = 1.3229
best possible LL = −10.19; now it is −7.32 from it

μ = 2.5 is 1.5 to the left of the sample mean 4; the best centre is x̄ whatever σ is. The curve is narrower than the best width for this centre (2): the point at 6 gets only 8.73e−4, which drags the sum of logs down. The log-likelihood is −17.51, which is 7.32 below the best possible −10.19.

Show the bar for each point
point xbar p(x)ln p(x)
20.3521−1.0439
30.3521−1.0439
3.50.242−1.4189
4.50.054−2.9189
50.0175−4.0439
68.727e−4−7.0439
sum of the logs = LL−17.5136

Drag on either plot, or focus the dot on the curve and use the arrow keys (one step is 0.05; Page Up and Page Down move 0.5; Home and End jump to the ends). The bars are drawn to scale; the top of the vertical axis changes when the curve gets very narrow.

Slide a Gaussian over the data. Top: the data points (dark dots on the line), a Gaussian curve with centre μ and spread σ, and one blue bar per point up to the curve. The pink dashed line is the sample mean x̄. Below: the log-likelihood (the sum of the logs of the bars) against μ with σ fixed, or against σ with μ fixed. Drag on either plot or use the sliders. The dot on the curve and the arrow keys also move μ. The buttons jump to the best μ, the best σ for the current μ, or the maximum of both. The readouts give the log-likelihood, the product of the bars, the average negative log-likelihood and the best possible value. Open the table to see every bar and its log. Four data sets: six points, the same with an outlier, two clusters, and six equal values.

What to try, with the six points 2, 3, 3.5, 4.5, 5, 62,\ 3,\ 3.5,\ 4.5,\ 5,\ 6:

  • Slide μ. Start with σ=1\sigma=1. The log-likelihood is a downward parabola in μ\mu with its top exactly at the sample mean xˉ=4\bar x=4. At μ=4, σ=1\mu=4,\ \sigma=1 it is −10.76-10.76.
  • Slide σ. Keep μ=4\mu=4. Too narrow (σ=0.3\sigma=0.3) and the points far from the centre get almost no density: the log-likelihood is −56.62-56.62 and the likelihood is 2.6×10−252.6\times10^{-25}. Too wide (σ=5\sigma=5) and every bar is low: −15.38-15.38. The top is at σ=1.3229\sigma=1.3229, where the log-likelihood is −10.19-10.19.
  • The two buttons. “Best μ (keep σ)” always lands on xˉ\bar x, whatever σ is. “Best σ (keep μ)” changes with μ: if the centre is off, the best spread is larger, because the curve must cover the distance to the points.
  • The outlier. Replacing 66 by 1212 moves the best centre from 44 to 55 and the best σ\sigma from 1.321.32 to 3.283.28. One point drags both estimates, because the Gaussian likelihood penalizes distance squared.
  • Two clusters. The best Gaussian is centred at 44, between the clusters, with the huge spread 2.532.53. Maximum likelihood finds the best member of the family you chose, even when the family is a bad description. (A model with two humps, centred at 1.51.5 and 6.56.5 with spread 0.410.41 and half the weight each, does far better: log-likelihood −7.30-7.30 against −14.09-14.09, P3.C2.)
  • All equal. The six values are all 44. Centre the curve at 44 and shrink σ\sigma: the log-likelihood keeps growing, so there is no best σ\sigma. The next section explains why, and the slider stops at 0.050.05.

The derivation

Write the log-likelihood of the Gaussian by taking the log of each factor and adding:

LL(μ,σ)=−Nln⁡σ−N2ln⁡(2π)−12σ2∑i=1N(xi−μ)2.\begin{aligned} \mathrm{LL}(\mu,\sigma)={}&-N\ln\sigma-\frac N2\ln(2\pi)\\ &-\frac{1}{2\sigma^2}\sum_{i=1}^N(x_i-\mu)^2. \end{aligned}

The partial derivatives (P1.C4) are set to zero one at a time. For μ\mu:

∂ LL∂μ=1σ2∑i(xi−μ)=0⇒ μ^=1N∑ixi=xˉ.\begin{aligned} \frac{\partial\,\mathrm{LL}}{\partial\mu}&=\frac1{\sigma^2}\sum_{i}(x_i-\mu)=0\\ \Rightarrow\ \hat\mu&=\frac1N\sum_i x_i=\bar x. \end{aligned}

The factor σ2\sigma^2 cancels, so the best centre is the sample mean for every σ\sigma (the pink line in the widget). For σ\sigma, put μ^\hat\mu back in and differentiate:

∂ LL∂σ=−Nσ+1σ3∑i(xi−μ^)2=0⇒ σ^2=1N∑i(xi−xˉ)2.\begin{aligned} \frac{\partial\,\mathrm{LL}}{\partial\sigma}&=-\frac N\sigma+\frac1{\sigma^3}\sum_i(x_i-\hat\mu)^2=0\\ \Rightarrow\ \hat\sigma^2&=\frac1N\sum_i(x_i-\bar x)^2. \end{aligned}

For these two equations the critical point is the global maximum, as the widget’s picture suggests (a rigorous check uses the second derivatives). For the six points, ∑(xi−4)2=10.5\sum(x_i-4)^2=10.5, so σ^2=10.5/6=1.75\hat\sigma^2=10.5/6=1.75 and σ^=1.3229\hat\sigma=1.3229. At that point the bars are 0.09620.0962, 0.22660.2266, 0.28080.2808, 0.28080.2808, 0.22660.2266 and 0.09620.0962, with logs −2.34-2.34, −1.48-1.48, −1.27-1.27, −1.27-1.27, −1.48-1.48 and −2.34-2.34, which add to −10.19-10.19. (In general LL(μ^,σ^)=−N2ln⁡(2πe σ^2)\mathrm{LL}(\hat\mu,\hat\sigma)=-\frac N2\ln(2\pi\mathrm{e}\,\hat\sigma^2), and the average NLL here is 1.69871.6987.)

This is the 1/N1/N variance. Maximum likelihood divides the sum of squares by NN, not by N−1N-1. P1.D4 showed that dividing by N−1N-1 (Bessel’s correction) gives an unbiased estimate of σ2\sigma^2. The 1/N1/N version is biased low: averaged over many data sets of size NN, it equals N−1Nσ2\frac{N-1}{N}\sigma^2, which is 80%80\% of the truth for N=5N=5 (a simulation in the code section gives 3.23.2 for a true variance of 44). The estimator is still consistent (it homes in on σ2\sigma^2 as NN grows), and the two versions agree for large NN. Maximum likelihood does not promise unbiasedness. NumPy’s np.var divides by NN, so it is the MLE; np.var(x, ddof=1) divides by N−1N-1.

Several dimensions. For vectors, maximum likelihood with the multivariate Gaussian of P1.D7 gives the sample mean vector μ^=xˉ\hat{\boldsymbol\mu}=\bar{\mathbf{x}} and the covariance matrix with the 1/N1/N factor, Σ^=1N∑i(xi−xˉ)(xi−xˉ)⊤\hat{\boldsymbol\Sigma}=\frac1N\sum_i(\mathbf{x}_i-\bar{\mathbf x})(\mathbf{x}_i-\bar{\mathbf x})^\top (the proof uses matrix calculus, P1.C11). For the five students of P1.D7 it gives covariance 8/5=1.68/5=1.6 and variances 10/5=210/5=2 instead of the covariance 22 and variances 2.52.5, and the correlation is still 1.6/2=0.81.6/2=0.8.

A categorical variable: counts over NN

A die, a spam filter that sorts email into three folders, or one step of a language model: the outcome is one of KK classes with probabilities θ1,…,θK\theta_1,\dots,\theta_K that add to 11 (the categorical distribution of P1.D3). If class jj occurred njn_j times in NN observations, the likelihood is ∏jθjnj\prod_j\theta_j^{n_j} and the log-likelihood is ∑jnjln⁡θj\sum_j n_j\ln\theta_j. The maximum, with ∑jθj=1\sum_j\theta_j=1, is

θ^j=njN.\hat\theta_j=\frac{n_j}{N}.

The best probabilities are the observed frequencies. Ten rolls of a die that show 1,2,3,3,4,5,5,6,6,61,2,3,3,4,5,5,6,6,6 give θ^=(0.1,0.1,0.2,0.1,0.2,0.3)\hat{\boldsymbol\theta}=(0.1,0.1,0.2,0.1,0.2,0.3) and a log-likelihood of −16.96-16.96, higher than the −17.92-17.92 of the fair die (16)\left(\frac16\right) for the same data. The coin is the case K=2K=2. A Go-deeper box proves the result without calculus.

Go deeper Poisson counts and exponential waiting times

Two more one-line derivations, both of the same recipe. For counts xix_i from a Poisson distribution (P1.D3), ln⁡p(x∣λ)=xln⁡λ−λ−ln⁡x!\ln p(x\mid\lambda)=x\ln\lambda-\lambda-\ln x!, so LL=ln⁡λ∑ixi−Nλ−∑iln⁡xi!\mathrm{LL}=\ln\lambda\sum_i x_i-N\lambda-\sum_i\ln x_i! and d LLdλ=∑xiλ−N=0\frac{d\,\mathrm{LL}}{d\lambda}=\frac{\sum x_i}{\lambda}-N=0 gives λ^=xˉ\hat\lambda=\bar x: the rate is the average count. For counts 2,0,3,12,0,3,1 it is 1.51.5.

For waiting times xix_i from the exponential density λe−λx\lambda\mathrm{e}^{-\lambda x}, LL=Nln⁡λ−λ∑ixi\mathrm{LL}=N\ln\lambda-\lambda\sum_i x_i, and Nλ−∑ixi=0\frac N\lambda-\sum_i x_i=0 gives λ^=1/xˉ\hat\lambda=1/\bar x. For the waits 0.50.5 and 11 the mean is 0.750.75, so λ^=43\hat\lambda=\frac43 and the likelihood is (43)2e−43⋅1.5=0.2406\left(\frac43\right)^2\mathrm{e}^{-\frac43\cdot1.5}=0.2406, a little above the 0.22310.2231 of λ=1\lambda=1 in the first section.

Go deeper Why counts over N is the maximum for a categorical variable

Let qj=nj/Nq_j=n_j/N be the observed frequencies, with every qj>0q_j>0 (a class with nj=0n_j=0 contributes nothing to the log-likelihood, so every sum below runs over the classes with qj>0q_j>0, and ∑jθj≤1\sum_j\theta_j\le1 over those classes still gives a result of at most 00). For any probabilities θj\theta_j that add to 11, write D=LL(θ)−LL(q)D=\mathrm{LL}(\boldsymbol\theta)-\mathrm{LL}(\mathbf q) for the gain over q\mathbf q. Then

D=N∑jqjln⁡θjqj≤N∑jqj(θjqj−1)=N(∑jθj−∑jqj)=0.\begin{aligned} D&=N\sum_j q_j\ln\frac{\theta_j}{q_j}\\ &\le N\sum_j q_j\Bigl(\frac{\theta_j}{q_j}-1\Bigr)\\ &=N\Bigl(\sum_j\theta_j-\sum_j q_j\Bigr)=0. \end{aligned}

The inequality uses ln⁡u≤u−1\ln u\le u-1 for every u>0u>0, with equality only at u=1u=1. So no θ\boldsymbol\theta beats q\mathbf q, and only θ=q\boldsymbol\theta=\mathbf q ties. The quantity D/ND/N is −KL(q ∥ θ)-\mathrm{KL}(\mathbf q\,\|\,\boldsymbol\theta), minus the KL divergence of P1.E4. Maximum likelihood for a categorical variable is minimizing the KL divergence from the observed frequencies to the model, and KL is never negative.

From likelihood to loss functions

In supervised learning each example is a pair (xi,yi)(\mathbf{x}_i,y_i), and the model p(y∣x,θ)p(y\mid\mathbf{x},\boldsymbol\theta) says how likely each target is given the input. With i.i.d. pairs the likelihood is ∏ip(yi∣xi,θ)\prod_i p(y_i\mid\mathbf{x}_i,\boldsymbol\theta). The inputs’ own distribution p(x)p(\mathbf{x}) does not depend on θ\boldsymbol\theta and drops out of the argmax. So

NLL(θ)=−∑i=1Nln⁡p(yi∣xi,θ).\mathrm{NLL}(\boldsymbol\theta)=-\sum_{i=1}^N\ln p(y_i\mid\mathbf{x}_i,\boldsymbol\theta).

Every standard loss is this sum for a particular choice of p(y∣x,θ)p(y\mid\mathbf x,\boldsymbol\theta). P1.D3 previewed three of them. Here they are derived.

Gaussian noise gives mean squared error

Suppose the target is a prediction plus noise, y=y^+εy=\hat y+\varepsilon with y^=f(x;θ)\hat y=f(\mathbf x;\boldsymbol\theta) and noise ε∼N(0,σ2)\varepsilon\sim N(0,\sigma^2) with a fixed σ\sigma. Then p(y∣x,θ)=N(y;y^,σ2)p(y\mid\mathbf x,\boldsymbol\theta)=N(y;\hat y,\sigma^2) and one example’s negative log density is

−ln⁡p(y∣y^)=(y−y^)22σ2+ln⁡(σ2π).-\ln p(y\mid\hat y)=\frac{(y-\hat y)^2}{2\sigma^2}+\ln\bigl(\sigma\sqrt{2\pi}\bigr).

With σ=1\sigma=1, y=3y=3 and y^=2.5\hat y=2.5 this is 0.125+0.9189=1.04390.125+0.9189=1.0439, the number from P1.D3. Summing over NN examples:

NLL=12σ2∑i(yi−y^i)2+Nln⁡(σ2π).\begin{aligned} \mathrm{NLL}={}&\frac{1}{2\sigma^2}\sum_i(y_i-\hat y_i)^2\\ &+N\ln\bigl(\sigma\sqrt{2\pi}\bigr). \end{aligned}

The second term does not depend on θ\boldsymbol\theta, and 12σ2\frac1{2\sigma^2} is a positive constant, so minimizing the NLL is minimizing the sum of squared errors, which is minimizing the mean squared error (P3.A2). With σ\sigma fixed, the chosen σ\sigma does not even change the best predictions. If σ\sigma is also fitted, the Gaussian result above applies: σ^2\hat\sigma^2 is the mean squared error of the best fit.

For three examples with (y,y^)=(3, 2.5), (5, 5.5), (4, 4)(y,\hat y)=(3,\,2.5),\ (5,\,5.5),\ (4,\,4) and σ=1\sigma=1, the per-example losses are 1.0439, 1.0439, 0.91891.0439,\ 1.0439,\ 0.9189. The total is 3.0068=0.52+3×0.91893.0068=\frac{0.5}{2}+3\times0.9189 and the average is 1.0023=MSE2+0.91891.0023=\frac{\mathrm{MSE}}2+0.9189 with MSE=16\mathrm{MSE}=\frac16. (Setting y^\hat y to a constant cc for every example gives the Gaussian fit of the previous section: the best cc is the mean. If the noise were Laplace instead, with density proportional to e−∣y−y^∣/b\mathrm{e}^{-|y-\hat y|/b}, the same steps give the absolute error.)

Bernoulli outputs give binary cross-entropy

For a yes-or-no label y∈{0,1}y\in\{0,1\} the model outputs p^\hat p, the probability that y=1y=1 (a sigmoid output, P1.A5). The probability of the observed label is p^ y(1−p^)1−y\hat p^{\,y}(1-\hat p)^{1-y}, so the NLL of one example is

−[ yln⁡p^+(1−y)ln⁡(1−p^) ].-\bigl[\,y\ln\hat p+(1-y)\ln(1-\hat p)\,\bigr].

This is binary cross-entropy. For labels (1,0,1)(1,0,1) and predictions (0.8,0.3,0.6)(0.8,0.3,0.6) the model gives the truth the probabilities 0.8, 0.7, 0.60.8,\ 0.7,\ 0.6. The likelihood of the labels is 0.8×0.7×0.6=0.3360.8\times0.7\times0.6=0.336, the NLL is −ln⁡0.336=1.0906-\ln0.336=1.0906, and the average is 1.09063=0.3635\frac{1.0906}3=0.3635: the number from P1.D3. The three losses are −ln⁡0.8=0.2231-\ln0.8=0.2231, −ln⁡0.7=0.3567-\ln0.7=0.3567 and −ln⁡0.6=0.5108-\ln0.6=0.5108, which add to 1.09061.0906. (A confident wrong answer costs much more: if the model says p^=0.8\hat p=0.8 and the label is 00, the truth gets 0.20.2 and the loss is −ln⁡0.2=1.6094-\ln0.2=1.6094.) Fitting the parameters is P3.A7.

Categorical outputs give cross-entropy

For one of KK classes the model outputs probabilities p^1,…,p^K\hat p_1,\dots,\hat p_K (softmax, P3.A8). The probability of the observed class cc is p^c\hat p_c, so the loss is

−ln⁡p^c=−∑j=1Kyjln⁡p^j,-\ln\hat p_c=-\sum_{j=1}^{K}y_j\ln\hat p_j,

where y\mathbf y is the one-hot label (the sum has a single nonzero term). This is cross-entropy. For (0.7,0.2,0.1)(0.7,0.2,0.1) with the true class first it is −ln⁡0.7=0.3567-\ln0.7=0.3567. Only the probability given to the true class matters.

Language models. A text is a sequence of tokens. The probability of the whole text is a product over positions of the next-token probabilities, p(t1) p(t2∣t1)⋯p(t_1)\,p(t_2\mid t_1)\cdots, which is the chain rule of P1.D5. The NLL of a text is the sum of the per-token cross-entropies, and pretraining a language model is maximum likelihood: the reported loss is the average NLL per token (P10.A1). Its exponential is the perplexity (P1.E5): an average NLL of ln⁡4=1.386\ln4=1.386 per token means the model is, on average, as unsure as if it were choosing among 44 equally likely tokens.

output and model (loss name, lesson)NLL of one example
real number, Gaussian with fixed σ\sigma (squared error, P3.A2)(y−y^)22σ2\frac{(y-\hat y)^2}{2\sigma^2} + constant
yes or no, Bernoulli (binary cross-entropy, P3.A7)−[yln⁡p^+(1−y)ln⁡(1−p^)]-[y\ln\hat p+(1-y)\ln(1-\hat p)]
one of KK classes, categorical (cross-entropy, P3.A8)−ln⁡p^true class-\ln\hat p_{\text{true class}}
next token, categorical over the vocabulary (P10.A1)−ln⁡p^true token-\ln\hat p_{\text{true token}}

When there is no formula

The coin and the Gaussian can be solved with a pencil. Logistic regression cannot: setting the gradient of the NLL to zero has no closed-form solution. The same holds for every neural network. The remedy is gradient descent on the average NLL (P1.F3): compute the gradient, step downhill, repeat. For binary cross-entropy the gradient with respect to the pre-sigmoid score has the pleasant form p^−y\hat p-y (for p^=0.8\hat p=0.8 and y=1y=1 it is −0.2-0.2, so the step increases the score), and for softmax cross-entropy it is the vector p^−y\hat{\mathbf p}-\mathbf y. The code section runs gradient descent on the coin’s NLL and arrives at 2/32/3.

What maximum likelihood can get wrong

Maximum likelihood is the default, not the whole story. Each of these points has a precise condition.

  • Small data and the edge of the range. After 33 heads in 33 flips, θ^=1\hat\theta=1: the model says tails is impossible. A fourth flip that lands tails would have likelihood 00 and an infinite loss, −ln⁡0=∞-\ln0=\infty. A coin that is only 80%80\% heads would still give three heads half the time (0.83=0.5120.8^3=0.512). A prior belief fixes this, which is MAP estimation (P1.D11): maximize ln⁡Lik(θ)+ln⁡p(θ)\ln\mathrm{Lik}(\boldsymbol\theta)+\ln p(\boldsymbol\theta). Adding one imagined head and one imagined tail gives 3+13+2=0.8\frac{3+1}{3+2}=0.8 here, and a prior that prefers small weights acts like the L2 penalty (P3.A6). The same problem appears whenever a class or word is never seen in the data (smoothing in naive Bayes, P3.B2).
  • A bias in small samples. The 1/N1/N variance is too small on average. For N=1N=1 it is 00 (a single point has no spread), and the likelihood is then unbounded, as in the “All equal” widget set.
  • A wrong family. Maximum likelihood gives the best parameters inside the family. It does not say the family is right. The two-cluster data get a perfectly good Gaussian fit, and a poor description. Check the fit (histograms, held-out data, P3.A4).
  • Sensitivity to the likelihood’s shape. A Gaussian puts a squared penalty on distance, so a single outlier drags the fit, as the widget showed. Heavier-tailed noise models give robust losses.
  • The model must be identifiable. If two parameter values give exactly the same distribution, several θ^\hat{\boldsymbol\theta} tie. For y^=(w1+w2)x\hat y=(w_1+w_2)x only the sum matters, and swapping two hidden units of a neural network (with their weights) gives the same function. The MLE is then not unique, which is harmless for predictions and awkward for interpreting parameters.
  • No closed form, many peaks. Beyond simple models the NLL must be minimized numerically, and for neural networks (P1.F2) the landscape has many valleys.
  • Dependent data. The product assumes independence. Time series or duplicated data break it. The likelihood is still right if written with the chain rule, p(x1)p(x2∣x1)⋯p(x_1)p(x_2\mid x_1)\cdots, which is how language models avoid the assumption.
  • The likelihood is not the probability of the parameters. The MLE is the parameter that makes the data most probable. It is not the most probable parameter given the data. They agree when the prior is flat (see P1.D11).
Go deeper Consistency, asymptotic normality and the spread of an estimate

Under regularity conditions (the data really come from some θ0\boldsymbol\theta_0 in the family, different parameters give different distributions, the likelihood is smooth, and θ0\boldsymbol\theta_0 is not on the edge of the allowed range), the MLE has two good properties as NN grows. It is consistent: θ^→θ0\hat{\boldsymbol\theta}\to\boldsymbol\theta_0 in probability. And it is asymptotically normal: for one parameter, N(θ^−θ0)\sqrt N(\hat\theta-\theta_0) approaches a Gaussian with variance 1/I(θ0)1/I(\theta_0), where II is the Fisher information, −E[d2dθ2ln⁡p(x∣θ)]-\mathbb{E}\bigl[\frac{d^2}{d\theta^2}\ln p(x\mid\theta)\bigr]. It measures how sharply the log-likelihood curves at the peak.

For the coin, I(θ)=1θ(1−θ)I(\theta)=\frac1{\theta(1-\theta)}, so the spread of θ^\hat\theta is about θ(1−θ)/N\sqrt{\theta(1-\theta)/N}. That is the standard error of an average of 0/10/1 results from P1.D8, since θ^=k/N\hat\theta=k/N is such an average. For 6060 heads in 100100 it is 0.0490.049. This matches the width of the bump in the coin widget: the likelihood falls to half its peak over a width of about 2.352.35 standard deviations, 0.1150.115. These are statements about large NN and a correct model. They do not apply to a wrong family or to a few data points.

Go deeper Maximum likelihood is minimizing a KL divergence

Let qq be the true distribution that generated the data. As NN grows, the average NLL L(θ)=1NNLL(θ)\mathcal L(\boldsymbol\theta)=\frac1N\mathrm{NLL}(\boldsymbol\theta) approaches an expectation (the law of large numbers, P1.D8):

L(θ)→Eq[−ln⁡p(x∣θ)]=H(q)+KL(q ∥ pθ).\begin{aligned} \mathcal L(\boldsymbol\theta)&\to\mathbb{E}_{q}\bigl[-\ln p(x\mid\boldsymbol\theta)\bigr]\\ &=H(q)+\mathrm{KL}\bigl(q\,\|\,p_{\boldsymbol\theta}\bigr). \end{aligned}

The middle expression is the cross-entropy of pθp_{\boldsymbol\theta} relative to qq (P1.E3), and H(q)H(q) is the entropy (P1.E2), which does not involve θ\boldsymbol\theta. So minimizing the average NLL is minimizing KL(q ∥ pθ)\mathrm{KL}(q\,\|\,p_{\boldsymbol\theta}) (P1.E4), the divergence from the data’s distribution to the model’s. For a finite data set the statement is exact with the observed frequencies in place of qq, as the categorical box showed. This is why the classification loss is called cross-entropy.

Go deeper A likelihood with no maximum: the Gaussian mixture

Fit a mixture of two Gaussians (P3.C2) to the six points: half the weight on a Gaussian centred on the first point x1=2x_1=2 with spread ss, half on a Gaussian with μ=4\mu=4 and σ=1.5\sigma=1.5. The density at x1x_1 is at least 12⋅1s2π\frac12\cdot\frac1{s\sqrt{2\pi}}, which grows without bound as s→0s\to0, while the other points are still covered by the second Gaussian. The log-likelihood is −11.64, −10.81, −8.54, −6.24-11.64,\ -10.81,\ -8.54,\ -6.24 for s=1, 0.1, 0.01, 0.001s=1,\ 0.1,\ 0.01,\ 0.001, and it keeps rising like ln⁡1s\ln\frac1s. So the likelihood has no maximum: it can be made as large as you like by putting a spike on one data point. The practical fixes are to limit how small a variance may become, or to add a prior (P1.D11). The single Gaussian in the widget’s “All equal” set shows the same effect in its simplest form.

Try it: maximum likelihood in code

The first cell finds the coin and Gaussian estimates by brute force on a grid and compares them with the formulas, shows the product underflowing while the sum of logs works, and checks that binary cross-entropy is the NLL divided by NN. The second cell fits the coin by gradient descent on the average NLL, simulates the bias of the 1/N1/N variance, and shows the mixture likelihood growing without limit. Predict first: will the grid search for σ\sigma land on 1.321.32 or on the N−1N-1 value 1.451.45?

Try it: grid search, formulas, underflow and cross-entropy

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The first block prints 0.670.67 for the coin (the grid has no 2/32/3, and the likelihoods at 0.5, 0.67, 0.80.5,\ 0.67,\ 0.8 are 0.125, 0.1481, 0.1280.125,\ 0.1481,\ 0.128). The grid and the formulas agree on μ=4\mu=4 and σ=1.32\sigma=1.32 with log-likelihood −10.1925-10.1925, while ddof=1 gives 1.44911.4491. The product of a thousand 0.10.1s prints 0.0 and the sum of logs is −2302.585-2302.585. The binary cross-entropy is 0.36350.3635, and the likelihood 0.3360.336 has the log −1.0906=3×(−0.3635)-1.0906=3\times(-0.3635). Challenge: change [1, 1, 0] to [1, 1, 1] and find which θ\theta wins (the largest value on the grid, 0.990.99, because the true peak is at the edge).

Try it: gradient descent, the bias of 1/N, and a likelihood with no maximum

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The gradient-descent run moves θ\theta from 0.50.5 through 0.61240.6124 and 0.66550.6655 to 0.66670.6667, and the average NLL falls from 0.69310.6931 to its minimum 0.63650.6365, which is −(23ln⁡23+13ln⁡13)-\bigl(\frac23\ln\frac23+\frac13\ln\frac13\bigr). The variance simulation prints about 3.23.2 for the 1/N1/N estimates and about 4.04.0 for the 1/(N−1)1/(N-1) estimates (the exact values depend on the random numbers). The mixture’s log-likelihood climbs from −11.64-11.64 to −6.24-6.24 and would keep climbing. Challenge: change the gradient-descent step size η\eta to 1010. The estimate θ\theta then bounces between about 0.470.47 and 0.860.86 and never settles, because the step is too large for the curvature (P1.F3).

Intuition, math and code at a glance

Intuition

The likelihood asks, for each possible setting of the parameters, “how surprised would this model be by the data I actually saw?” A good setting is rarely surprised. Maximum likelihood picks the least surprised model. Taking logs turns a product of probabilities into a sum of surprises, −ln⁡p-\ln p (P1.E1), so the loss is the total surprise.

Math

The likelihood, log-likelihood and estimate:

Lik(θ)=∏ip(xi∣θ)LL(θ)=∑iln⁡p(xi∣θ)θ^=arg⁡min⁡θ(−LL)\begin{aligned} \mathrm{Lik}(\boldsymbol\theta)&=\prod_i p(x_i\mid\boldsymbol\theta)\\ \mathrm{LL}(\boldsymbol\theta)&=\sum_i\ln p(x_i\mid\boldsymbol\theta)\\ \hat{\boldsymbol\theta}&=\arg\min_{\boldsymbol\theta}\bigl(-\mathrm{LL}\bigr) \end{aligned}

Closed forms:

  • coin: θ^=k/N\hat\theta=k/N
  • Gaussian: μ^=xˉ\hat\mu=\bar x and σ^2=1N∑i(xi−xˉ)2\hat\sigma^2=\frac1N\sum_i(x_i-\bar x)^2
  • categorical: θ^j=nj/N\hat\theta_j=n_j/N

Losses from −ln⁡p(y∣x,θ)-\ln p(y\mid\mathbf x,\boldsymbol\theta):

  • Gaussian: (y−y^)22σ2+const\frac{(y-\hat y)^2}{2\sigma^2}+\text{const}
  • Bernoulli: −yln⁡p^−(1−y)ln⁡(1−p^)-y\ln\hat p-(1-y)\ln(1-\hat p)
  • categorical: −ln⁡p^true-\ln\hat p_{\text{true}}

Code

Compute a Gaussian’s maximum-likelihood fit and its log-likelihood with NumPy.

import numpy as np

x = np.array([2, 3, 3.5, 4.5, 5, 6.0])
mu, sigma = x.mean(), x.std()                  # np.std divides by N: the MLE
ll = np.sum(-np.log(sigma * np.sqrt(2 * np.pi)) - (x - mu) ** 2 / (2 * sigma ** 2))
print(mu, sigma, ll)                           # 4.0, 1.3229, -10.1925

Common mistakes

Check your understanding

  1. A coin lands heads 77 times in 1010 flips. What is the maximum-likelihood estimate of the probability of heads?

  2. Why do we maximize the log-likelihood instead of the likelihood?

  3. After 33 heads in 33 flips, maximum likelihood gives θ^=1\hat\theta=1. What goes wrong?

  4. A model predicts y^i\hat y_i and the targets are yi=y^i+εiy_i=\hat y_i+\varepsilon_i with Gaussian noise of a fixed σ\sigma. Maximizing the likelihood of the data over the model’s parameters is the same as minimizing which quantity?

  5. A classifier gives the true class the probabilities 0.50.5, 0.250.25 and 0.80.8 on three examples. What is the average negative log-likelihood (the cross-entropy loss)?

Exercises

  1. A coin gives 77 heads in 1010 flips. Write Lik(θ)\mathrm{Lik}(\theta) and LL(θ)\mathrm{LL}(\theta), find θ^\hat\theta, and compare the likelihood at θ=0.5\theta=0.5 with the likelihood at θ^\hat\theta.
    Show answerLik=θ7(1−θ)3\mathrm{Lik}=\theta^7(1-\theta)^3 and LL=7ln⁡θ+3ln⁡(1−θ)\mathrm{LL}=7\ln\theta+3\ln(1-\theta). Setting 7θ−31−θ=0\frac7\theta-\frac3{1-\theta}=0 gives θ^=0.7\hat\theta=0.7. The likelihood at 0.70.7 is 0.00222360.0022236 and at 0.50.5 it is 0.510=0.00097660.5^{10}=0.0009766, a ratio of 0.4390.439. The log-likelihoods are −6.1086-6.1086 and −6.9315-6.9315.
  2. Find the maximum-likelihood Gaussian for the data 1, 2, 61,\ 2,\ 6, and compare σ^\hat\sigma with the N−1N-1 standard deviation.
    Show answerμ^=3\hat\mu=3. The squared distances are 4, 1, 94,\ 1,\ 9, adding to 1414. So σ^2=14/3=4.667\hat\sigma^2=14/3=4.667 and σ^=2.160\hat\sigma=2.160. The N−1N-1 version is 14/2=2.646\sqrt{14/2}=2.646.
  3. Waiting times are 0.50.5 and 11. Find the maximum-likelihood rate of an exponential model, and the likelihood there.
    Show answerλ^=1/xˉ=1/0.75=43\hat\lambda=1/\bar x=1/0.75=\frac43, and Lik=λ2e−λ∑xi=(43)2e−2=0.2406\mathrm{Lik}=\lambda^2\mathrm{e}^{-\lambda\sum x_i}=\left(\frac43\right)^2\mathrm{e}^{-2}=0.2406.
  4. A call center counts 2, 0, 3, 12,\ 0,\ 3,\ 1 calls in four hours. What is the maximum-likelihood Poisson rate per hour?
    Show answerThe sample mean, λ^=6/4=1.5\hat\lambda=6/4=1.5.
  5. Of 2020 emails, 1212 are ordinary, 66 are spam and 22 are other. What does maximum likelihood say about the three class probabilities?
    Show answerThe observed frequencies, 0.6, 0.3, 0.10.6,\ 0.3,\ 0.1.
  6. A model gives probability 0.050.05 to each of 500500 independent examples. What is the log-likelihood, the average NLL, and why can the product not be stored?
    Show answerLL=500ln⁡0.05=−1497.87\mathrm{LL}=500\ln0.05=-1497.87 and the average NLL is −ln⁡0.05=2.9957-\ln0.05=2.9957. The product is about 10−650.510^{-650.5}, far below the smallest positive float, about 5×10−3245\times10^{-324}, so it would be stored as 0.00.0.
  7. For (y,y^)=(3,2.5), (5,5.5), (4,4)(y,\hat y)=(3,2.5),\ (5,5.5),\ (4,4), find the total NLL of a Gaussian with σ=1\sigma=1, and the per-example loss of an error of 11 when σ=2\sigma=2.
    Show answerThe errors are ±0.5\pm0.5 and 00, so the sum of (y−y^)22\frac{(y-\hat y)^2}{2} is 0.250.25 and the total is 0.25+3ln⁡2π=0.25+2.7568=3.00680.25+3\ln\sqrt{2\pi}=0.25+2.7568=3.0068. With σ=2\sigma=2 and an error of 11: 18+ln⁡(22π)=0.125+1.6121=1.7371\frac{1}{8}+\ln\bigl(2\sqrt{2\pi}\bigr)=0.125+1.6121=1.7371.
  8. A language model gives three tokens the probabilities 0.5, 0.250.5,\ 0.25 and 0.1250.125. Find the average NLL per token and the perplexity.
    Show answerThe NLLs are ln⁡2, ln⁡4, ln⁡8\ln2,\ \ln4,\ \ln8, adding to 6ln⁡2=4.1596\ln2=4.159. The average is 2ln⁡2=1.3862\ln2=1.386 and the perplexity is e1.386=4\mathrm{e}^{1.386}=4.
  9. A coin gives 22 heads in 22 flips. What does maximum likelihood estimate, what does add-one smoothing estimate, and why is the second safer?
    Show answerθ^=1\hat\theta=1. Adding one imagined head and one imagined tail gives 2+12+2=0.75\frac{2+1}{2+2}=0.75. The first says tails is impossible (a tail later has likelihood 00 and infinite loss), and the second never gives a probability of exactly 00 or 11. P1.D11 shows that this is MAP estimation with a particular prior.
  10. Compare 66 heads in 1010 flips with 6060 in 100100: the standard error θ^(1−θ^)/N\sqrt{\hat\theta(1-\hat\theta)/N} of the estimate, and the likelihood at θ=0.5\theta=0.5 as a fraction of the peak.
    Show answerThe standard errors are 0.1550.155 and 0.0490.049. At θ=0.5\theta=0.5 the likelihood is 0.8180.818 of the peak for 1010 flips and 0.1340.134 for 100100 flips. More data narrows the bump and rules out more biases.
  11. Show that for a Gaussian with known σ\sigma and unknown μ\mu, maximizing the likelihood is the same as minimizing ∑i(xi−μ)2\sum_i(x_i-\mu)^2.
    Show answerThe only part of the log-likelihood that depends on μ\mu is −12σ2∑i(xi−μ)2-\frac1{2\sigma^2}\sum_i(x_i-\mu)^2, and 12σ2\frac1{2\sigma^2} is positive. Maximizing the negative of a positive multiple of a sum is minimizing the sum. Setting its derivative −2∑i(xi−μ)-2\sum_i(x_i-\mu) to zero gives μ=xˉ\mu=\bar x.
  12. Why is the likelihood ∏ip(xi∣θ)\prod_i p(x_i\mid\theta) not a valid probability distribution over θ\theta, and what is needed to get one?
    Show answerFor fixed data, nothing forces it to add up (or integrate) to 11 over θ\theta: for H, H, T the integral is 112\frac1{12}. A distribution over θ\theta needs a prior and Bayes’ theorem (P1.D6), whose posterior is proportional to likelihood times prior.

Next: P1.D11 adds a prior to the likelihood (MAP estimation) and shows how it repairs the small-data problem and acts like regularization. P1.E3 and P1.E4 look at cross-entropy and the KL divergence on their own, P1.F3 uses gradient descent to minimize an NLL that has no formula, and P3.A2, P3.A7 and P3.A8 build regression and classification on the losses derived here.

Key takeaways

  • The likelihood Lik(θ)=p(data∣θ)\mathrm{Lik}(\boldsymbol\theta)=p(\text{data}\mid\boldsymbol\theta) is the probability (or density) the model gives to the observed data, read as a function of the parameters with the data fixed. It is not a probability distribution over θ\boldsymbol\theta: the area under it need not be 11. For i.i.d. data it is the product ∏ip(xi∣θ)\prod_i p(x_i\mid\boldsymbol\theta).
  • Maximum likelihood picks the parameters that make the observed data most probable. Taking the log is allowed because the log is increasing, so the maximizer is unchanged, and it turns the product into a sum LL=∑iln⁡p(xi∣θ)\mathrm{LL}=\sum_i\ln p(x_i\mid\boldsymbol\theta) that is easier to differentiate and does not underflow. Machine learning minimizes the negative log-likelihood, usually averaged over the NN examples.
  • Standard results: a coin gives θ^=k/N\hat\theta=k/N (H, H, T gives 2/32/3); a Gaussian gives μ^=xˉ\hat\mu=\bar x and σ^2=1N∑(xi−xˉ)2\hat\sigma^2=\frac1N\sum(x_i-\bar x)^2 (the 1/N1/N version, which is biased low by the factor (N−1)/N(N-1)/N); a categorical variable gives each class’s count divided by NN.
  • For a model of yy given x\mathbf{x}, the negative log-likelihood is a loss. A Gaussian with fixed σ\sigma gives (y−y^)22σ2\frac{(y-\hat y)^2}{2\sigma^2} plus a constant: mean squared error. A Bernoulli output gives binary cross-entropy −[yln⁡p^+(1−y)ln⁡(1−p^)]-[y\ln\hat p+(1-y)\ln(1-\hat p)]. A categorical output gives cross-entropy −ln⁡p^true class-\ln\hat p_{\text{true class}}, which is next-token prediction in a language model.
  • When there is no formula, a computer minimizes the negative log-likelihood by gradient descent (P1.F3). Maximum likelihood can fail: with 33 heads in 33 flips it says tails is impossible, a wrong model family still gets a ‘best’ fit, outliers pull a Gaussian fit, and some likelihoods (such as a Gaussian mixture) have no maximum. Priors (P1.D11) repair the small-data problem.
Found a mistake? Tell us