Module contents
Lesson 5 of 27Core 110 min

Maximum likelihood estimation

The platform’s home for maximum likelihood. Define likelihood, log-likelihood, and score; derive classical estimators and prove invariance. Solve cases without closed form numerically using stable log-sum-exp and unconstrained reparameterization, and show that the cross-entropy used to train networks is a negative log-likelihood.

After this lesson you can

  • Write likelihood and log-likelihood and analytically derive MLEs for Bernoulli, Poisson, normal, exponential, and uniform models.
  • Prove MLE invariance and apply it to functions of the parameter.
  • Calculate MLEs numerically by minimizing negative log-likelihood using reparameterization and log-sum-exp.
  • Recognize pathologies: unbounded mixture likelihood, boundary maxima, and nonexistence under perfect separation.
  • Explain why minimizing classifier or language-model cross-entropy is maximum likelihood.

Before you start

Motivation: from a coin to a GPT

Flip a coin ten times and get seven heads and three tails, in order: C C X C C X C C X C (C denotes heads, X denotes tails). Asked for “the” probability pp of heads, you answer 0.70.7 without thinking. This is so natural it hides a decision: among possible values of pp, you chose the one making what you saw most probable. The probability of that particular sequence is p7(1−p)3p^7(1-p)^3, and this function of pp peaks at 0.70.7.

That principle, choosing the parameter under which observed data are least surprising, is the most used in statistics. It yields sample mean as normal-center estimator, exponential rate, logistic-regression coefficients and, with very different computation, language-model weights: when a network minimizes token cross-entropy loss, it maximizes the probability the model assigns to corpus text. It is the coin problem with 101110^{11} parameters instead of one.

The preceding lesson built estimators “by hand”: one had to choose which moments to match, and the result could contradict the data (a 2Xˉ2\bar X below observed maximum for uniform). Maximum likelihood is a recipe requiring no invention: write data probability as a parameter function and maximize it. This lesson covers:

  • what likelihood is (and why it is not a probability over the parameter);
  • log-likelihood and the score function, turning the problem into calculus;
  • closed-form estimators for classical models, including one obtained without differentiation;
  • invariance, allowing reparameterization without redoing the work;
  • calculating an estimator without a formula (the usual practical case), with stability techniques preventing overflow;
  • cases where the recipe fails (unbounded likelihood, perfect separation, multiple maxima);
  • why cross-entropy is negative log-likelihood.

Likelihood

Work within a statistical model {p(⋅ ;θ):θ∈Θ}\{p(\cdot\,;\theta) : \theta \in \Theta\}, each p(⋅ ;θ)p(\cdot\,;\theta) a probability mass or density function. Joint probability of sample x=(x1,…,xn)x = (x_1, \dots, x_n) of independent identically distributed variables is product p(x;θ)=∏ip(xi;θ)p(x;\theta) = \prod_i p(x_i;\theta) (the joint law factorizes by independence). Until now we read it as a function of xx with fixed θ\theta. Fisher’s idea is to reverse this.

The arbitrary constant is not a technical detail. Measuring in millimeters instead of meters changes data density by a factor independent of θ\theta, and no reasonable conclusion should depend on that choice. Likelihood is therefore defined “up to a constant,” and we use relative likelihood R(θ)=L(θ)/L(θ^)R(\theta) = L(\theta)/L(\hat\theta), equal to 11 at the maximum.

In the coin example, with kk heads in nn flips, L(p)=pk(1−p)n−kL(p) = p^k(1-p)^{n-k} if the sequence is recorded, or (nk)pk(1−p)n−k\binom{n}{k}p^k(1-p)^{n-k} if only the head count is recorded: proportional, hence the same likelihood. Add flips in the interactive and see how the curve changes.

InteractiveLikelihood sharpens with data
Data: 10 tosses (filled circle = heads, hollow = tails)
Relative likelihood L(p)/L(p^)L(p)/L(\hat p)
0.15true p
Log likelihood ℓ(p)−ℓ(p^)\ell(p) - \ell(\hat p) and its parabola at the maximum
log 0.15 = −1.90
  • likelihood
  • maximum p^\hat p
  • region ≥0.15\ge 0.15
  • parabola with curvature at maximum
  • true pp
0.70
Tosses nn | heads kk10 | 7
Maximum p^=k/n\hat p = k/n0.700
Region with L/L^≥0.15L/\hat L \ge 0.15[0.398, 0.912]
Region width0.515
Curvature −ℓ′′(p^)=n/(p^(1−p^))-\ell''(\hat p) = n/(\hat p(1-\hat p))47.6
Area under L(p)L(p) (not 1!)7.58e−4
Top-left curve is L(p)/L(p^)L(p)/L(\hat p) for the flip sequence above; right is its logarithm, with the parabola best approximating it at the maximum (dashed). Start with 7 heads in 10 and add 100 flips drawn with p=0.7p = 0.7: how much does the region with relative likelihood above 0.150.15 narrow? Check width decreases approximately as 1/n1/\sqrt{n} and curvature n/(p^(1−p^))n/(\hat p(1-\hat p)) grows as nn. Press 'Start over': with no data the likelihood is flat and all pp values equally plausible. From there add only heads: the maximum lies at boundary p=1p = 1 and the parabola no longer makes sense.

Notice three things. First, the maximum follows observed proportion p^=k/n\hat p = k/n (orange line). Second, the curve sharpens: with little data many pp values explain observations almost equally well; with much data only those near p^\hat p do. Width of the R(p)≥0.15R(p) \ge 0.15 region visually represents uncertainty, narrowing as 1/n1/\sqrt{n}. Third, log-likelihood resembles a parabola near its maximum; its curvature measures information in data and is the next lesson’s Fisher information.

Likelihood is not a density over θ\theta

The commonest conceptual error is reading L(θ;x)L(\theta;x) as “probability the parameter equals θ\theta.” It is not, as a calculation shows. For the binomial model with n=10n = 10 and k=7k = 7,

∫01(107)p7(1−p)3  ⁣dp=1n+1=111≈0.0909,\int_0^1 \binom{10}{7}p^7(1-p)^3\,\dd p = \frac{1}{n+1} = \frac{1}{11} \approx 0.0909,

and recording the sequence instead of the count gives area B(8,4)=7! 3!/11!≈7.6⋅10−4B(8, 4) = 7!\,3!/11! \approx 7.6\cdot 10^{-4}. Neither integrates to 11, and the value depends on what was recorded, precisely the arbitrary constant in the definition. Likelihood is a function of θ\theta that is not a distribution of θ\theta; obtaining one requires a prior distribution (Bayesian inference, lesson 21).

There is a subtler distinction from densities. Reparameterizing by bijection η=g(θ)\eta = g(\theta) gives likelihood L∗(η)=L(g−1(η))L^\ast(\eta) = L(g^{-1}(\eta)): values are preserved and no Jacobian appears. A density of θ\theta, by contrast, changes under reparameterization and its maximum moves. Since LL‘s maximum depends only on values, the maximum-likelihood estimator survives reparameterization; the invariance section proves this.

Log-likelihood, score, and likelihood equations

A product of nn factors is awkward to maximize and risky to calculate. Take logarithms.

Three reasons to prefer it. Algebraic: a sum differentiates term by term, a product does not. Numerical: with a few hundred observations the product of densities leaves float64 range (below, 10001000 normal data have likelihood of order e−1397e^{-1397}, rounded to 00), while the log sum is manageable. Statistical: log-likelihood sums independent terms, obeying the law of large numbers and CLT, enabling estimator study in asymptotic theory. Since log⁡\log is strictly increasing, LL and ℓ\ell attain maxima at the same point.

