AI Wiki中文/EN

Maximum likelihood estimation

最大似然估计

Derive Bernoulli and Gaussian estimates, handle missing and nonunique maxima, and state what consistency actually requires.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Choose a parameter, then ask what that choice means

In a hypothetical test, a binary system succeeds three times in four independent trials. Under a common Bernoulli success probability, the maximum likelihood estimate is 3/43/4. It is the value that gives the observed sequence its largest likelihood. It is not a 75% probability that the estimate is correct, and four trials do not make the underlying probability known.

There are three separate objects to keep track of. The likelihood is a function of possible parameters for fixed data. An estimator is a rule that takes a dataset and returns a parameter; before sampling, its output is random. An estimate is the particular output after seeing the data. A program that approximately optimizes the likelihood implements that rule only to its stated numerical accuracy.

The maximum may be inside, on a boundary, or absent

Given a model family and observations DD, maximum likelihood estimation seeks

θ^(D)∈arg max⁡θ∈ΘL(θ;D)=arg max⁡θ∈Θℓ(θ;D).\widehat\theta(D)\in\operatorname*{arg\,max}_{\theta\in\Theta}L(\theta;D)=\operatorname*{arg\,max}_{\theta\in\Theta}\ell(\theta;D).

The log is strictly increasing on positive likelihoods; zero likelihood can be assigned log value −∞-\infty. The argmax is a set, which can be empty or contain several points. A single-valued estimator needs a rule for choosing among ties. This definition and the distinction between attainable and unattainable maxima are developed in MIT, Lecture 2.

For hh successes in n>0n>0 independent Bernoulli trials, on 0<p<10<p<1,

ℓ(p)=hlog⁡p+(n−h)log⁡(1−p),ℓ′(p)=hp−n−h1−p,ℓ′′(p)=−hp2−n−h(1−p)2.\ell(p)=h\log p+(n-h)\log(1-p),\qquad \ell'(p)=\frac hp-\frac{n-h}{1-p},\qquad \ell''(p)=-\frac h{p^2}-\frac{n-h}{(1-p)^2}.

If 0<h<n0<h<n, solving the score equation ℓ′(p)=0\ell'(p)=0 gives p^=h/n\widehat p=h/n. The strictly negative second derivative and the endpoint behavior establish the unique global maximum. If h=0h=0, the likelihood decreases toward the included maximum p=0p=0; if h=nh=n, it increases toward p=1p=1. These endpoints are part of Θ=[0,1]\Theta=[0,1]. If instead the model insists on Θ=(0,1)\Theta=(0,1), the all-equal samples have only a supremum, not an attained MLE. Empty data give constant likelihood, so every parameter maximizes it. MIT, Bernoulli example

Next fit i.i.d. Xi∼N(μ,v)X_i\sim\mathcal N(\mu,v), where v=σ2>0v=\sigma^2>0 is the variance and both parameters are unknown. The log likelihood is

ℓ(μ,v)=−n2log⁡(2πv)−12v∑i=1n(xi−μ)2.\ell(\mu,v)=-\frac n2\log(2\pi v)-\frac1{2v}\sum_{i=1}^n(x_i-\mu)^2.

For every fixed vv, the 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(\mu-\bar x)^2 puts the optimum at xˉ\bar x. Write S=∑i(xi−xˉ)2S=\sum_i(x_i-\bar x)^2. When S>0S>0, the profiled derivative in vv is (S−nv)/(2v2)(S-nv)/(2v^2), positive below S/nS/n and negative above it. Hence

μ^=xˉ,v^ML=Sn,E[v^ML]=n−1nv.\widehat\mu=\bar x,\qquad \widehat v_{\mathrm{ML}}=\frac Sn,\qquad E[\widehat v_{\mathrm{ML}}]=\frac{n-1}{n}v.

For n≥2n\ge2, S>0S>0 almost surely under the nondegenerate Gaussian model; the expectation statement uses that sampling setting. The centered-sum identity underlying it actually holds for any i.i.d. population with finite variance. Since E[S]=nv−nVar⁡(Xˉ)=(n−1)vE[S]=nv-n\operatorname{Var}(\bar X)=(n-1)v, the likelihood estimate is biased downward. Dividing by n−1n-1 yields the unbiased sample variance, a different criterion. For [1,2,6][1,2,6], the mean is 3, S=14S=14, the MLE variance is 14/314/3, and the unbiased estimate is 7. MIT, normal example

The condition S>0S>0 matters. With identical observations, setting μ\mu to that common value and taking v↓0v\downarrow0 makes the density unbounded. Variance zero is outside the stated Gaussian parameter space. Reporting it as an ordinary fitted Gaussian hides a failure of existence. This always occurs for n=1n=1 when both mean and variance are free.

Separate a closed form from a restricted search

The complete Python example returns exact rational estimates for small rational datasets. gaussian_mle rejects zero scatter explicitly. grid_bernoulli_mle solves a different, restricted problem: choose among the supplied candidates. It preserves ties rather than pretending that a grid result proves a unique optimum over the continuous interval.

