Maximum a posteriori estimation
最大后验估计
Distinguish posterior modes from means and predictions, handle Beta boundaries, and track coordinate and regularization scales.
map-estimationA peak is one way to summarize uncertainty
Three successes in four independent Bernoulli trials give MLE . Suppose you also choose a Beta(2,2) prior for the success probability, favoring central probabilities over extreme ones. After the observations, the posterior is Beta(5,3). Its highest density is at , while its mean is . Which number should a system return? They answer different questions.
Maximum a posteriori estimation, or MAP, chooses a posterior mode. For a continuous parameter this means a peak of a specified density, not the parameter point with the largest positive probability: every single point can have probability zero. For discrete parameters, MAP instead maximizes posterior probability mass. Review likelihood and Beta distributions before interpreting the peak as a decision.
Keep both the prior and its coordinate system visible
Assume a proper posterior with density relative to a stated parameter measure. Its normalizing constant must be finite and positive. Since that constant is independent of ,
This optimizes likelihood and prior together; it does not replace the likelihood with a probability distribution over parameters. The maximum may be absent or nonunique. A density version and its boundary convention matter to pointwise optimization. MML, Sections 8.3.2 and 9.2.3 derives the log-posterior objective.
For successes in independent Bernoulli trials with a Beta() prior, , write the posterior shapes as and . On ,
If both and , the second derivative is negative, giving the unique interior mode
The subtraction of one comes from the density exponents. It is not a reason to allow negative “observation counts.” The Beta posterior and interior-mode calculation are given in UBC, MAP Estimation, slides 19–20. For the opening case, gives and . Neither expression should be substituted for the other.
Outside the interior case, inspect the density rather than applying the fraction blindly. If , it is constant and every interior point is a mode. If , its finite supremum is at the limit ; if , it is at . Extending the density to the closed interval by those finite limits yields an attained boundary mode. If a shape is below one, the density diverges toward its corresponding endpoint. If both are below one, it diverges at both ends; the stationary point from the same algebra is a minimum. On the open interval these divergent cases have no attained maximum. The distribution remains proper and has zero point mass at either endpoint.
A Gaussian prior gives a familiar penalty, with a precise scale. Let independent observations satisfy with known , and let with fixed . Ignoring constants independent of ,
The Hessian is , so this scalar problem has one global minimizer, even with no data. MML, equation 9.28 gives the corresponding Gaussian-prior penalty for linear regression. For , multiplying the whole objective by leaves its minimizer unchanged:
Thus the same fixed prior requires a different coefficient when a summed loss becomes an averaged loss. With known noise variance, doubling the sample size halves this if the prior is unchanged. Keeping the averaged-loss penalty fixed instead corresponds to changing the prior scale. If noise or prior scales are themselves estimated, their normalizing terms depend on those parameters and cannot be discarded as constants.
Report a boundary case instead of inventing a point
The complete Python program uses exact rational inputs. beta_mode_report classifies the posterior on the open interval. finite-boundary reports a limit location; unbounded-boundary reports where the density diverges. Neither label claims an attained interior maximum. flat returns no preferred point. The Gaussian function accepts a general prior mean and returns the posterior mode and variance; its posterior mean equals its mode in this particular Gaussian model.
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 beta_posterior(h,n,a,b):
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")
a,b = exact(a),exact(b)
if a <= 0 or b <= 0:
raise ValueError("positive prior shapes required")
return a+h,b+n-h
def beta_mode_report(a,b):
a,b = exact(a),exact(b)
if a <= 0 or b <= 0:
raise ValueError("positive posterior shapes required")
if a > 1 and b > 1:
return "interior",((a-1)/(a+b-2),)
if a == b == 1:
return "flat",() # Every interior point is a maximizer.
divergent = tuple(v for v,shape in [(F(0),a),(F(1),b)] if shape < 1)
if divergent:
return "unbounded-boundary",divergent
return "finite-boundary",(F(0) if a == 1 else F(1),)
def gaussian_location_map(data,noise_variance,prior_variance,prior_mean=0):
x = [exact(v) for v in data]
v,t,m0 = map(exact,(noise_variance,prior_variance,prior_mean))
if v <= 0 or t <= 0:
raise ValueError("positive known noise and prior variances required")
precision = F(len(x))/v+1/t
location = (sum(x)/v+m0/t)/precision
return location,1/precision
a,b = beta_posterior(3,4,2,2)
assert (a,b) == (5,3)
assert beta_mode_report(a,b) == ("interior",(F(2,3),))
assert a/(a+b) == F(5,8)
assert beta_mode_report(1,1) == ("flat",())
assert beta_mode_report(1,4) == ("finite-boundary",(F(0),))
assert beta_mode_report(F(1,2),F(1,2)) == ("unbounded-boundary",(F(0),F(1)))
assert gaussian_location_map([2,4],1,1) == (2,F(1,3))
assert gaussian_location_map([],1,4,3) == (3,4)
The Beta calculations use constant rational arithmetic and storage after counts are supplied. The Gaussian calculation uses arithmetic and storage as written. Fraction bit costs depend on the inputs, so this is a small reproducible example rather than a large-scale optimizer. No tolerance decides whether a shape equals one: the classification uses exact fractions. For floating-point numerical optimization, boundary handling and tolerances need a separately stated policy.
For observations , known noise variance 1 and prior , the MAP is 2, compared with MLE 3. The posterior variance is . With ten genuinely independent observations having the same sample mean 3, the same prior gives MAP , closer to 3. Merely duplicating stored records does not create those independent observations.
A change of coordinates can move a density peak
Use log-odds , a smooth one-to-one map from to . Its inverse derivative is . The posterior density on the new coordinate is therefore
Maximizing it corresponds to , not the original -density mode . For Beta(5,3), the new mode is at , corresponding to ; simply transforming the old mode gives . The probability distribution is unchanged, but density height is measured per unit of a different coordinate. Its agreement with the Beta mean in this example is not a general identity between MAP and posterior means.
If log-odds are used only as an optimizer’s internal coordinates while maximizing the original density on , compose that original objective with the inverse map without a Jacobian. Including the Jacobian instead asks for a mode of the density on . Stan’s optimization documentation explicitly distinguishes these two targets. An affine change with a constant Jacobian preserves corresponding modes; general nonlinear changes need not.
MAP also discards posterior spread. For the opening posterior, the probability of one future success is . For two future trials independent given , the probability both succeed is , not the MAP substitution and not the squared-mean substitution . Integrating a shared uncertain parameter creates dependence between future outcomes. A point estimate cannot generally retain that information.
Prior choice is part of the model, not an automatic improvement certificate. A prior assigning zero density throughout the true region can exclude it from the posterior, and a poorly chosen scale can distort predictions. Reusing observations to choose a prior and then treating it as independent prior information can count evidence twice. Record how hyperparameters were chosen and evaluate predictions with data appropriate to the intended use.
Find the target before finding its maximum
- After three successes in four trials with Beta(2,2) prior, compare MLE, MAP in coordinates, and posterior mean. Answer: , , and . They maximize different objectives or compute a different summary.
- Can the formula find the mode of Beta()? Answer: it returns , an interior minimum. The density diverges at both endpoint limits and has no attained maximum on .
- For , , what coefficient belongs in ? Answer: , giving MAP 2. Using coefficient 1 with the averaged loss would encode a different prior and give .
- Does transforming the MAP to log-odds find the mode of the transformed Beta(5,3) density? Answer: no. It gives ; including the density Jacobian gives mode instead.
Use a point only when a point answers the question
For a discrete parameter and zero-one decision loss, selecting the most probable value minimizes posterior expected loss. For a continuous parameter under squared-error loss, the minimizing point is the posterior mean when the required moments exist; a density peak has no universal decision-theoretic priority. Expanding posterior squared error as proves the mean claim. These distinctions explain why a MAP fit and a Bayesian predictive distribution can serve different tasks.
Gaussian priors connect MAP to quadratic regularization; Laplace priors produce absolute-value penalties through the negative log density. A penalty acquires a probabilistic interpretation only with its parameter domain, scale, normalization and observation model specified. Continue with posterior prediction and Bayesian decision theory when uncertainty affects the decision, rather than assuming that the highest peak is all the posterior has to say.
Make a prediction, then check
The posterior is Beta(5,3), with density mode 2/3 in p. Which p corresponds to the density mode after changing to logit coordinates?
Learning objectives
- Derive the MAP objective from likelihood and prior, separating continuous density modes from discrete mass maximization.
- Classify interior, flat, finite-boundary and divergent-boundary Beta posteriors without misusing the interior-mode formula.
- Derive λ=σ²/(nτ²) for an averaged loss and use a logit transform to explain MAP coordinate dependence and its difference from prediction.
Prerequisites & connections
- Maximum likelihood estimation
- Beta and Dirichlet distributions
- Likelihood
- Derivatives and local approximation
References
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020 - CPSC 440/540 — MAP Estimation (2022W2 course materials)
University of British Columbia CPSC 440/540 teaching materials · 2023 - Stan Reference Manual — Optimization (version 2.39)
Stan Development Team
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 the inspected MML, UBC and Stan passages; re-derived Beta mode classification, the Gaussian posterior, regularization scaling and the inverse logit Jacobian.
- Independently integrated the Beta(5,3) polynomial for normalization, mean 5/8 and two-success probability 5/12; checked transformed density and finite differences to verify that the logit mode is not the transformed original MAP.
- Checked Gaussian MAP locations and variances through exact completed-square differences, including loss averaging, empty samples, shape boundaries and invalid parameters; compared both languages and all four answers.
- Cross-review noted that a negative second derivative alone does not ensure an interior mode: Beta(1,4) is a counterexample. Chinese wording now combines A,B>1 with endpoint behavior; coordinate transforms and loss scales were separately checked.
- 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:
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft) · 2024-01-15 draft, sections 6.6.1 (PDF pp. 214–215), 8.3.2 (PDF pp. 274–275), and 9.2.3 (PDF pp. 306–307), especially equation 9.28: Beta conjugate exponents, posterior mode objective and Gaussian-prior quadratic penalty. The article derives its scalar Gaussian case and the average-loss coefficient including n.
- CPSC 440/540 — MAP Estimation (2022W2 course materials) · PDF slides 12–20: discrete prior example; probability mass versus continuous density; Beta posterior shapes; interior-mode restrictions; Beta(2,2) MAP smoothing. The article derives the omitted boundary classifications and does not repeat vague asymptotic or overfitting guarantees. Course provenance checked at https://www.cs.ubc.ca/~dsuth/440/22w2/.
- Stan Reference Manual — Optimization (version 2.39) · Stan Reference Manual version 2.39, General configuration: optimizing with versus without the log absolute inverse-transform Jacobian finds modes of different coordinate densities. Read the actual official section; supplementary Program Blocks transformation discussion had also been inspected in the preceding likelihood review.
Related topics