For differentiation use the score function.

For the coin, s(p)=k/p−(n−k)/(1−p)s(p) = k/p - (n-k)/(1-p), and s(p)=0s(p) = 0 gives p=k/np = k/n. The second-order condition comes from the Hessian: ℓ′′(p)=−k/p2−(n−k)/(1−p)2<0\ell''(p) = -k/p^2 - (n-k)/(1-p)^2 < 0, so ℓ\ell is concave and the critical point is the unique maximum (critical-point classification).

Score has a property explaining why likelihood equations are a good idea.

Proof

Since p(⋅ ;θ)p(\cdot\,;\theta) is a density, ∫p(x;θ)  ⁣dx=1\int p(x;\theta)\,\dd x = 1 for every θ\theta. Differentiate both sides with respect to θ\theta and exchange derivative and integral:

0=∫∇θ p(x;θ)  ⁣dx=∫∇θ p(x;θ)p(x;θ) p(x;θ)  ⁣dx=Eθ[∇θlog⁡p(X;θ)].\vb{0} = \int \grad_\theta\, p(x;\theta)\,\dd x = \int \frac{\grad_\theta\, p(x;\theta)}{p(x;\theta)}\,p(x;\theta)\,\dd x = \E_\theta\big[\grad_\theta \log p(X;\theta)\big].

We used ∇p/p=∇log⁡p\grad p/p = \grad \log p.

∎

Interpretation: likelihood equations 1n∑is(θ;xi)=0\frac1n\sum_i s(\theta; x_i) = 0 are the sample version of population equation Eθ[s(θ;X)]=0\E_\theta[s(\theta;X)] = 0, exactly satisfied at the true value. This is the same pattern as last lesson’s moments method (equate sample average to expectation), using a special moment function: score. Its zero expectation starts estimator consistency and, when its variance is calculated, Fisher information.

Maximum-likelihood estimator

The definition does not guarantee a maximum exists (the supremum may not be attained) or is unique (there can be multiple points or a whole manifold if the model is not identifiable). Both occur in practice; the pathologies section shows them. Meanwhile, for clean cases:

  1. Write ℓ(θ;x)\ell(\theta;x) and simplify, removing everything independent of θ\theta.
  2. Calculate score and set it to zero.
  3. Check the critical point is a maximum (negative definite Hessian or concavity) and global.
  4. Inspect the boundary of Θ\Theta and points where ℓ\ell is not differentiable: the maximum may be there.

Five closed-form models

ModelParameterMLEBias
Bern⁡(p)\Bern(p)ppp^=Xˉ\hat p = \bar Xunbiased
Pois⁡(λ)\Pois(\lambda)λ\lambdaλ^=Xˉ\hat\lambda = \bar Xunbiased
exponential (rate λ\lambda)λ\lambdaλ^=1/Xˉ\hat\lambda = 1/\bar XEλ^=nn−1λ\E\hat\lambda = \frac{n}{n-1}\lambda
N(μ,σ2)\Normal(\mu, \sigma^2)μ\muμ^=Xˉ\hat\mu = \bar Xunbiased
N(μ,σ2)\Normal(\mu, \sigma^2)σ2\sigma^2σ^2=1n∑i(Xi−Xˉ)2\hat\sigma^2 = \frac1n\sum_i(X_i - \bar X)^2Eσ^2=n−1nσ2\E\hat\sigma^2 = \frac{n-1}{n}\sigma^2
Unif⁡(0,θ)\Unif(0, \theta)θ\thetaθ^=X(n)\hat\theta = X_{(n)}Eθ^=nn+1θ\E\hat\theta = \frac{n}{n+1}\theta

Bernoulli and Poisson. For Bernoulli, ℓ(p)=klog⁡p+(n−k)log⁡(1−p)\ell(p) = k\log p + (n-k)\log(1-p) with k=∑ixik = \sum_i x_i, and the calculation above gives p^=xˉ\hat p = \bar x. If k=0k = 0 or k=nk = n the curve is monotone and the maximum is at boundary p=0p = 0 or p=1p = 1, outside open parameter space (0,1)(0,1): the MLE exists only if closure is allowed. For Poisson, ℓ(λ)=log⁡λ∑ixi−nλ−∑ilog⁡xi!\ell(\lambda) = \log\lambda\sum_i x_i - n\lambda - \sum_i\log x_i! and s(λ)=∑ixi/λ−n=0s(\lambda) = \sum_i x_i/\lambda - n = 0 gives λ^=xˉ\hat\lambda = \bar x. Both MLEs coincide with moment estimators.

Exponential. With Xi∼iidExp⁡(λ)X_i \iid \operatorname{Exp}(\lambda) (exponential-gamma family), ℓ(λ)=nlog⁡λ−λ∑ixi\ell(\lambda) = n\log\lambda - \lambda\sum_i x_i and s(λ)=n/λ−∑ixi=0s(\lambda) = n/\lambda - \sum_i x_i = 0 give λ^=1/xˉ\hat\lambda = 1/\bar x. It is biased: since Xˉ∼Gamma⁡(n,nλ)\bar X \sim \operatorname{Gamma}(n, n\lambda), E[1/Xˉ]=nλ/(n−1)\E[1/\bar X] = n\lambda/(n-1), 25 %25\,\% too high at n=5n = 5. Bias vanishes as 1/n1/n, the price of 1/Xˉ1/\bar X being a nonlinear function of a mean (Jensen’s inequality).

Normal. With both parameters unknown and v=σ2v = \sigma^2, ℓ(μ,v)=−n2log⁡(2πv)−12v∑i(xi−μ)2\ell(\mu, v) = -\frac n2\log(2\pi v) - \frac{1}{2v}\sum_i(x_i - \mu)^2. Identity ∑i(xi−μ)2=∑i(xi−xˉ)2+n(xˉ−μ)2\sum_i(x_i - \mu)^2 = \sum_i(x_i - \bar x)^2 + n(\bar x - \mu)^2 separates parameters: for any vv, ℓ\ell is maximized at μ=xˉ\mu = \bar x, whatever vv. Substitution leaves ℓ(xˉ,v)=−n2log⁡(2πv)−SS⁡2v\ell(\bar x, v) = -\frac n2\log(2\pi v) - \frac{\operatorname{SS}}{2v} with SS⁡=∑i(xi−xˉ)2\operatorname{SS} = \sum_i (x_i - \bar x)^2, maximized at v^=SS⁡/n\hat v = \operatorname{SS}/n. The variance estimator divides by nn, not n−1n - 1: it is biased, and the previous lesson showed its MSE (0.19 σ40.19\,\sigma^4 at n=10n = 10) is lower than unbiased sample variance (0.2222 σ40.2222\,\sigma^4).

There is a way to see this together. In the next interactive a normal sample’s log-likelihood is a surface over (μ,σ)(\mu, \sigma); drag sample points and watch the peak move.

InteractiveNormal likelihood surface
Sample (drag points) and two normals: candidate and maximum likelihood
−20246810mean
Contour map of ℓ−ℓ^\ell - \hat\ell in (μ,σ)(\mu, \sigma); levels −0.25-0.25, −1-1, −3-3 (highlighted: approximate 95 %95\,\% joint region), −4.5-4.5, −8-8, −12-12
Surface ℓ(μ,σ)−ℓ^\ell(\mu, \sigma) - \hat\ell, clipped at −12-12 (rotate with mouse)
  • candidate (μ,σ)(\mu, \sigma)
  • maximum (xˉ,σ^)(\bar x, \hat\sigma)
  • ridge μ=xˉ\mu = \bar x (profile of σ\sigma)
  • contour −3-3: joint region ≈95 %\approx 95\,\%
