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
- 05Statistical modelIdentifiabilityPoint estimator and estimandBias of an estimatorMethod of moments
- 03GradientHessian matrixClassification of critical points
- 04Bernoulli-trial distributionsUnivariate normal distributionExponential, gamma and chi-squared distributionsIndependent random variablesJoint law and marginals
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 of heads, you answer without thinking. This is so natural it hides a decision: among possible values of , you chose the one making what you saw most probable. The probability of that particular sequence is , and this function of peaks at .
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 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 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 , each a probability mass or density function. Joint probability of sample of independent identically distributed variables is product (the joint law factorizes by independence). Until now we read it as a function of with fixed . 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 , and no reasonable conclusion should depend on that choice. Likelihood is therefore defined “up to a constant,” and we use relative likelihood , equal to at the maximum.
In the coin example, with heads in flips, if the sequence is recorded, or if only the head count is recorded: proportional, hence the same likelihood. Add flips in the interactive and see how the curve changes.
Notice three things. First, the maximum follows observed proportion (orange line). Second, the curve sharpens: with little data many values explain observations almost equally well; with much data only those near do. Width of the region visually represents uncertainty, narrowing as . 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
The commonest conceptual error is reading as “probability the parameter equals .” It is not, as a calculation shows. For the binomial model with and ,
and recording the sequence instead of the count gives area . Neither integrates to , and the value depends on what was recorded, precisely the arbitrary constant in the definition. Likelihood is a function of that is not a distribution of ; obtaining one requires a prior distribution (Bayesian inference, lesson 21).
There is a subtler distinction from densities. Reparameterizing by bijection gives likelihood : values are preserved and no Jacobian appears. A density of , by contrast, changes under reparameterization and its maximum moves. Since ‘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 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, normal data have likelihood of order , rounded to ), 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 is strictly increasing, and attain maxima at the same point.
For differentiation use the score function.
For the coin, , and gives . The second-order condition comes from the Hessian: , so 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 is a density, for every . Differentiate both sides with respect to and exchange derivative and integral:
We used .
∎Interpretation: likelihood equations are the sample version of population equation , 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:
- Write and simplify, removing everything independent of .
- Calculate score and set it to zero.
- Check the critical point is a maximum (negative definite Hessian or concavity) and global.
- Inspect the boundary of and points where is not differentiable: the maximum may be there.
Five closed-form models
| Model | Parameter | MLE | Bias |
|---|---|---|---|
| unbiased | |||
| unbiased | |||
| exponential (rate ) | |||
| unbiased | |||
Bernoulli and Poisson. For Bernoulli, with , and the calculation above gives . If or the curve is monotone and the maximum is at boundary or , outside open parameter space : the MLE exists only if closure is allowed. For Poisson, and gives . Both MLEs coincide with moment estimators.
Exponential. With (exponential-gamma family), and give . It is biased: since , , too high at . Bias vanishes as , the price of being a nonlinear function of a mean (Jensen’s inequality).
Normal. With both parameters unknown and , . Identity separates parameters: for any , is maximized at , whatever . Substitution leaves with , maximized at . The variance estimator divides by , not : it is biased, and the previous lesson showed its MSE ( at ) is lower than unbiased sample variance ().
There is a way to see this together. In the next interactive a normal sample’s log-likelihood is a surface over ; drag sample points and watch the peak move.
Ridge expresses the preceding calculation: the optimum in does not depend on , so the surface has a straight “backbone” and the problem reduces to a curve in (the profile likelihood of , returning in profile likelihood intervals). Asymmetry is strong: halving from costs log-likelihood units while raising it by half costs only , ratio . On scale, with symmetric steps , the ratio is . This is neither accidental nor data-dependent: as a function of is plus a constant, nearly quadratic in and clearly nonquadratic in . This explains optimizing via : besides removing , it yields a much easier surface for Newton and similar methods.
Uniform. The last case is not solved by differentiation. With ,
because the indicator product is exactly when all data fit in . For likelihood is zero (that makes an observed value impossible). For it decreases as . The maximum is at the discontinuity: , where no critical point exists (score never vanishes).
This estimator was missing from the previous lesson. Moments gave , contradicting the data with probability tending to ; the MLE by construction never does. Its error is order , not : and , versus for moments. With data , , , and , MLE is , moment estimator , and bias-corrected maximum is .
Invariance
Likelihood does not rescale on reparameterization, with a practical consequence: if you can estimate , you can estimate any function of it. If is not injective, define “likelihood of ” by maximizing over preimages.
Proof
Let . For any , set is contained in , so . Conversely belongs to , so . Combining, for every .
∎Immediate consequences without extra calculation: ; the MLE of for normal is ; the MLE of odds is ; and the MLE of exponential mean is , also unbiased, while the rate 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 with shape and rate :
Function is strictly decreasing (because ), tends to as and as ; 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, , starting from a well-known closed approximation , already within a fraction of a percent. This is the calculation statistical software hides behind gamma.fit.
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 to and , 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 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 or at some step and log-likelihood returns nan. Use a free parameter and transform: for scale, for probability, for a probability vector. By invariance, the maximum in is the maximum in and, as the surface showed, often gives a function much closer to quadratic.
2. Compute in log space. Do not evaluate : directly use log-density, which can be written stably. When a sum of probabilities appears (a mixture), use log-sum-exp:
Subtracting the maximum avoids overflow ( infinite) and total underflow (all zero). A mixture is evaluated as .
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.
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 . Naive log-sum-exp of three log-probabilities around gives -inf; stable calculation gives , equal to .
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 ) 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.
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 versus , less than two standard errors, about at ), 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 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 and five parameters. It looks innocent, but its log-likelihood has no maximum.
Proof
The term satisfies . For every , , independent of . Summing logarithms, with constant , and .
∎The intuition is the spike. A component centered exactly on one observation with almost no width concentrates all probability there and gives enormous density () to that observation while the other component covers the rest. Pay a finite price for the remaining observations and gain an unbounded reward on one. Try it.
Two remedies are used. First, bound parameter space: require (as reg_covar in sklearn.mixture.GaussianMixture does by adding a small constant, default , 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, and log-likelihood is with . If direction correctly classifies every observation, for every (complete separation), every summand improves as grows: strictly increases in and tends to as . But for every finite : supremum is not attained. The MLE does not exist. Software symptoms include huge coefficients, absurd standard errors, fitted probabilities exactly and , and convergence warnings. Remedies include regularization (L2 or Firth penalty) or a prior.
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 at to at ) and Newton advances nearly one unit step per iteration: score keeps shrinking, so “score near zero” stopping eventually accepts a meaningless . 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.
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 , , and , with very similar log-likelihoods (, , and ). 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 values, and plot likelihood when suspicious. Mixtures add harmless multiplicity: permuting component labels yields the same because the model is identifiable only up to permutation (identifiability).
A boundary or nonunique maximum
The maximum lies at a discontinuity and Bernoulli with 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 , empirical distribution assigns mass to each observation. The model ‘s mean negative log-likelihood is an expectation under it:
the cross-entropy of relative to . For categorical data, where are relative symbol frequencies, .
Cross-entropy decomposes: , with data entropy independent of . Thus maximizing likelihood minimizes Kullback–Leibler divergence from empirical distribution to model:
For an unconstrained categorical model this solves completely, giving the shortest proof that relative frequency is the MLE.
Proof
, summing only over with . By Jensen’s inequality for concave , . Equality requires constant where and to have no mass outside those symbols, meaning .
∎This happens in the next interactive with a corpus of tokens and a five-symbol model , the logit parameterization used by a network’s last layer.
Three observations. Loss does not depend on order: only counts, just as coin likelihood depended only on . The minimum is a lower bound ( 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, , has a simple interpretation: the number of equiprobable symbols among which the model hesitates; uniform on five symbols gives exactly .
Which losses are MLE?
The same reasoning with different explains everyday losses.
| Data model | Loss minimized | |
|---|---|---|
| , fixed | mean squared error | |
| binary cross-entropy | ||
| multiclass cross-entropy | ||
| Poisson deviance |
In the table, for binary and for multiclass, with 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, , and trains by minimizing
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 : for vocabulary size tokens, nats, a classic training-start sanity check (another value signals an implementation error). Divide by 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, , and each row of 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.
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 ( bits per character versus for uniform; any perturbation worsens to or more, as the categorical theorem guarantees). Second, new text contains pairs absent from the corpus ( of ), MLE assigns probability and loss is infinite: the estimator is too faithful to data, simplest overfitting. Third, additive smoothing (add to every count) restores finite loss; among tested values is best with bits (too-small leaves new text surprising, while dilutes learning and training loss only worsens as 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 and ); the delta method converts them.
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
Step 1 of 3. is not injective. How is the likelihood of defined?
Step 1 of 4. What does the likelihood equation in give?
More than one answer may be correct.
More than one answer may be correct.
logsumexp(a, axis=-1), the stable function (which must return -inf if all elements are -inf), and (b) mixture_loglik(x, pi, mu, sigma), total log-likelihood of a -component Gaussian mixture, computed with logsumexp without overflow even when log-densities are order . 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.0Summary
- Likelihood is a parameter function with fixed data, defined up to a constant; it is not a density over (binomial with , has area ). Values do not change on reparameterization.
- Log-likelihood turns products into sums (avoiding underflow). Score has zero expectation under the true parameter if support is independent of , and likelihood equations are its sample version.
- Closed forms: for Bernoulli, Poisson, and normal ; for exponential rate; for (biased, though lower MSE than unbiased at ); and for uniform, at the boundary without differentiation.
- Invariance: is the MLE of (proved using induced likelihood). Unbiasedness is not inherited.
- Numerical MLE: minimize mean negative log-likelihood over unconstrained parameters (, 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 or regularize); logistic regression under perfect separation has no MLE; Cauchy has multiple local maxima; uniform and Bernoulli with have boundary maxima.
- Cross-entropy: , 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.