from fractions import Fraction as F

def exact(x):
    if type(x) is not int and not isinstance(x,F):
        raise ValueError("use integers or Fraction values")
    return F(x)

def bernoulli_mle(h,n):
    if type(h) is not int or type(n) is not int or not 0 <= h <= n:
        raise ValueError("integer counts with 0 <= h <= n required")
    if n == 0:
        raise ValueError("empty data: every p in [0,1] maximizes likelihood")
    return F(h,n)

def gaussian_mle(data):
    x = [exact(v) for v in data]
    if not x:
        raise ValueError("nonempty data required")
    mean = sum(x)/len(x)
    squared = sum((v-mean)**2 for v in x)
    if squared == 0:
        raise ValueError("no finite MLE with strictly positive variance")
    return mean,squared/len(x)

def grid_bernoulli_mle(h,n,candidates):
    bernoulli_mle(h,n)  # Validate counts; this API rejects empty data.
    p = [exact(v) for v in candidates]
    if not p or any(v < 0 or v > 1 for v in p):
        raise ValueError("nonempty candidate probabilities in [0,1] required")
    # Integer powers use the empty-product convention at the endpoints.
    values = [v**h*(1-v)**(n-h) for v in p]
    best = max(values)
    return [v for v,value in zip(p,values) if value == best],best

assert bernoulli_mle(3,4) == F(3,4)
assert bernoulli_mle(0,4) == 0
assert bernoulli_mle(4,4) == 1
assert gaussian_mle([1,2,6]) == (3,F(14,3))
winners,value = grid_bernoulli_mle(1,2,[F(1,4),F(3,4)])
assert winners == [F(1,4),F(3,4)] and value == F(3,16)
try:
    gaussian_mle([2,2])
except ValueError:
    pass
else:
    raise AssertionError("a collapsing variance must not be reported as a valid MLE")

Given counts, the Bernoulli closed form needs constant rational arithmetic and storage. Counting raw observations first costs O(n)O(n). The Gaussian implementation uses O(n)O(n) arithmetic and storage; a numerical online implementation can use constant extra storage. The grid evaluates gg candidates, with O(log⁡n)O(\log n) rational multiplications per integer power under exponentiation by squaring and O(g)O(g) stored results. Bit costs grow with numerator and denominator size, so exact fractions are a teaching choice for small problems. A large implementation should evaluate stable log likelihoods and report optimization tolerances.

Try supplying only 1/41/4 and 3/43/4 for one success in two trials. Both candidates tie, although the unrestricted optimum is 1/21/2. Increasing grid resolution may improve approximation; it does not turn a discrete scan into a proof about all real parameter values.

Fitting and statistical reliability are different questions

A derivative equal to zero is only an interior stationarity condition. Parameter-dependent support must remain in the objective: for nonnegative observations from Uniform⁡[0,θ]\operatorname{Uniform}[0,\theta] with θ>0\theta>0, the included-endpoint convention gives θ^=max⁡ixi\widehat\theta=\max_i x_i when that maximum is positive. This estimate occurs where the support first contains the data, not where a smooth score vanishes. The likelihood article treats the excluded-endpoint convention and all-zero data separately.

Non-identifiability can also prevent uniqueness. If a Gaussian mean is parameterized as a+ba+b, the data identify at most the sum: (a+c,b−c)(a+c,b-c) gives the same distribution for every cc. Mixture models can have additional local peaks. A numerical optimizer’s stopping message does not establish a global maximum, a unique parameterization, or a good model. Examine feasibility, multiple starts where appropriate, objective values, and out-of-sample behavior. MML, Sections 8.3.1 and 8.3.3 connects likelihood fitting, numerical optimization, and overfitting.

Consistency means convergence to the target as sample size grows; it is not the same as finite-sample unbiasedness. A precise small theorem shows the extra structure needed. Suppose the candidate set Θ\Theta is finite and contains the true parameter θ0\theta_0, samples are i.i.d. from its distribution, each log⁡fθ(X)\log f_\theta(X) is integrable, and Q(θ)=Eθ0[log⁡fθ(X)]Q(\theta)=E_{\theta_0}[\log f_\theta(X)] has a unique maximizer at θ0\theta_0. The law of large numbers makes each average log likelihood converge to Q(θ)Q(\theta). Finitely many candidates give simultaneous convergence; the strictly positive gap to the second-best expected value then forces any empirical maximizer to select θ0\theta_0 with probability tending to one.

For a continuum of parameters, pointwise convergence alone does not justify interchanging limit and argmax. Conditions controlling the objective uniformly and separating the true maximum are needed. Usual asymptotic normality results further depend on local smoothness, an interior parameter and nondegenerate information, among other model-specific regularity assumptions. Stanford, Lecture 14 explicitly notes that its classroom statement omits technical conditions. It must not be read as a guarantee for every MLE.