Scale parameter axis
nn | xˉ=μ^\bar x = \hat\mu6 | 3.217
σ^=∑(xi−xˉ)2/n\hat\sigma = \sqrt{\sum(x_i - \bar x)^2/n}1.720
ℓ(μ^,σ^)\ell(\hat\mu, \hat\sigma)−11.767
Candidate (μ,σ)(\mu, \sigma)(4.60, 1.00)
Candidate ℓ(μ,σ)−ℓ^\ell(\mu, \sigma) - \hat\ell−8.361
Drop in ℓ\ell at σ^∓0.5σ^\hat\sigma \mp 0.5\hat\sigma (left | right)4.84 | 0.77
Asymmetry: left / right drop6.32
Top left: editable sample (drag points with mouse or arrows) and two normals: candidate (blue) and maximum likelihood (orange dashed). Below: contour map of ℓ−ℓ^\ell - \hat\ell with draggable candidate (μ,σ)(\mu, \sigma) (same as surface) and highlighted contour bounding approximate joint 95 %95\,\% confidence region. Right: 3D surface, mouse-rotatable; magenta line is ridge μ=xˉ\mu = \bar x. On the σ\sigma axis the surface plunges as σ→0\sigma \to 0 and has a long right tail: inspect asymmetry in the last readout. Switch to log⁡σ\log\sigma axis: the same values distribute nearly symmetrically. What happens to the ridge when you move an observation far away? Does the maximum in μ\mu change with σ\sigma?

Ridge μ=xˉ\mu = \bar x expresses the preceding calculation: the optimum in μ\mu does not depend on σ\sigma, so the surface has a straight “backbone” and the problem reduces to a curve in σ\sigma (the profile likelihood of σ\sigma, returning in profile likelihood intervals). Asymmetry is strong: halving σ\sigma from σ^\hat\sigma costs 0.81 n0.81\,n log-likelihood units while raising it by half costs only 0.13 n0.13\,n, ratio 6.36.3. On log⁡σ\log\sigma scale, with symmetric steps ±ln⁡1.5\pm\ln 1.5, the ratio is 1.71.7. This is neither accidental nor data-dependent: ℓ\ell as a function of u=log⁡(σ/σ^)u = \log(\sigma/\hat\sigma) is −n[u+(e−2u−1)/2]-n\big[u + (e^{-2u} - 1)/2\big] plus a constant, nearly quadratic in uu and clearly nonquadratic in σ\sigma. This explains optimizing via σ=es\sigma = e^s: besides removing σ>0\sigma > 0, it yields a much easier surface for Newton and similar methods.

Uniform. The last case is not solved by differentiation. With Xi∼iidUnif⁡(0,θ)X_i \iid \Unif(0,\theta),

L(θ)=∏i=1n1[0≤xi≤θ]θ=θ−n 1[θ≥x(n)],L(\theta) = \prod_{i=1}^n \frac{\ind[0 \le x_i \le \theta]}{\theta} = \theta^{-n}\,\ind[\theta \ge x_{(n)}],

because the indicator product is 11 exactly when all data fit in [0,θ][0,\theta]. For θ<x(n)\theta < x_{(n)} likelihood is zero (that θ\theta makes an observed value impossible). For θ≥x(n)\theta \ge x_{(n)} it decreases as θ−n\theta^{-n}. The maximum is at the discontinuity: θ^=X(n)\hat\theta = X_{(n)}, where no critical point exists (score −n/θ-n/\theta never vanishes).

This estimator was missing from the previous lesson. Moments gave 2Xˉ2\bar X, contradicting the data with probability tending to 1/21/2; the MLE by construction never does. Its error is order 1/n1/n, not 1/n1/\sqrt{n}: E[X(n)]=nn+1θ\E[X_{(n)}] = \frac{n}{n+1}\theta and ECM⁡=2θ2(n+1)(n+2)\operatorname{ECM} = \frac{2\theta^2}{(n+1)(n+2)}, versus θ2/(3n)\theta^2/(3n) for moments. With data 2.12.1, 0.70.7, 3.43.4, and 1.91.9, MLE is 3.43.4, moment estimator 4.054.05, and bias-corrected maximum n+1nX(n)\frac{n+1}{n}X_{(n)} is 4.254.25.

Invariance

Likelihood does not rescale on reparameterization, with a practical consequence: if you can estimate θ\theta, you can estimate any function of it. If gg is not injective, define “likelihood of η=g(θ)\eta = g(\theta)” by maximizing over preimages.

Proof

Let η^=g(θ^)\hat\eta = g(\hat\theta). For any η\eta, set {θ:g(θ)=η}\{\theta : g(\theta) = \eta\} is contained in Θ\Theta, so L∗(η)≤sup⁡θL(θ)=L(θ^)L^\ast(\eta) \le \sup_{\theta}L(\theta) = L(\hat\theta). Conversely θ^\hat\theta belongs to {θ:g(θ)=η^}\{\theta : g(\theta) = \hat\eta\}, so L∗(η^)≥L(θ^)L^\ast(\hat\eta) \ge L(\hat\theta). Combining, L∗(η^)=L(θ^)≥L∗(η)L^\ast(\hat\eta) = L(\hat\theta) \ge L^\ast(\eta) for every η\eta.

∎

Immediate consequences without extra calculation: σ^=σ^2\hat\sigma = \sqrt{\hat\sigma^2}; the MLE of P(X>c)\Pr(X > c) for normal is 1−Φ((c−xˉ)/σ^)1 - \Phi\big((c - \bar x)/\hat\sigma\big); the MLE of odds p/(1−p)p/(1-p) is xˉ/(1−xˉ)\bar x/(1-\bar x); and the MLE of exponential mean 1/λ1/\lambda is xˉ\bar x, also unbiased, while the rate λ\lambda MLE is not. Invariance is a property of the maximum; unbiasedness is not inherited.

Numerical MLE

Nearly all real models lack closed form. Even gamma, simplest after normal, lacks one. Let Xi∼iidGamma⁡(α,β)X_i \iid \operatorname{Gamma}(\alpha, \beta) with shape α\alpha and rate β\beta:

ℓ(α,β)=nαlog⁡β−nlog⁡Γ(α)+(α−1)∑ilog⁡xi−β∑ixi.\ell(\alpha, \beta) = n\alpha\log\beta - n\log\Gamma(\alpha) + (\alpha - 1)\sum_i\log x_i - \beta\sum_i x_i.
∂ℓ∂β=nαβ−∑ixi=0  ⇒  β^=αxˉ\pd{\ell}{\beta} = \frac{n\alpha}{\beta} - \sum_i x_i = 0 \;\Rightarrow\; \hat\beta = \frac{\alpha}{\bar x}
For each shape α, optimal rate is α divided by the mean: a linear equation.
1/4

Function f(α)=log⁡α−ψ(α)f(\alpha) = \log\alpha - \psi(\alpha) is strictly decreasing (because ψ′(α)>1/α\psi'(\alpha) > 1/\alpha), tends to +∞+\infty as α→0\alpha \to 0 and 00 as α→∞\alpha \to \infty; s>0s > 0 always by Jensen’s inequality applied to logarithm (nonconstant data). Thus the equation has one solution and gamma MLE exists and is unique. Find it with one-dimensional Newton, α←α−f(α)−s1/α−ψ′(α)\alpha \leftarrow \alpha - \dfrac{f(\alpha) - s}{1/\alpha - \psi'(\alpha)}, starting from a well-known closed approximation α0=3−s+(s−3)2+24s12s\alpha_0 = \dfrac{3 - s + \sqrt{(s-3)^2 + 24 s}}{12 s}, already within a fraction of a percent. This is the calculation statistical software hides behind gamma.fit.

