Maximum a Posteriori Estimation and Its Link to Weight Penalties
See how a prior on the weights turns into an L2 or L1 penalty, how to match the constants, and where the analogy stops.
Key takeaways
- The MAP estimate maximizes the log likelihood plus the log prior of the parameters.
- A zero-mean Gaussian prior corresponds to an L2 penalty, and a zero-mean Laplace prior to an L1 penalty.
- The matching penalty strength depends on the prior width, the noise level and whether your loss is summed or averaged.
- The influence of a fixed prior fades as the number of examples grows.
- MAP returns a single point that depends on how the model is parameterized, so it is not a full Bayesian analysis.
Maximum a posteriori (MAP) estimation picks the parameter values that are most probable after combining the data with a prior belief about the parameters. Take the negative logarithm and the result is a training loss plus a penalty. A Gaussian prior on the weights gives an L2 penalty, and a Laplace prior gives an L1 penalty.
This reading tells you what the penalty strength means: it is the balance between how noisy you think the data are and how small you think the weights should be.
Bayes' rule for parameters
Let D be the data and w the parameters. Bayes' rule combines two ingredients.
p(w | D) = p(D | w) p(w) / p(D)
p(D | w) likelihood: how probable the data are if w were true
p(w) prior: what you believe about w before seeing D
p(w | D) posterior: the updated belief The denominator p(D) does not depend on w, so it can be ignored when you only want the peak. Maximum likelihood maximizes p(D | w) alone. MAP maximizes the product.
w_MAP = argmin [ −ln p(D | w) − ln p(w) ]
data loss penalty A one-parameter example
You want the mean μ of a quantity whose measurements are Gaussian with known variance σ² = 4. Your prior for μ is Gaussian with mean 0 and variance τ² = 1. You collect n values with average x̄.
Setting the derivative of the negative log posterior to zero gives:
μ_MAP = (n x̄ / σ²) / (n / σ² + 1 / τ²)
= x̄ · n / (n + σ²/τ²) The estimate is the sample average multiplied by a factor below 1. With x̄ = 2:
| Examples n | Shrink factor n/(n + 4) | MAP estimate |
|---|---|---|
| 1 | 0.200 | 0.40 |
| 5 | 0.556 | 1.11 |
| 20 | 0.833 | 1.67 |
| 100 | 0.962 | 1.92 |
The ratio σ²/τ² = 4 behaves like four imaginary measurements at zero. With little data they carry real weight. With much data they hardly matter.
Gaussian prior gives L2
Now take linear regression with y = Xw + noise, where the noise is Gaussian with variance σ² and X has shape (n, d). Give every weight an independent Gaussian prior with mean 0 and variance τ².
−ln p(y | X, w) = ‖y − Xw‖² / (2σ²) + constant
−ln p(w) = ‖w‖² / (2τ²) + constant
multiply the sum by 2σ²:
‖y − Xw‖² + (σ²/τ²) ‖w‖² This is ridge regression with λ = σ²/τ². Noisier data, meaning larger σ², call for more shrinkage. A wider prior, meaning larger τ², calls for less. Ridge regression studies the consequences for the coefficients.
Laplace prior gives L1
A zero-mean Laplace prior with scale b has density exp(−|w|/b)/(2b). Its negative log is |w|/b plus a constant. With the same Gaussian noise, multiplying by 2σ² gives ‖y − Xw‖² + (2σ²/b) ‖w‖₁.
The absolute value has a kink at zero, which lets the optimum sit exactly there. In one dimension, minimizing ½(w − z)² + t|w| gives the soft threshold:
w = sign(z) · max(|z| − t, 0)
t = 0.5: z = 2.0 → 1.5 z = 0.3 → 0 The quadratic penalty would instead scale both values by the same factor and leave neither at zero. See why lasso produces exact zeros. Note the limit of the probabilistic story: the MAP estimate under a Laplace prior is sparse, but typical samples from the posterior are not exactly zero.
Getting the constants right
The mapping from τ to a number in your code depends on the loss convention. Suppose you minimize the mean negative log likelihood plus (λ/2)‖w‖². Dividing the negative log posterior by n shows:
(1/n) ∑ −ln p(yᵢ | xᵢ, w) + ‖w‖² / (2 n τ²)
so λ = 1 / (n τ²) For the same prior, doubling the data should halve λ in this convention. If you tune λ on a subset and then retrain on everything with a mean loss, the same λ corresponds to a tighter prior than before. With a summed loss, the penalty coefficient stays fixed.
Libraries differ further. Some define the strength as the inverse, often called C, so that larger means weaker. Read the objective written in the documentation.
Choices hidden in "a penalty on the weights"
A prior treats every weight alike only if you say so, and that usually requires preparation.
- Scale the features. A weight's natural size depends on the units of its input. Standardize using statistics from the training fold only.
- Leave the intercept out. Shrinking the bias term toward zero asserts that the average target is near zero, which you rarely believe.
- Group sensibly. Different layers or feature blocks can have different prior widths.
- Mind the optimizer. With plain gradient descent, an L2 term and weight decay can be made equivalent. With adaptive methods such as Adam they differ, as explained in weight decay and L2.
For neural networks, a Gaussian prior on individual weights is a weak description of what functions you expect. Treat the correspondence as a helpful interpretation and tune the strength empirically.
A short experiment
The code below solves the MAP problem for linear regression in closed form and checks that the gradient of the negative log posterior vanishes.
import numpy as np
rng = np.random.default_rng(0)
n, d, sigma, tau = 30, 5, 2.0, 1.0
X = rng.normal(size=(n, d)) # (30, 5)
w_true = rng.normal(scale=tau, size=d)
y = X @ w_true + rng.normal(scale=sigma, size=n)
lam = sigma**2 / tau**2
w_map = np.linalg.solve(X.T @ X + lam*np.eye(d), X.T @ y)
grad = X.T @ (X @ w_map - y)/sigma**2 + w_map/tau**2
print(np.abs(grad).max()) # essentially zero
w_ml = np.linalg.lstsq(X, y, rcond=None)[0]
print(np.linalg.norm(w_map), np.linalg.norm(w_ml)) The MAP weights have a smaller norm than the maximum likelihood weights. Whether they are closer to the truth on a given draw varies. Averaged over many draws from this exact model, the shrinkage helps.
The same idea outside linear regression
Nothing in the derivation needed a linear model. Swap in the Bernoulli likelihood and a Gaussian prior, and you get penalized logistic regression. The solution no longer has a closed form, but the objective stays convex, so iterative solvers find it reliably. The penalty also repairs a specific problem: when the two classes can be perfectly separated, maximum likelihood pushes the weights toward infinity, while any Gaussian prior keeps them finite.
Priors also apply to quantities other than weights. Add-one smoothing of word counts in a naive Bayes classifier is the MAP estimate of a categorical distribution under a Dirichlet prior with every parameter equal to 2. It stops an unseen word from receiving probability zero.
word counts for three words: 3, 1, 0 total 4
maximum likelihood: 0.75, 0.25, 0
add one to each (MAP): 4/7, 2/7, 1/7 A prior can also center somewhere other than zero. When you fine-tune a pretrained model, penalizing the squared distance from the pretrained weights corresponds to a Gaussian prior centered on them. It expresses the belief that good weights for the new task lie near the old ones.
MAP is not the whole posterior
MAP keeps only the highest point of the posterior density. It says nothing about how wide the peak is, so it gives no uncertainty by itself.
It also depends on the choice of variable. Take the Beta(8, 4) posterior for a probability p. Its density peaks at 7/10 = 0.7. Rewrite the same belief in terms of the log odds θ = ln(p/(1 − p)), and the peak in θ corresponds to p = 8/12, about 0.667. The beliefs are identical. The density gets rescaled by the change of variable, which moves its maximum.
Full Bayesian prediction averages over parameters instead of picking one. For linear models with Gaussian assumptions this is available in closed form, as in Bayesian linear regression. There the posterior mean happens to equal the MAP estimate. Elsewhere you may need variational inference or sampling.
Choosing the strength
You can set λ from real knowledge of σ and τ, but those are seldom known. The usual route is to try values on a logarithmic grid and pick by validation or cross-validation, then report the final score on a separate test set.
A Bayesian alternative, sometimes called empirical Bayes, chooses the prior width by maximizing the probability of the data with the weights integrated out. It uses all the training data, and it relies on the model assumptions being reasonable.
Common questions
Is every regularizer a prior?
No. A penalty can be written as a negative log prior when its negative exponential can be normalized into a distribution, but dropout, early stopping and data augmentation have no such exact reading in general. Some admit approximate interpretations under particular assumptions.
Does a stronger penalty always reduce test error?
No. Too little shrinkage leaves the fit at the mercy of noise, and too much pushes real effects toward zero. Test error usually falls and then rises as the strength grows, and where the bottom lies depends on the data. With plenty of examples relative to parameters, the curve may be nearly flat over a wide range.
What prior does maximum likelihood use?
Numerically it matches MAP with a constant prior. Over an unbounded range, such a prior cannot be normalized, and "flat" in one parameterization is not flat in another.