A coin lands heads three times in three flips. Maximum likelihood (P1.D10) says the heads probability is , so tails is impossible. Would you bet your savings that the next flip is heads? Probably not. You know something the three flips do not say: coins that come out of a pocket are nearly fair, and three flips is very little evidence.
That outside knowledge has a place in the mathematics. It is the prior from Bayes’ theorem (P1.D6). Maximum likelihood asks which parameters make the data most probable and ignores everything else. MAP estimation asks which parameters are most probable after the data and the prior are both taken into account. This lesson shows that the answer for the coin is a tidy formula, that the prior is the same as a few imagined flips, and that the most common trick against overfitting in machine learning, penalizing large weights, is a prior in disguise. P1.D6 and P1.D10 each promised this lesson, and both promises are kept here.
Bayes’ theorem for parameters
P1.D6 used Bayes’ theorem for hypotheses such as “this patient is sick”. A hypothesis can also be a value of a model’s parameter , and the evidence the data. The three parts keep their names:
The prior says which parameter values were plausible before the data. The likelihood is the function of P1.D10. The posterior is what you believe after. The evidence is a single number. It has no in it, because was integrated out, so it only rescales the posterior until its area is . When you only want to compare parameter values, it can be ignored:
A small example. For heads in flips the likelihood is . Suppose the prior is flat, on . Then the evidence is , and the posterior is , which has area . Suppose the prior instead is , which prefers biases near . The product is , the evidence is , and the posterior is . The two priors give different evidence, but only the shape of likelihood times prior decides where the peak is, and with the second prior it is at , not at . The next sections explain why.
From maximum likelihood to MAP
The MAP estimate (maximum a posteriori) is the parameter value at the highest point of the posterior:
Dividing by the evidence changes no ratio between parameter values, so it cannot move the maximum. Taking the log is allowed for the same reason as in P1.D10 (the log is increasing). Using :
So MAP is maximum likelihood with an extra term, the log prior. In loss language, is a penalty added to the negative log-likelihood. A parameter value that the prior finds implausible gets a big penalty. A flat prior has equal to a constant, which adds nothing to the argmax, so maximum likelihood is MAP with a flat prior. For i.i.d. examples the recipe of P1.D10 is unchanged: write , add , and maximize.
| Maximum likelihood | MAP | |
|---|---|---|
| Maximizes | ||
| Equals the posterior’s highest point when | the prior is flat | always |
| Needs | a model of the data | a model of the data and a prior |
| Small data | can give or , or a wild fit | pulled toward the prior |
| Much data | the data decide | about the same as maximum likelihood |
Go deeper Flat depends on how the parameter is written
“Flat” means equal density per unit of the parameter, so it depends on the parameter chosen. Write the coin’s bias as and take a flat prior on . Rewrite the same coin by its log-odds . The prior on is then not flat: its density is , which is at and at . A flat prior on would be a different belief about the coin.
Maximum likelihood does not care: the MLE of is the log-odds of the MLE of , because the log-odds is a one-to-one function of . The MAP does care, because a density changes shape when the variable is changed. The pitfalls section works one example. The lesson is that a prior is only fully described together with the parameter it is placed on, and that a MAP value should be read with that parametrization named.
A coin with a Beta prior
For a coin, is a number between and , so the prior must be a distribution on . A convenient family is the Beta distribution with two positive parameters. Its density is proportional to
For this is flat. For it is a gentle hill centred on . For it is a narrow hill. For it is a narrow hill near : a strong belief that the coin rarely lands heads. This lesson uses , which keeps every density finite. Why this family? Look at the likelihood, for heads in flips. It has the same form, powers of and . Multiplying prior by likelihood just adds the exponents:
and that is the density of . The posterior is again a Beta: updating only adds the counts. A prior with this property is called a conjugate prior for that likelihood. Three consequences follow, all for .
The MAP. The highest point of is at (set the derivative of the log to zero, as in P1.D10). With and :
The posterior mean of is , which is .
Imagined flips. Compare with the MLE . The MAP is the same fraction with imaginary heads and imaginary tails added to the real counts. These are called pseudo-counts. For the MAP, the prior acts like imagined heads and imagined tails seen before the experiment starts. For the posterior mean it acts like heads and tails instead, which is why the mean has in its denominator.
For heads in flips:
| prior | posterior | MAP | mean |
|---|---|---|---|
With the flat prior the MAP is , the same as the MLE, and the mean is . With the MAP is and the mean is .
The prior is one imaginary head and one imaginary tail: . This is add-one smoothing, also called Laplace smoothing. P1.D10 pointed to it with the same numbers, and P1.D6 gave the version for the mean: from a flat prior, heads in flips give , Laplace’s rule of succession. The two values have different meanings but the same formula, : the posterior mean under the flat , and the posterior mode under . For heads in flips both give , the number from P1.D10.
Now try it. The three curves share one vertical axis, because the likelihood is drawn rescaled to have area (the rescaling only changes its height, not its shape, and it is the posterior you would get from a flat prior).
Things to try:
- Flat prior, 3 of 3. The posterior has the shape of the likelihood. The MAP equals the MLE and sits at the edge, , while the mean is . A flat prior repairs nothing for the MAP.
- Weak prior, 3 of 3. Choose : the MAP moves to , off the edge.
- Strong fair prior, 8 of 10. The data say but the MAP is , near the prior’s . Move to with heads: . The table below goes on to flips and .
- Strong wrong prior. believes the coin is mostly tails (mode ). After heads in flips the MAP is and after in it is : the data pull it far, but slowly.
- Edges. Set with : the MAP is whatever is, and the status line warns. A flat prior and no data gives a flat posterior with no highest point, so the MAP is undefined.
The prior fades as data arrive
The MAP can be rewritten as a weighted average. Write for the number of imagined flips and for the prior’s highest point (its mode). Then
The data’s estimate has weight and the prior’s mode has weight . The prior’s share is , which shrinks like . Here is the strong fair prior (, ) against data that are heads:
| flips | heads | MLE | MAP | prior’s share of the weight |
|---|---|---|---|---|
This is the general pattern. With little data the prior decides, with lots of data the data decide, and the MAP and the MLE converge. The prior is not wrong to be strong, it just needs enough evidence to be overruled. A prior that gives zero density to the truth can never be overruled, which is why priors usually leave every plausible value possible, even if unlikely.
A point, and a picture
The MAP is one number. The posterior is the whole distribution, and it also says how sure you are. After heads and tail from a flat prior, the posterior is :
- the MAP (mode) is , equal to the MLE;
- the mean is , and the median is ;
- the standard deviation is , and a central range is to ;
- the probability that the coin favours heads () is .
The mode, median and mean differ because the posterior is skewed (it leans against the edge at ). The mode is the single most probable value, the mean is the best guess to minimize squared error, and the posterior mean is also what you should use to predict the next flip: with a posterior, the probability of heads on the next flip is exactly . MAP throws away the spread, which is why a lot of Bayesian machine learning keeps the whole posterior when it can afford it, and why MAP is the cheap, common point summary when it cannot.
A Gaussian mean with a Gaussian prior
The same idea works for continuous parameters. Suppose measurements come from a Gaussian with a known spread and an unknown mean (P1.D3), and the prior says : a best guess , with uncertainty . The log posterior, up to constants, is
Set the derivative with respect to to zero: . Solving for gives
This is a weighted average of the sample mean and the prior mean . The weights are precisions: precision is (variance: P1.D4), so a sharper source gets more weight. The data’s precision is (it grows with ) and the prior’s is . The posterior is again Gaussian, with precision equal to the sum , so it is always narrower than both sources. A Gaussian is symmetric, so its mean and mode coincide and the MAP is also the posterior mean.
Take , a prior , and :
| data precision | prior’s share | MAP of | sd | |
|---|---|---|---|---|
The MLE is always , and the MAP starts at and creeps toward . The pull toward the prior mean is called shrinkage: estimates are shrunk toward a central value. A wider prior (large ) shrinks less. As the prior becomes flat and the MAP tends to , the maximum-likelihood answer.
Priors on weights are regularizers
Here is the connection that makes this lesson matter for machine learning. Take a linear model with Gaussian noise: , , with a Gaussian prior on each weight, , independent (a prior centred on that says “weights are probably small”; as a vector, , the multivariate Gaussian of P1.D7 with no correlation between weights). From P1.D10 the negative log-likelihood is plus a constant. The negative log prior is
Add the two and multiply everything by the positive number . The MAP weights minimize
with
This is ridge regression (L2 regularization): squared error plus times the squared length of the weights. A Gaussian prior is an L2 penalty. The correspondence tells you what means: a larger noise level means the data are less trustworthy, so shrink more, and a narrower prior (small ) also shrinks more. If the loss is the average squared error , divide the whole expression by : the penalty is then , which again shows the prior fading as grows. The closed form is , which exists for every even when has no inverse (P1.B12 and P3.A6 explain why adding fixes that).
Weight decay. In gradient descent (P1.F3) on the loss plus , the penalty’s gradient is , so each step first multiplies the weights by and then takes the usual step. The weights decay toward unless the data pull them away. This is weight decay. Adding the penalty to the loss, an L2 penalty, is a MAP objective with a Gaussian prior (P4.17). With plain gradient descent the two views give the same update. With adaptive optimizers such as Adam, adding the penalty to the loss and decaying the weights directly are no longer the same thing, which is why a separate “decoupled” weight decay (AdamW) exists, and it no longer matches the Gaussian-prior MAP exactly.
A Laplace prior gives an L1 penalty. Suppose each weight instead has a Laplace prior with scale , density , a sharp peak at with heavier tails than a Gaussian. Then , and the same steps give
with
This is lasso (L1 regularization). It behaves differently from L2, and the next widget shows how. (The Laplace distribution and Laplace’s add-one smoothing are different things that share a name.)
One weight: L2 shrinks, L1 can switch off
Look at a single weight. Measured in units of the data’s own uncertainty, the data alone give the cost , lowest at the maximum-likelihood weight . The prior adds its penalty, and the MAP is the lowest point of the sum. Here , so the penalty strength in the cost (L2) or (L1) relates to the earlier formulas like this: for L2, , the same as before; for L1, , half of . Both cases have a closed form:
- Gaussian prior (L2): . It is a fixed fraction of . For and it is . It reaches only if .
- Laplace prior (L1): . It subtracts a fixed amount and stops at exactly . For and it is , and for it is . This is called soft thresholding.
Try the Laplace prior with the data’s best weight at . A moderate prior makes the MAP exactly , and the Gaussian prior with the same strength only halves it. Then raise the best weight to and see that L1 keeps most of it. The reason is the shape of the penalty at : the V has a corner, with slope on each side, so a weight stays at as long as the data’s pull is weaker than that slope. The bowl is flat at , so any pull, however small, moves the weight a little. With many weights, an L1 penalty therefore switches off the weak ones and leaves a sparse solution (many weights exactly ). P3.A6 shows why this gives feature selection and draws the geometry.
Practical notes on weights. The bias term is usually not penalized, which corresponds to a flat prior on it. A single for all weights is a statement that every weight has the same typical size, which is only sensible when the features are on similar scales (P3.A11 covers scaling). And (or ) is a hyperparameter you choose, usually with a validation set (P3.A4, P4.23), not something that falls out of the data.
Choosing a prior
Where does a prior come from? There is no single answer, and the choices are modelling decisions:
- Informative priors put real knowledge in: a physical constant, an earlier study, or the knowledge that coins are nearly fair. If the knowledge is right, the estimate improves a lot for small data.
- Weak priors just rule out absurd values, such as for a coin or for a weight. They stabilize the fit and give way to the data quickly.
- Flat priors try to say nothing, but as the Go-deeper box showed, “flat” depends on the parametrization, and a flat prior on a weight with an unbounded range cannot even be a proper distribution (it has no area to normalize).
- Conjugate priors are chosen for convenience: the posterior has the same form as the prior, as with Beta for a coin, Gaussian for a Gaussian mean, and Dirichlet for category counts. They make the algebra, and the imagined-count reading, work. Many models have no conjugate prior, and MAP is then found by numerical optimization (P1.F3).
- Regularization strength as a prior is often tuned on held-out data instead of being justified by belief. Both views are useful: you can read as a belief () or as a knob.
Go deeper Counts for many categories: add-k smoothing and the Dirichlet prior
The coin’s two outcomes generalize to categories, such as the next word out of a vocabulary of size (P6.2). The conjugate prior of the categorical distribution is the Dirichlet with one pseudo-count parameter per category. After seeing category exactly times in draws with all :
- the posterior mean for category is ;
- the MAP, for , is .
So add-one smoothing is the posterior mean for , and also the MAP for , the same pair as for the coin (). Add- smoothing uses with a smaller such as . With and , a category never seen gets and not . This matters because a probability of makes the log-loss infinite, as P1.D10 showed. Better smoothing methods exist for language models (P6.2). Label smoothing (P4.17) also softens targets, but it changes the training targets and is not derived from a prior on the parameters.
What can go wrong
Each pitfall has a condition:
- A strong wrong prior. A prior that says the coin is mostly tails, , needs about flips at heads before the MAP even reaches (the formula gives exactly at ). The prior’s pseudo-counts are real weight. Check the prior against the data you have, and prefer weaker priors when unsure.
- MAP can still sit at an edge. adds no imaginary heads. After heads in any number of flips the MAP is . The prior must give a little room on both sides, as does.
- MAP is not invariant to reparametrization. The posterior has its mode at . If the same posterior is written as a density over the log-odds , its highest point is at , which is . In general the mode in log-odds sits at , which is the posterior mean, so the two parametrizations disagree about where the MAP is. The MLE does not have this problem. A MAP is therefore always a MAP in some parametrization, and two people who parametrize differently can report different values.
- MAP is not the whole posterior. It ignores spread and skew. A very tall narrow spike can be the mode while holding almost no probability, which can mislead in high dimension.
- The prior can look like cheating. Choosing a prior after seeing the data, to get a nicer answer, is a way to fool yourself. Fix the prior, or the way is chosen, before looking at the test set (P3.A4).
- Regularization has a price. A stronger prior lowers variance and raises bias (P3.A5). An L2 penalty also shrinks useful weights, so too large a underfits.
Go deeper Keeping the whole posterior
The full Bayesian answer does not pick a single . It averages predictions over the posterior: . For the coin this gives the posterior mean as the probability of heads on the next flip, and its spread says how unsure the estimate is. For a neural network the integral over millions of weights cannot be done exactly, so practical methods approximate it, and the MAP weights (the weights minimizing the loss plus weight decay) are the cheapest summary. This course mentions the idea but does not teach Bayesian neural networks. Confidence intervals and the frequentist alternative are in P1.D13.
Where this shows up in machine learning
- Regularized regression. Ridge and lasso are the formulas above (P3.A6). The best is chosen by validation (P3.A4).
- Weight decay in deep learning. Many large networks are trained with some form of it (P4.17). The Gaussian-prior reading explains why each weight is shrunk toward .
- Smoothing counts. Naive Bayes and n-gram language models add pseudo-counts so unseen events keep a small probability (P3.B2, P6.2).
- Language model pretraining. The loss of P1.D10 is a negative log-likelihood. Adding an L2 penalty to it gives a MAP objective, though the prior is rarely discussed (decoupled weight decay, AdamW, matches that only for plain gradient descent).
- Bayesian uncertainty. The full posterior over weights gives error bars on predictions, at a high cost for big models.
Intuition
MAP is a tug-of-war. The data pull the estimate toward what they say, for a coin or for a mean. The prior pulls toward what you believed before. Each side pulls with a strength equal to how much information it carries: real flips against imagined ones, or precision against . The knot ends at the weighted average. With more data the data’s team gets bigger and the knot moves toward it.
The analogy breaks in two places. It holds exactly for the coin and the Gaussian, but for other priors the pull is not a fixed weighted average (an L1 prior removes a fixed amount, and can stop at ). And a tug-of-war has a winner, while MAP is a compromise: with a wrong prior and few data it can be worse than the data alone.
Math
Posterior. and , so .
Beta–Bernoulli. Prior , data of , posterior . Mode for (the posterior is flat when ), mean , variance . Weighted form: with .
Gaussian. With and data : posterior precision and mean .
Weights. . Gaussian prior: in , solution . Laplace prior: in . One weight, in units of the data’s own uncertainty (): cost (L2) or (L1), where is the maximum-likelihood weight. L2 gives with , the same as above. L1 gives with , which is half of .
Code
A MAP estimate by maximizing the log posterior on a grid, then by the closed form, and ridge regression with NumPy.
import numpy as np
# coin: 3 heads in 3 flips, Beta(2, 2) prior
theta = np.linspace(0.0005, 0.9995, 1999)
log_post = 3 * np.log(theta) + (2 - 1) * np.log(theta) + (2 - 1) * np.log(1 - theta)
print(theta[np.argmax(log_post)], (2 + 3 - 1) / (2 + 2 + 3 - 2)) # 0.8 and 0.8
# ridge: minimize ||y - Xw||^2 + lam ||w||^2 with lam = sigma^2 / tau^2
X = np.random.default_rng(0).normal(size=(20, 3))
y = X @ np.array([1.0, 0.0, -2.0]) + np.random.default_rng(1).normal(size=20)
lam = 1.0
w_map = np.linalg.solve(X.T @ X + lam * np.eye(3), X.T @ y)In PyTorch the same L2 penalty is the weight_decay argument of an optimizer such as torch.optim.SGD.
Try it: MAP in code
The first cell finds the MAP for several coins by maximizing the log posterior on a fine grid, compares it with the formula, and prints how the prior fades. The second cell fits a regression with two nearly identical features: the maximum-likelihood weights are large and of opposite signs, and the MAP weights are similar in size and both positive. It checks the ridge formula against gradient descent on the negative log posterior, varies , and compares L2 with L1 on one weight.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The first line of output shows the flat prior: the MAP by the formula is , the same as the MLE (the grid stops at its last point, , because the true peak is the edge). Next comes with . Strong priors give (, of ), (, of ) and (, of ). For the other four coins the grid MAP and the formula agree to four decimals. The second table shows the prior’s share falling from to while the MAP rises from to .
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The unpenalized fit is : with two nearly equal features, a large positive weight and a negative one almost cancel, and a small change in the data would change them a lot. The ridge fit is , and gradient descent on the negative log posterior reaches the same weights. As shrinks from to the weights shrink, and their length falls from to . In the last lines, L1 sets the weight to exactly while L2 halves it to .
Common mistakes
Check your understanding
A coin has a flat prior on its heads probability, and you see heads in flips. Which statement about the MAP estimate is correct?
A flat prior contributes a constant to , which does not move the argmax, so the MAP is . The value is the posterior mean, which is a different summary of the same posterior. A flat prior does not pull toward , and a MAP can be above or below the MLE depending on the prior. The posterior is not flat after data arrive, so it has a highest point; only the case of no data at all is undefined.
A coin gives heads in flips. With a prior, what is the MAP estimate?
The posterior is and its mode is . The value is the maximum-likelihood estimate and the MAP under a flat prior. The value is the posterior mean , not the mode. The value is the posterior mode for heads in flips, not for in .
You fit noise, with noise spread and a Gaussian prior on each weight, and minimize . Which gives the MAP estimate?
The negative log posterior is . Multiplying by gives the sum of squares plus . The ratio is upside down: a narrower prior must give a larger penalty. The other two do not follow from the algebra, which has variances and not standard deviations.
One weight has maximum-likelihood value . Which prior, with a strong enough penalty, makes the MAP weight exactly ?
The L1 penalty has a corner at , so the weight stays at whenever the data's pull is no bigger than the penalty's slope. The L2 penalty has zero slope at , so the weight becomes , which is smaller but not . A flat prior adds no penalty. The claim that no prior can reach is false: soft thresholding is exactly that.
Data: from measurements with . Prior: . What is the MAP estimate of ?
The data precision is and the prior precision is , so the weights are and : . The value is the answer for , with equal weights. The value is the maximum-likelihood estimate, which ignores the prior. The value is the answer for .
Exercises
- A coin has a prior and gives heads in flips. Find the posterior, the MAP, the posterior mean and the MLE.
Show answer
The posterior is . The MAP is , the mean is and the MLE is . The prior pulls the estimate toward . - After heads in flips, give the MLE, the MAP under , the MAP under and the posterior mean under .
Show answer
The MLE is . The MAP under is also (the flat prior changes nothing). The MAP under is , and so is the posterior mean under , . - How many real flips balance the imagined flips of a prior, so that the data and the prior have the same weight in the MAP?
Show answer
The prior counts as imagined flips, so real flips give equal weight. - Data have , and . The prior is . Find the MAP of .
Show answer
The data precision is and the prior precision is . Equal weights give . - A regression has noise spread and a prior on each weight. What penalty is it in ? What if the loss is instead the mean over examples?
Show answer
. For the average loss the penalty coefficient becomes . - A single weight has data-only value and penalty strength , in the cost (L2) or (L1). Give the L2 and the L1 answers.
Show answer
L2: . L1: . L1 removed a fixed amount, and L2 a fixed fraction. - Compute the standard deviation of the posterior from the P1.D6 exercise ( prior, heads, tail), and say what it tells you about the mean .
Show answer
. The coin’s bias is only known to about (one standard deviation), so a single number such as hides how uncertain the estimate is. - A prior meets data with heads. How many flips are needed for the MAP to reach ?
Show answer
Solve , so and (with heads). Check: . - An n-gram model has seen the current word times, and different words are possible next. Under add-one smoothing, what probability does a never-seen next word get?
Show answer
. Without smoothing it would be , with infinite loss. - Why is the bias term usually left out of the L2 penalty?
Show answer
Penalizing it would shrink the model’s baseline toward (for example, the average output), which has no reason to be small. Not penalizing it is the same as a flat prior on the bias. - Why does a Laplace prior give sparse solutions but a Gaussian prior does not?
Show answer
The negative log Laplace density has a corner at , with a slope of on each side, so a weight whose data pull is weaker than stays at exactly . The Gaussian’s has zero slope at , so every non-zero pull gives a non-zero weight. - The posterior has mode and mean . Which one do you use to predict the next flip, and why?
Show answer
The mean: the predictive probability of heads is the posterior mean , because it averages over the uncertain . The mode is the single most probable , not the best predictive probability.
Next: P1.D12 summarizes data without a model (mean, median, percentiles). P1.D13 asks how far results can be trusted when the data are a random sample, and P1.E1 to P1.E4 turn the negative log probabilities used here into information, entropy and cross-entropy. P3.A6 develops L1 and L2 regularization in practice, P4.17 puts weight decay in neural networks, and P6.2 smooths n-gram counts.