[ ]Gamma likelihood equation with NewtonBrowser
import numpy as np
from scipy import stats, special

rng = np.random.default_rng(3)
x = rng.gamma(shape=3.0, scale=2.0, size=200)        # forma 3, tasa 1/2

s = np.log(x.mean()) - np.log(x).mean()               # el estadístico de la ecuación
a = (3 - s + np.sqrt((s - 3) ** 2 + 24 * s)) / (12 * s)   # inicio en forma cerrada
print(f"s = {s:.5f}, inicio alpha0 = {a:.5f}")
for it in range(1, 5):
    f = np.log(a) - special.digamma(a) - s
    a = a - f / (1 / a - special.polygamma(1, a))
    print(f"iteración {it}: alpha = {a:.10f}   (residuo antes del paso {f:.2e})")

beta = a / x.mean()
print(f"EMV propio: alpha = {a:.8f}, beta = {beta:.8f}")
ah, loc, esc = stats.gamma.fit(x, floc=0)
print(f"scipy.fit:  alpha = {ah:.8f}, beta = {1 / esc:.8f}")

A couple of iterations suffice: Newton has quadratic convergence (Newton’s method, optimization module): residual approximately squares each step, from 3⋅10−43\cdot10^{-4} to 6⋅10−76\cdot10^{-7} and 2⋅10−122\cdot10^{-12}, and the closed-form start already has two digits correct (3.305 versus 3.311).

Four numerical MLE rules

With multiple parameters or a mixture, do not solve an equation by hand: give an optimizer the objective. This is numerical MLE: minimize mean negative log-likelihood −ℓ(θ;x)/n-\ell(\theta;x)/n iteratively, treating the optimizer as a black box whose interior the optimization module reveals. Four choices under your control distinguish a reliable result from silent disaster.

1. Reparameterize away constraints. An unconstrained optimizer will propose σ<0\sigma < 0 or p>1p > 1 at some step and log-likelihood returns nan. Use a free parameter u∈Ru \in \R and transform: σ=eu\sigma = e^u for scale, p=sigmoide⁡(u)=1/(1+e−u)p = \operatorname{sigmoide}(u) = 1/(1 + e^{-u}) for probability, p=softmax⁡(u)\vb{p} = \softmax(\vb{u}) for a probability vector. By invariance, the maximum in uu is the maximum in θ\theta and, as the surface showed, log⁡σ\log\sigma often gives a function much closer to quadratic.

2. Compute in log space. Do not evaluate log⁡(pdf⁡)\log(\operatorname{pdf}): directly use log-density, which can be written stably. When a sum of probabilities appears (a mixture), use log-sum-exp:

LSE⁡(a1,…,aK)=log⁡∑k=1Keak=m+log⁡∑k=1Keak−m,m=max⁡kak.\operatorname{LSE}(a_1, \dots, a_K) = \log\sum_{k=1}^K e^{a_k} = m + \log\sum_{k=1}^K e^{a_k - m}, \qquad m = \max_k a_k.

Subtracting the maximum avoids overflow (eae^{a} infinite) and total underflow (all zero). A mixture ∑kπk pk(x)\sum_k \pi_k\, p_k(x) is evaluated as LSE⁡k(log⁡πk+log⁡pk(x))\operatorname{LSE}_k\big(\log\pi_k + \log p_k(x)\big).

3. Initialize with a cheap consistent estimator, such as last lesson’s method of moments, and try several starts if local maxima are possible.

4. Check. Gradient at the solution should be near zero, Hessian negative definite (or the optimizer equivalent), and results from multiple starts should agree. An optimizer saying it finished is not the same as finding the global maximum.

[ ]Why calculations use logarithmsBrowser
import numpy as np

x = np.random.default_rng(0).normal(0.0, 1.0, size=1000)
dens = stats.norm.pdf(x)
print("producto de 1000 densidades:   ", np.prod(dens))
print("suma de sus 1000 logaritmos:   ", f"{np.log(dens).sum():.3f}")

a = np.array([-1000.0, -1001.0, -1002.0])               # tres log-probabilidades
with np.errstate(divide="ignore"):
    print("log(sum(exp(a))) ingenuo:      ", np.log(np.exp(a).sum()))
m = a.max()
print("log-suma-exponencial estable:  ", f"{m + np.log(np.exp(a - m).sum()):.6f}")

For the thousand observations, product is exactly 0.0 and log sum approximately −1397-1397. Naive log-sum-exp of three log-probabilities around −1000-1000 gives -inf; stable calculation gives −999.592-999.592, equal to −1000+log⁡(1+e−1+e−2)-1000 + \log(1 + e^{-1} + e^{-2}).

Now the full engine. Function mle receives log-density, data, a start, and for each parameter a pair (transformation to its domain, inverse transformation); it minimizes mean negative log-likelihood (so optimizer tolerance does not depend on nn) with scipy.optimize.minimize and returns the estimator in original units with diagnostics. Apply it to gamma (moment start), Weibull, and a two-normal mixture.

[ ]A generic MLE engine from scratchBrowser
from scipy.optimize import minimize
from scipy.special import gammaln, expit, logsumexp

IDENT = (lambda u: u, lambda t: t)                        # parámetro libre
POS = (np.exp, np.log)                                    # θ > 0 : θ = e^u
PROB = (expit, lambda p: np.log(p / (1 - p)))             # θ en (0, 1): θ = sigmoide(u)

def mle(logpdf, x, init, transforms, method="BFGS"):
    """EMV: minimiza la log-verosimilitud negativa media sobre parámetros sin restricciones."""
    fwd = [t[0] for t in transforms]
    u0 = np.array([t[1](v) for t, v in zip(transforms, init)])
    theta_de = lambda u: [f(ui) for f, ui in zip(fwd, u)]
    def nll(u):
        val = -np.mean(logpdf(x, *theta_de(u)))
        return val if np.isfinite(val) else 1e10          # barrera si algo sale mal
    res = minimize(nll, u0, method=method)
    return dict(theta=np.array(theta_de(res.x)), nll=res.fun, ok=res.success,
                iteraciones=res.nit, norma_grad=np.linalg.norm(res.jac))

def logpdf_gamma(x, a, b):
    return a * np.log(b) - gammaln(a) + (a - 1) * np.log(x) - b * x

def logpdf_weibull(x, k, lam):
    return np.log(k) - np.log(lam) + (k - 1) * (np.log(x) - np.log(lam)) - (x / lam) ** k

def logpdf_mezcla(x, pi, m1, s1, m2, s2):
    return logsumexp([np.log(pi) + stats.norm.logpdf(x, m1, s1),
                      np.log1p(-pi) + stats.norm.logpdf(x, m2, s2)], axis=0)

rng = np.random.default_rng(4)

xg = rng.gamma(3.0, 2.0, size=400)
m, v = xg.mean(), xg.var()
r = mle(logpdf_gamma, xg, (m**2 / v, m / v), [POS, POS])
sc = stats.gamma.fit(xg, floc=0)
print("gamma    propio:", np.round(r["theta"], 5), f"| scipy: ({sc[0]:.5f}, {1 / sc[2]:.5f}) | verdad (3, 0.5)")
print(f"         {r['iteraciones']} iteraciones, norma del gradiente {r['norma_grad']:.1e}")

xw = 2.0 * rng.weibull(1.5, size=400)
r = mle(logpdf_weibull, xw, (1.0, 1.0), [POS, POS])
sc = stats.weibull_min.fit(xw, floc=0)
print("Weibull  propio:", np.round(r["theta"], 5), f"| scipy: ({sc[0]:.5f}, {sc[2]:.5f}) | verdad (1.5, 2)")