Check the estimator, not just its formula

  1. All four Bernoulli observations are zero. What changes when the parameter space changes from [0,1][0,1] to (0,1)(0,1)? Answer: the closed interval gives MLE 0. On the open interval the likelihood approaches 1 as p↓0p\downarrow0, but never attains it.
  2. For [1,2,6][1,2,6], would replacing 14/314/3 with 7 improve the Gaussian likelihood at mean 3? Answer: no. 14/314/3 maximizes that likelihood. The value 7 is motivated by unbiased estimation under repeated sampling, not by a larger likelihood for this dataset.
  3. Suppose the only possible Bernoulli parameters are 1/41/4 and 3/43/4, and one of two trials succeeds. Is the MLE 1/21/2? Answer: no; 1/21/2 is outside this parameter space. Both allowed values attain likelihood 3/163/16, so the argmax contains both.
  4. Two Gaussian observations are both 2, with unknown mean and strictly positive variance. Is (2,0)(2,0) a valid MLE? Answer: no. The likelihood is unbounded as the variance approaches zero; zero itself is excluded.

What large samples can justify in a concrete model

For Bernoulli sampling, p^\widehat p is simply the sample mean, so its unbiasedness and variance p(1−p)/np(1-p)/n follow directly. The law of large numbers proves consistency. For a fixed 0<p<10<p<1, the central limit theorem gives n(p^−p)⇒N(0,p(1−p))\sqrt n(\widehat p-p)\Rightarrow\mathcal N(0,p(1-p)). At p=0p=0 or 1 the estimate is deterministic and this nondegenerate normal picture does not apply. Deriving a result for the chosen model is more informative than attaching a blanket “asymptotically optimal” label.

Maximum likelihood leads naturally to likelihood-ratio inference, uncertainty estimates and model checking. MAP adds a specified prior; posterior prediction retains parameter uncertainty instead of replacing it with one fitted point. Choosing among these requires deciding what output is needed: a point, an interval, a comparison, or a prediction.

Make a prediction, then check

Both Gaussian observations equal 2; the mean is unknown and variance must be strictly positive. What is the maximum likelihood result?

Choose one answer

Learning objectives

  • Distinguish a likelihood function, an estimator, a realized estimate, and its numerical implementation.
  • Derive Bernoulli endpoint and Gaussian mean/variance estimates, explaining the n denominator, bias and nonexistence on degenerate data.
  • Identify absent, nonunique and local maxima and state concrete sufficient conditions for finite-candidate consistency.

Prerequisites & connections

Explore related knowledge →

References

  1. Statistics for Applications — Lecture 2: Maximum Likelihood Estimators
    Dmitry Panchenko; MIT OpenCourseWare · 2006
  2. Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
    Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020
  3. STATS 200 — Lecture 14: Consistency and Asymptotic Normality of the MLE
    Zhou Fan; Stanford University · 2016

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex multi-agent technical check: primary-source verification, derivation and numerical assertions, bilingual comparison, and review by another agent or the parent; no independent human peer review.

  • Compared MIT Gaussian, Bernoulli and Uniform examples; re-derived scores, boundaries, profiled variance derivatives and the n−1 bias correction, explicitly restricting the nondegenerate Gaussian expectation to n≥2.
  • Verified MLE optimality, unbiasedness and sampling variance over every binary sequence for n=1…7 and five exact probabilities; compared rational Gaussian fits to direct joint likelihoods; independently integrated the two-observation Gaussian sampling density to confirm expected variance MLE 1/2.
  • Checked non-identifiability, grid ties, empty data and zero-scatter failures; proved consistency separately for a finite parameter set rather than treating classroom simplifications as universal guarantees. Compared both languages paragraph by paragraph.
  • A second Codex agent independently reviewed support and existence, finite-candidate consistency conditions, grid ties and source passages, and reran all seven estimation tests.
  • The parent executed all 30 new checks and all 55 combined probability/inference tests; bilingual code, display equations, six main anchors, citations and four answered exercises were additionally compared.

Source locations checked:

  • Statistics for Applications — Lecture 2: Maximum Likelihood Estimators · Lecture 2, PDF pp. 5–9 (printed 11–15): MLE as an attained likelihood maximum; Bernoulli score and endpoint values; Gaussian joint mean/variance estimates; Uniform parameter-dependent support; included versus excluded endpoint density versions. Previously read during likelihood review, re-used for this derivation.
  • Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft) · 2024-01-15 draft, sections 8.3.1–8.3.3 (PDF pp. 272–277) and 9.2.1–9.2.2 (PDF pp. 300–305): likelihood optimization, Gaussian least-squares and n-denominator variance, numerical fitting and overfitting. The article explicitly adds full-existence/rank/regularity qualifications rather than importing blanket uniqueness or asymptotic claims.
  • STATS 200 — Lecture 14: Consistency and Asymptotic Normality of the MLE · Lecture 14, PDF pp. 1–4: definition of consistency and asymptotic normality, Theorem 14.1 including its footnote about additional omitted technical conditions, and pointwise-LLN plus expected-log-likelihood proof sketch. The article provides its own finite-candidate sufficient-condition argument and does not infer moment convergence from convergence in distribution. Author and Autumn 2016 offering verified on the course lectures page.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.