z = rng.random(300) < 0.3
xm = np.where(z, rng.normal(-2.0, 0.7, 300), rng.normal(2.0, 1.0, 300))
q1, q3 = np.quantile(xm, [0.25, 0.75])
r = mle(logpdf_mezcla, xm, (0.5, q1, 1.0, q3, 1.0), [PROB, IDENT, POS, IDENT, POS])
print("mezcla   propio:", np.round(r["theta"], 3), "| verdad (0.3, -2, 0.7, 2, 1)")
print(f"         log-verosimilitud media por dato {-r['nll']:.4f}")

All three fits recover true parameters within expected sample error (gamma shape is 2.662.66 versus 33, less than two standard errors, about 0.20.2 at n=400n = 400), and gamma and Weibull agree with scipy to four or five digits (differences come from optimizer stopping criteria). Note the mixture needs the most care: initialized from data quantiles; starting μ1=μ2\mu_1 = \mu_2 would prevent the optimizer distinguishing components.

Pathological cases

The MLE recipe fails in four distinct ways. None is exotic: all occur in data science practice.

Unbounded likelihood: mixtures

A two-normal mixture has density p(x)=π φ(x;μ1,σ12)+(1−π) φ(x;μ2,σ22)p(x) = \pi\,\varphi(x;\mu_1,\sigma_1^2) + (1-\pi)\,\varphi(x;\mu_2,\sigma_2^2) and five parameters. It looks innocent, but its log-likelihood has no maximum.

Proof

The x1x_1 term satisfies p(x1)≥π φ(x1;x1,σ12)=π/(σ12π)p(x_1) \ge \pi\,\varphi(x_1; x_1, \sigma_1^2) = \pi/(\sigma_1\sqrt{2\pi}). For every i≥2i \ge 2, p(xi)≥(1−π) φ(xi;μ2,σ22)>0p(x_i) \ge (1-\pi)\,\varphi(x_i;\mu_2,\sigma_2^2) > 0, independent of σ1\sigma_1. Summing logarithms, ℓ≥−log⁡σ1+C\ell \ge -\log\sigma_1 + C with constant CC, and −log⁡σ1→+∞-\log\sigma_1 \to +\infty.

∎

The intuition is the spike. A component centered exactly on one observation with almost no width concentrates all probability there and gives enormous density (∼π/σ1\sim\pi/\sigma_1) to that observation while the other component covers the rest. Pay a finite price for the remaining n−1n-1 observations and gain an unbounded reward on one. Try it.

InteractiveAn exploding likelihood
Mixture density with μ₁ = −0.3, σ₁ = 0.032 and π = 0.11
peak 1.6
  • mixture density
  • anchored observation
  • other observations
Profile log likelihood versus σ1\sigma_1 (component narrows to the right)
reasonable local maximum
  • profile ℓp(σ1)\ell_p(\sigma_1)
  • reasonable local maximum
  • exceeds reasonable fit
x4 = −0.3
0.032
0.1000
Effective σ1\sigma_10.032
Mixture ℓ(θ)\ell(\theta)−16.31
Reasonable fit ℓ\ell (EM, local maximum)−13.68
Difference from reasonable fit−2.63
Density peak height at xjx_j1.58
ℓ(σ1)−ℓ(10 σ1)\ell(\sigma_1) - \ell(10\,\sigma_1) (tends to ln⁡10=2.30\ln 10 = 2.30)1.29
Eight observations and a two-normal mixture. Component 1 is anchored at your chosen observation; other parameters (π\pi, μ2\mu_2, σ2≥0.3\sigma_2 \ge 0.3) are refit by EM for each σ1\sigma_1, so the right curve is profile log-likelihood of σ1\sigma_1. Start at σ1=0.03\sigma_1 = 0.03: the curve is still below the reasonable local maximum (orange). Lower to 10−610^{-6} and inspect spike height: likelihood does not stop, and each division of σ1\sigma_1 by 10 adds ln⁡10=2.30\ln 10 = 2.30. Change the anchored observation: same result. The orange line is the reasonable local maximum with all mixture parameters free, including μ1\mu_1: at what σ1\sigma_1 does the curve exceed it? Enable bound σ≥σmin⁡\sigma \ge \sigma_{\min} and verify the supremum becomes finite.

Two remedies are used. First, bound parameter space: require σk≥σmin⁡\sigma_k \ge \sigma_{\min} (as reg_covar in sklearn.mixture.GaussianMixture does by adding a small constant, default 10−610^{-6}, to covariance diagonals), or bound the ratio of standard deviations, Hathaway’s formulation (1985). Second, regularize with a prior penalizing degenerate components (weakly informative priors). In practice EM finds a reasonable local maximum, and the infinite supremum is a theoretical trap worth recognizing when one component collapses onto one observation: a common symptom of fitting too many mixture components.

Perfect separation: logistic regression without a maximum

In logistic regression, P(Y=1∣x)=σ(w⊤x)\Pr(Y = 1 \mid \vb{x}) = \sigma(\vb{w}\T\vb{x}) and log-likelihood is ℓ(w)=−∑ilog⁡(1+e−ci w⊤xi)\ell(\vb{w}) = -\sum_i\log\big(1 + e^{-c_i\,\vb{w}\T\vb{x}_i}\big) with ci=2yi−1∈{−1,+1}c_i = 2y_i - 1 \in \{-1, +1\}. If direction w0\vb{w}_0 correctly classifies every observation, ci w0⊤xi>0c_i\,\vb{w}_0\T\vb{x}_i > 0 for every ii (complete separation), every summand improves as w=t w0\vb{w} = t\,\vb{w}_0 grows: ℓ(t w0)\ell(t\,\vb{w}_0) strictly increases in tt and tends to 00 as t→∞t \to \infty. But ℓ(w)<0\ell(\vb{w}) < 0 for every finite w\vb{w}: supremum 00 is not attained. The MLE does not exist. Software symptoms include huge coefficients, absurd standard errors, fitted probabilities exactly 00 and 11, and convergence warnings. Remedies include regularization (L2 or Firth penalty) or a prior.

[ ]Perfect separation: the maximum recedes without boundBrowser
X = np.array([-2.0, -1.0, 1.0, 2.0])
y = np.array([0, 0, 1, 1])
c = 2 * y - 1

print("  w      -log-verosimilitud")
for w in (1, 2, 5, 10, 20, 50):
    print(f"{w:4d}   {np.sum(np.log1p(np.exp(-c * w * X))):.3e}")

w = 0.0
print("\nNewton sobre la log-verosimilitud:")
for it in range(1, 13):
    p = 1 / (1 + np.exp(-w * X))
    g = np.sum((y - p) * X)
    H = -np.sum(p * (1 - p) * X * X)
    w = w - g / H
    if it in (1, 2, 3, 6, 12):
        print(f"  iteración {it:2d}: w = {w:7.3f}   score = {g:.2e}")

Loss keeps falling (from 0.880.88 at w=1w = 1 to 4⋅10−224\cdot 10^{-22} at w=50w = 50) and Newton advances nearly one unit step per iteration: score keeps shrinking, so “score near zero” stopping eventually accepts a meaningless ww. The trap is that the optimizer converges, but not to a maximum.

Multiple local maxima

Log-likelihood need not be concave. The classical example is Cauchy location: with a few widely spaced observations, likelihood is multimodal. A local optimizer finds only the peak nearest its start.

[ ]Three local maxima in a Cauchy sampleBrowser
x = np.array([-6.0, -5.2, 0.3, 5.5, 6.1])
rejilla = np.linspace(-12, 12, 4801)
ll = np.array([stats.cauchy.logpdf(x, t).sum() for t in rejilla])
picos = [i for i in range(1, len(ll) - 1) if ll[i] > ll[i - 1] and ll[i] > ll[i + 1]]
print("máximos locales de la log-verosimilitud (posición, valor):")
for i in picos:
    print(f"  theta = {rejilla[i]:6.2f}   l = {ll[i]:.3f}")
print(f"el máximo global está en {rejilla[np.argmax(ll)]:.2f}; mediana de los datos = {np.median(x)}")

There are three local maxima near −5.3-5.3, 0.30.3, and 5.65.6, with very similar log-likelihoods (−19.25-19.25, −19.75-19.75, and −19.00-19.00). The robust median lies at the central peak, worst of the three. The optimizer’s local maximum depends on its start: try multiple starts, compare solution ℓ\ell values, and plot likelihood when suspicious. Mixtures add harmless multiplicity: permuting component labels yields the same ℓ\ell because the model is identifiable only up to permutation (identifiability).

A boundary or nonunique maximum

The Unif⁡(0,θ)\Unif(0,\theta) maximum lies at a discontinuity and Bernoulli with k=0k = 0 at the parameter-space boundary: in both, score is nonzero and step 2 of the recipe fails. For a nonidentifiable model, argmax is a manifold of equivalent parameters (the ridge in the statistical models lesson), so “the” MLE is not singular. The method still works if adapted, but requires inspecting likelihood, not merely differentiating.

Likelihood and cross-entropy

The connection making maximum likelihood the engine of ML is an exact equality. For sample x1,…,xnx_1, \dots, x_n, empirical distribution p^=1n∑iδxi\hat p = \frac1n\sum_i\delta_{x_i} assigns mass 1/n1/n to each observation. The model qθq_\theta‘s mean negative log-likelihood is an expectation under it:

−1n ℓ(θ;x)=−1n∑i=1nlog⁡qθ(xi)=−Ep^[log⁡qθ(X)]=H(p^,qθ),-\frac{1}{n}\,\ell(\theta; x) = -\frac{1}{n}\sum_{i=1}^n \log q_\theta(x_i) = -\E_{\hat p}\big[\log q_\theta(X)\big] = H(\hat p, q_\theta),

the cross-entropy of p^\hat p relative to qθq_\theta. For categorical data, where p^v=nv/n\hat p_v = n_v/n are relative symbol frequencies, H(p^,q)=−∑vp^vlog⁡qvH(\hat p, q) = -\sum_v \hat p_v\log q_v.

Cross-entropy decomposes: H(p^,qθ)=H(p^)+KL⁡(p^ ∥ qθ)H(\hat p, q_\theta) = H(\hat p) + \KL(\hat p\,\|\,q_\theta), with data entropy H(p^)H(\hat p) independent of θ\theta. Thus maximizing likelihood minimizes Kullback–Leibler divergence from empirical distribution to model:

θ^EMV=arg max⁡θℓ(θ;x)=arg min⁡θH(p^,qθ)=arg min⁡θKL⁡(p^ ∥ qθ).\hat\theta_{\text{EMV}} = \argmax_\theta \ell(\theta; x) = \argmin_\theta H(\hat p, q_\theta) = \argmin_\theta \KL(\hat p\,\|\,q_\theta).

For an unconstrained categorical model this solves completely, giving the shortest proof that relative frequency is the MLE.

Proof

H(p^,q)−H(p^)=KL⁡(p^ ∥ q)=∑vp^vlog⁡(p^v/qv)=−∑vp^vlog⁡(qv/p^v)H(\hat p, q) - H(\hat p) = \KL(\hat p\,\|\,q) = \sum_v \hat p_v\log(\hat p_v/q_v) = -\sum_v\hat p_v\log(q_v/\hat p_v), summing only over vv with p^v>0\hat p_v > 0. By Jensen’s inequality for concave log⁡\log, −∑vp^vlog⁡(qv/p^v)≥−log⁡∑vp^v (qv/p^v)=−log⁡∑v:p^v>0qv≥−log⁡1=0-\sum_v\hat p_v\log(q_v/\hat p_v) \ge -\log\sum_v\hat p_v\,(q_v/\hat p_v) = -\log\sum_{v:\hat p_v > 0} q_v \ge -\log 1 = 0. Equality requires qv/p^vq_v/\hat p_v constant where p^v>0\hat p_v > 0 and qq to have no mass outside those symbols, meaning q=p^q = \hat p.

∎

This happens in the next interactive with a corpus of 2020 tokens and a five-symbol model q=softmax⁡(z)q = \softmax(\vb{z}), the logit parameterization used by a network’s last layer.

InteractiveCross-entropy is log-likelihood
Corpus: 20 tokens. Each bar is −ln⁡q(xt)-\ln q(x_t), the model’s surprise at that token; the dashed line is the mean loss
elgatocomeelpez.elgatocomeelgatocomeelgato.elgatopezelcomemean loss 1.745
Corpus frequencies p^\hat p (hollow) and model qq (filled); above, contribution −p^vln⁡qv-\hat p_v \ln q_v
0.6440.2350.4680.1240.274
Loss varying only qgatoq_{\text{gato}} (the rest rescaled): minimum at p^\hat p
H(p̂)
  • current loss
  • slice minimum at q=p^q = \hat p
  • excess over H(p^)H(\hat p)
0.00
0.90
−0.50
0.60
−0.90
Mean loss per token 1N∑t−ln⁡q(xt)\frac1N\sum_t -\ln q(x_t)1.7447
By symbol ∑vp^v(−ln⁡qv)\sum_v \hat p_v(-\ln q_v)1.7447
H(p^)+KL⁡(p^ ∥ q)H(\hat p) + \KL(\hat p\,\|\,q)1.4964 + 0.2483
Perplexity elosse^{\text{loss}}5.724
Corpus log likelihood ℓ=−N⋅\ell = -N\cdotloss−34.89
References: uniform ln⁡5\ln 5 | minimum H(p^)H(\hat p)1.6094 | 1.4964
Top: corpus (20 tokens). Each bar's height is −ln⁡q(xt)-\ln q(x_t), the model's surprise at that token; dashed line is the mean: loss. Move logits. Left: corpus frequencies p^\hat p (empty) and model qq (filled); over each symbol, contribution −p^vln⁡qv-\hat p_v \ln q_v. Right: loss when only one symbol's probability varies: the minimum is always its frequency. Verify all three loss readouts (token mean, symbol sum, H+KL⁡H + \KL) match. Press 'Shuffle corpus': nothing changes. Press 'q=p^q = \hat p': loss reaches minimum H(p^)H(\hat p). What is perplexity with a uniform model?

Three observations. Loss does not depend on order: only counts, just as coin likelihood depended only on kk. The minimum is a lower bound (H(p^)=1.496H(\hat p) = 1.496 nats in this corpus): no model can have lower loss on these data, and reaching it with a flexible model usually means memorizing the corpus. Perplexity, exp⁡(peˊrdida)\exp(\text{pérdida}), has a simple interpretation: the number of equiprobable symbols among which the model hesitates; uniform qq on five symbols gives exactly 55.

Which losses are MLE?

The same reasoning with different qθq_\theta explains everyday losses.

Data model−log⁡qθ(y∣x)-\log q_\theta(y\mid\vb{x})Loss minimized
y∼N(fθ(x),σ2)y \sim \Normal(f_\theta(\vb{x}), \sigma^2), fixed σ\sigma12σ2(y−fθ(x))2+cte\frac{1}{2\sigma^2}(y - f_\theta(\vb{x}))^2 + \text{cte}mean squared error
y∼Bern⁡(σ(fθ(x)))y \sim \Bern(\sigma(f_\theta(\vb{x})))−ylog⁡y^−(1−y)log⁡(1−y^)-y\log\hat y - (1-y)\log(1-\hat y)binary cross-entropy
y∼Cat⁡(softmax⁡(fθ(x)))y \sim \operatorname{Cat}(\softmax(f_\theta(\vb{x})))−log⁡y^y-\log\hat y_{y}multiclass cross-entropy
y∼Pois⁡(efθ(x))y\sim\Pois(e^{f_\theta(\vb{x})})efθ(x)−y fθ(x)+ctee^{f_\theta(\vb{x})} - y\,f_\theta(\vb{x}) + \text{cte}Poisson deviance

In the table, y^=σ(fθ(x))\hat y = \sigma(f_\theta(\vb{x})) for binary and y^=softmax⁡(fθ(x))\hat y = \softmax(f_\theta(\vb{x})) for multiclass, with y^y\hat y_y its observed-class component: network output is model-assigned probability for each class.

Linear and logistic regression, and the entire generalized linear model family, are precisely this. Note that “changing the loss” changes the noise model: squared error assumes constant-variance Gaussian noise, and heavy-tailed errors require a different loss.

A language model is MLE

An autoregressive language model factorizes sequence probability by the chain rule, pθ(x1,…,xT)=∏t=1Tpθ(xt∣x<t)p_\theta(x_1, \dots, x_T) = \prod_{t=1}^T p_\theta(x_t \mid x_{<t}), and trains by minimizing

L(θ)=−1T∑t=1Tlog⁡pθ(xt∣x<t),\mathcal{L}(\theta) = -\frac{1}{T}\sum_{t=1}^T \log p_\theta(x_t \mid x_{<t}),

mean negative log-likelihood per token, also averaged across the corpus. This is the same calculation with a categorical vocabulary distribution at each position, logits from a network. If a model distributes mass uniformly, initial loss is ln⁡V\ln V: for vocabulary size V=50257V = 50257 tokens, ln⁡50257=10.825\ln 50257 = 10.825 nats, a classic training-start sanity check (another value signals an implementation error). Divide by ln⁡2\ln 2 for bits per character or token.

A nuance developed in asymptotic theory: if the model excludes the true distribution (usual with real data), MLE does not converge to “truth” but to the model distribution closest in Kullback–Leibler divergence. This precisely defines “best fit within model expressiveness” (misspecified MLE).

Maximum-likelihood character model

See everything together in a small example: a character language model with a transition table. Each character depends only on the previous, p(xt∣xt−1)=Pxt−1,xtp(x_t\mid x_{t-1}) = P_{x_{t-1},x_t}, and each row of PP is categorical. Each row’s MLE is relative frequencies of observed pairs. Check it, measure bits-per-character loss, and observe what happens on new text.

[ ]A character model: MLE, loss, and zero probabilitiesBrowser
train = ("el aprendizaje automático consiste en ajustar un modelo a los datos. "
         "un modelo de lenguaje asigna una probabilidad a cada texto y se entrena maximizando la verosimilitud de un corpus. "
         "la pérdida por carácter es el logaritmo negativo de la probabilidad que el modelo da al carácter siguiente. "
         "cuanto menor es la pérdida, mejor predice el modelo el texto que todavía no ha visto. "
         "el estimador de máxima verosimilitud de las probabilidades de transición son las frecuencias relativas de cada par de caracteres. ")
test = "la máxima verosimilitud es un principio general. un modelo pequeño puede predecir bien los pares de letras frecuentes pero falla ante un par que nunca vio."

chars = sorted(set(train + test + "^"))                  # «^» marca el inicio del texto
idx = {c: i for i, c in enumerate(chars)}
V = len(chars)

def pares(texto):
    t = "^" + texto
    return np.array([idx[c] for c in t[:-1]]), np.array([idx[c] for c in t[1:]])

def bits_por_caracter(P, texto):
    a, b = pares(texto)
    with np.errstate(divide="ignore"):
        return -np.mean(np.log2(P[a, b]))

a, b = pares(train)
C = np.zeros((V, V))
np.add.at(C, (a, b), 1)                                  # recuentos de cada par
filas = C.sum(axis=1, keepdims=True)
P = np.divide(C, filas, out=np.zeros_like(C), where=filas > 0)   # EMV: frecuencias relativas

print(f"vocabulario {V}, pares de entrenamiento {len(a)}; el modelo uniforme da {np.log2(V):.3f} bits/carácter")
print(f"EMV (frecuencias relativas): {bits_por_caracter(P, train):.4f} bits/carácter en el corpus de entrenamiento")

rng = np.random.default_rng(0)
for k in range(3):                                       # cualquier otra tabla debe ser peor
    Q = P * np.exp(0.3 * rng.standard_normal(P.shape))
    Q /= Q.sum(axis=1, keepdims=True)
    print(f"   tabla perturbada {k + 1}:    {bits_por_caracter(Q, train):.4f}")

a2, b2 = pares(test)
vistos = C[a2, b2] > 0
print(f"\ntexto nuevo: {np.sum(~vistos)} de {len(a2)} pares nunca aparecieron en el entrenamiento")
print(f"EMV sobre el texto nuevo: {bits_por_caracter(P, test)} bits/carácter")
for alfa in (1e-3, 1e-2, 0.1, 1.0):
    S = C + alfa                                         # suavizado aditivo
    S = S / S.sum(axis=1, keepdims=True)
    print(f"   suavizado {alfa:<6}: test {bits_por_caracter(S, test):.3f}   entrenamiento {bits_por_caracter(S, train):.3f}")

Three facts in the output. First, MLE gives minimum loss on the training corpus (2.682.68 bits per character versus 5.045.04 for uniform; any perturbation worsens to 2.722.72 or more, as the categorical theorem guarantees). Second, new text contains pairs absent from the corpus (2020 of 155155), MLE assigns 00 probability and loss is infinite: the estimator is too faithful to data, simplest overfitting. Third, additive smoothing (add α\alpha to every count) restores finite loss; among tested values α=0.1\alpha = 0.1 is best with 3.593.59 bits (too-small α\alpha leaves new text surprising, while α=1\alpha = 1 dilutes learning and training loss only worsens as α\alpha rises): adding pseudocounts equals the posterior mean under a symmetric Dirichlet prior, developed in Bayesian inference. In a real language model, regularization, data size, and logit shape provide smoothing (softmax never gives exactly zero probability).

With libraries

scipy.stats implements fit for all continuous distributions: numerical MLE with the scheme just written. Fix parameters not estimated (floc=0 for gamma and Weibull, since scipy adds a location parameter). statsmodels offers GenericLikelihoodModel: give it per-observation negative log-likelihood and it returns the estimator and standard-error estimates from the numerical Hessian, justified by next lesson’s Fisher information and asymptotic theory. Returned standard errors are on the parameterization scale (here log⁡α\log\alpha and log⁡β\log\beta); the delta method converts them.

[ ]scipy.stats and statsmodels versus custom implementationBrowser
import warnings
from statsmodels.base.model import GenericLikelihoodModel

warnings.simplefilter("ignore")

class GammaEMV(GenericLikelihoodModel):
    """Gamma(forma a, tasa b), parámetros libres (log a, log b)."""
    def nloglikeobs(self, params):
        a, b = np.exp(params)
        return -logpdf_gamma(self.endog, a, b)

mod = GammaEMV(xg, np.ones(len(xg)))
res = mod.fit(start_params=np.log([m**2 / v, m / v]), method="bfgs", disp=0)
print(f"{'método':<22} {'alfa':>10} {'beta':>10}")
propio = mle(logpdf_gamma, xg, (m**2 / v, m / v), [POS, POS])
sc_gamma = stats.gamma.fit(xg, floc=0)
print(f"{'propio (BFGS)':<22} {propio['theta'][0]:10.5f} {propio['theta'][1]:10.5f}")
print(f"{'scipy.stats.gamma.fit':<22} {sc_gamma[0]:10.5f} {1 / sc_gamma[2]:10.5f}")
print(f"{'statsmodels':<22} {np.exp(res.params[0]):10.5f} {np.exp(res.params[1]):10.5f}")
print(f"log-verosimilitud en el máximo: statsmodels {res.llf:.4f} | propia {-len(xg) * propio['nll']:.4f}")
print("errores estándar de (log alfa, log beta):", np.round(res.bse, 4))

All three estimators and maximum log-likelihood agree in every displayed digit, as expected: they solve the same optimization. The practical lesson: fit is convenient but opaque; it does not report optimizer convergence, alternative local maxima, or parameterization; a custom engine controls transformations, start, and diagnostics.

Common mistakes

Exercises

ProofMLE invariance
Prove: Let θ^\hat\theta be an MLE of θ\theta and g ⁣:Θ→Hg\colon\Theta\to H any function. Prove g(θ^)g(\hat\theta) maximizes induced likelihood L∗(η)=sup⁡{L(θ):g(θ)=η}L^\ast(\eta) = \sup\{L(\theta) : g(\theta) = \eta\}.
0
Write η^=g(θ^)\hat\eta = g(\hat\theta) and compare L∗(η)L^\ast(\eta) with L(θ^)L(\hat\theta) for arbitrary η\eta.

Step 1 of 3. gg is not injective. How is the likelihood of η\eta defined?

ProofMLE of a normal sample
Prove: Let X1,…,Xn∼iidN(μ,v)X_1, \dots, X_n \iid \Normal(\mu, v) with v=σ2v = \sigma^2, n≥2n \ge 2, and nonconstant data. Prove (μ^,v^)=(xˉ,SS⁡/n)(\hat\mu, \hat v) = (\bar x, \operatorname{SS}/n) uniquely maximizes ℓ(μ,v)\ell(\mu, v) and the Hessian there is negative definite.
0
Write ℓ(μ,v)=−n2log⁡(2πv)−12v∑i(xi−μ)2\ell(\mu, v) = -\frac n2\log(2\pi v) - \frac{1}{2v}\sum_i(x_i-\mu)^2 and SS⁡=∑i(xi−xˉ)2\operatorname{SS} = \sum_i(x_i - \bar x)^2.

Step 1 of 4. What does the likelihood equation in μ\mu give?

NumericUniform MLE
Observe X1,…,X4∼iidUnif⁡(0,θ)X_1, \dots, X_4 \iid \Unif(0, \theta) with values 2.12.1, 0.70.7, 3.43.4, and 1.91.9. Calculate the maximum-likelihood estimate of θ\theta.
NumericInvariance: MLE of a probability
A normal sample has xˉ=10\bar x = 10 and σ^2=1n∑i(xi−xˉ)2=4\hat\sigma^2 = \frac1n\sum_i(x_i - \bar x)^2 = 4. Calculate the MLE of P(X>13)\Pr(X > 13).
NumericBias of a rate MLE
Let X1,…,X5∼iidExp⁡(λ)X_1, \dots, X_5 \iid \operatorname{Exp}(\lambda) and λ^=1/Xˉ\hat\lambda = 1/\bar X be the rate MLE. By what factor does E[λ^]\E[\hat\lambda] multiply true rate λ\lambda?
NumericLoss of an untrained language model
A language model with a vocabulary of 5025750257 tokens initially assigns uniform probability to all. What mean per-token cross-entropy loss (in nats) should be measured on any corpus?
QuizWhat likelihood is and is not
Which likelihood statements are true?

More than one answer may be correct.

QuizLogistic MLE with separable classes
Fit logistic regression with intercept and classes are linearly separable in feature space. What happens to the maximum-likelihood estimator?
QuizLosses that are maximum likelihood
Which statements are true?

More than one answer may be correct.

CodeLog-sum-exp and mixture log-likelihood
Implement (a) logsumexp(a, axis=-1), the stable function log⁡∑keak\log\sum_k e^{a_k} (which must return -inf if all elements are -inf), and (b) mixture_loglik(x, pi, mu, sigma), total log-likelihood ∑ilog⁡∑kπk N(xi;μk,σk2)\sum_i\log\sum_k\pi_k\,\Normal(x_i;\mu_k,\sigma_k^2) of a KK-component Gaussian mixture, computed with logsumexp without overflow even when log-densities are order −1800-1800. x has shape (n,) and pi, mu, sigma have shape (K,).
import numpy as np

def logsumexp(a, axis=-1):
  """log(sum(exp(a))) de forma estable."""
  a = np.asarray(a, dtype=float)
  return np.log(np.sum(np.exp(a), axis=axis))   # ingenua: se desborda

def mixture_loglik(x, pi, mu, sigma):
  """Log-verosimilitud total de una mezcla gaussiana de K componentes."""
  # tu código: log pi_k + log N(x_i; mu_k, sigma_k) para cada (i, k), logsumexp sobre k y suma sobre i
  return 0.0
Shift+Enter to run

Summary

Key idea
Maximum likelihood chooses the parameter making observed data most probable: maximize ℓ(θ)=∑ilog⁡p(xi;θ)\ell(\theta) = \sum_i\log p(x_i;\theta), measuring model fit to empirical distribution; any cross-entropy loss minimizes its negative, from a coin to a language model.
  • Likelihood L(θ;x)=p(x;θ)L(\theta;x) = p(x;\theta) is a parameter function with fixed data, defined up to a constant; it is not a density over θ\theta (binomial with n=10n = 10, k=7k = 7 has area 1/111/11). Values do not change on reparameterization.
  • Log-likelihood turns products into sums (avoiding underflow). Score s=∇ℓs = \grad\ell has zero expectation under the true parameter if support is independent of θ\theta, and likelihood equations s=0s = 0 are its sample version.
  • Closed forms: xˉ\bar x for Bernoulli, Poisson, and normal μ\mu; 1/xˉ1/\bar x for exponential rate; SS⁡/n\operatorname{SS}/n for σ2\sigma^2 (biased, though lower MSE than unbiased at n=10n = 10); and X(n)X_{(n)} for uniform, at the boundary without differentiation.
  • Invariance: g(θ^)g(\hat\theta) is the MLE of g(θ)g(\theta) (proved using induced likelihood). Unbiasedness is not inherited.
  • Numerical MLE: minimize mean negative log-likelihood over unconstrained parameters (log⁡σ\log\sigma, sigmoid, softmax), use log-sum-exp, initialize with moments, and check gradient and several starts. Gamma shape reduces to an equation involving digamma that Newton solves in two or three steps.
  • Pathologies: Gaussian mixture likelihood is unbounded (bound σ\sigma or regularize); logistic regression under perfect separation has no MLE; Cauchy has multiple local maxima; uniform and Bernoulli with k=0k = 0 have boundary maxima.
  • Cross-entropy: −ℓ/n=H(p^,qθ)=H(p^)+KL⁡(p^ ∥ qθ)-\ell/n = H(\hat p, q_\theta) = H(\hat p) + \KL(\hat p\,\|\,q_\theta), so MLE minimizes Kullback–Leibler divergence from data to model; categorical MLE is relative frequencies; MSE, binary and multiclass cross-entropy, and language-model token loss are negative log-likelihoods of specific noise models.