TExcelTAD
Home › Math for Machine Learning › MAP Estimation and Regularization

MAP Estimation and Regularization

Maximum likelihood trusts the data completely and overfits small samples. Adding a prior over the parameters and maximizing the posterior instead gives the maximum a posteriori (MAP) estimate. The log of a Gaussian prior is exactly an ℓ2\ell_2 penalty, and a Laplace prior gives ℓ1\ell_1: regularization is a prior in disguise.

From posterior to penalty

By Bayes' theorem p(θ∣D)∝p(D∣θ) p(θ)p(\boldsymbol{\theta} \mid \mathcal{D}) \propto p(\mathcal{D} \mid \boldsymbol{\theta})\,p(\boldsymbol{\theta}). Taking negative logs:

θMAP=arg⁡min⁡θ(−log⁡p(D∣θ)⏟data fit (NLL) − log⁡p(θ)⏟regularizer)\boldsymbol{\theta}_{\text{MAP}} = \arg\min_{\boldsymbol{\theta}} \Big(\underbrace{-\log p(\mathcal{D} \mid \boldsymbol{\theta})}_{\text{data fit (NLL)}}\ \underbrace{-\ \log p(\boldsymbol{\theta})}_{\text{regularizer}}\Big)

With a Gaussian prior θ∼N(0,b2I)\boldsymbol{\theta} \sim \mathcal{N}(\mathbf{0}, b^2 I), −log⁡p(θ)=12b2∥θ∥2+const-\log p(\boldsymbol{\theta}) = \frac{1}{2b^2}\lVert \boldsymbol{\theta} \rVert^2 + \text{const}. For linear regression with noise variance σ2\sigma^2:

θMAP=arg⁡min⁡θ12σ2∥y−Xθ∥2+12b2∥θ∥2=(XTX+λI)−1XTy,λ=σ2b2\boldsymbol{\theta}_{\text{MAP}} = \arg\min_{\boldsymbol{\theta}} \frac{1}{2\sigma^2}\lVert \mathbf{y} - X\boldsymbol{\theta} \rVert^2 + \frac{1}{2b^2}\lVert \boldsymbol{\theta} \rVert^2 = (X^TX + \lambda I)^{-1}X^T\mathbf{y}, \qquad \lambda = \frac{\sigma^2}{b^2}

This is ridge regression. A tight prior (small bb) means a large λ\lambda and strong shrinkage towards 0. With a Laplace prior p(θd)∝e−∣θd∣/bp(\theta_d) \propto e^{-\lvert\theta_d\rvert/b}, the penalty is 1b∥θ∥1\frac{1}{b}\lVert \boldsymbol{\theta} \rVert_1: the lasso, which produces sparse solutions (Norms).

Ridge fixes overfitting and singular systems

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
f_true = lambda x: np.sin(2 * x)
x_tr = rng.uniform(-2, 2, 15); y_tr = f_true(x_tr) + 0.2 * rng.normal(size=15)
x_te = rng.uniform(-2, 2, 1000); y_te = f_true(x_te) + 0.2 * rng.normal(size=1000)
Phi = lambda x: np.vander(x / 2, 15, increasing=True)          # degree-14 polynomial features
for lam in (0.0, 1e-6, 1e-3, 1e-1, 10.0):
    A = Phi(x_tr).T @ Phi(x_tr) + lam * np.eye(15)
    theta = np.linalg.lstsq(A, Phi(x_tr).T @ y_tr, rcond=None)[0]
    te = np.mean((Phi(x_te) @ theta - y_te) ** 2)
    print(f"lambda={lam:<6g}  |theta|={np.linalg.norm(theta):10.2f}  test MSE {te:.4f}")
lambda=0       |theta|=   4962.63  test MSE 45.0959
lambda=1e-06   |theta|=    128.90  test MSE 0.0999
lambda=0.001   |theta|=      6.12  test MSE 0.2528
lambda=0.1     |theta|=      2.57  test MSE 0.1708
lambda=10      |theta|=      0.26  test MSE 0.4845

Without regularization the degree-14 fit has huge coefficients and a terrible test error. A moderate λ\lambda shrinks the coefficients and generalizes well; too large a λ\lambda underfits. Adding λI\lambda I also makes XTX+λIX^TX + \lambda I positive definite and well conditioned, so the system always has a unique solution.

Weight decay

In gradient descent, the ℓ2\ell_2 term adds λθ\lambda\boldsymbol{\theta} to the gradient, so each step shrinks the weights by a factor (1−γλ)(1 - \gamma\lambda) before the data step: weight decay. (For adaptive optimizers like Adam the two are not identical, which is the point of AdamW: Adam and AdamW.)

MAP versus the full posterior

MAP returns a single point, the mode of the posterior. It ignores the posterior's spread, so it says nothing about uncertainty, and the mode can be atypical in high dimensions. The full Bayesian approach keeps the whole posterior and averages predictions over it (Bayesian Linear Regression).

python · try it yourself
import numpy as np

# coin flips: 3 heads in 3 tosses. ML says mu = 1; a Beta(2, 2) prior says otherwise
h, t = 3, 0
a, b = 2, 2
mu_ml = h / (h + t)
mu_map = (h + a - 1) / (h + t + a + b - 2)          # mode of Beta(h + a, t + b)
mu_mean = (h + a) / (h + t + a + b)                 # posterior mean
print(f"ML {mu_ml:.3f}   MAP {mu_map:.3f}   posterior mean {mu_mean:.3f}")
ML 1.000   MAP 0.800   posterior mean 0.714

In software

  • Ridge(alpha=λ), Lasso(alpha=...), LogisticRegression(C=1/λ) in scikit-learn (Regularization).
  • torch.optim.SGD(..., weight_decay=λ) and torch.optim.AdamW.
  • Dropout and early stopping are other regularizers without such a simple prior interpretation (Regularization in Deep Learning).

Exercises

Exercise 1: Prior strength

Noise standard deviation σ=2\sigma = 2 and prior standard deviation b=0.5b = 0.5. What is the equivalent ridge λ\lambda?

Answer
Solution

λ=σ2/b2=4/0.25=16\lambda = \sigma^2/b^2 = 4/0.25 = 16. Noisy data and a confident prior both increase the regularization.

Exercise 2: One-dimensional ridge

For one feature with ∑xn2=10\sum x_n^2 = 10 and ∑xnyn=20\sum x_ny_n = 20, compare θML\theta_{\text{ML}} and θMAP\theta_{\text{MAP}} with λ=10\lambda = 10.

Answer

θML=2\theta_{\text{ML}} = 2, θMAP=1\theta_{\text{MAP}} = 1.

Solution

θ=∑xnyn∑xn2+λ\theta = \frac{\sum x_ny_n}{\sum x_n^2 + \lambda}: 20/10=220/10 = 2 without, 20/20=120/20 = 1 with regularization.

Exercise 3: Weight decay factor (code)

With learning rate 0.10.1 and λ=0.01\lambda = 0.01, by what factor does pure weight decay shrink a weight after 1,000 steps (no data gradient)?

Answer

About 0.3680.368 (≈e−1\approx e^{-1}).

Solution

Each step multiplies by 1−0.1⋅0.01=0.9991 - 0.1 \cdot 0.01 = 0.999, and 0.9991000≈e−10.999^{1000} \approx e^{-1}.

python · try it yourself
import math
print(round(0.999 ** 1000, 4), round(math.exp(-1), 4))
0.3677 0.3679

Test yourself

A Gaussian prior on the weights corresponds to which penalty?

  1. ℓ1\ell_1
  2. ℓ2\ell_2 squared (ridge)
  3. no penalty
  4. ℓ∞\ell_\infty

The ridge solution is…

  1. (XTX)−1XTy(X^TX)^{-1}X^T\mathbf{y}
  2. (XTX+λI)−1XTy(X^TX + \lambda I)^{-1}X^T\mathbf{y}
  3. XTyX^T\mathbf{y}
  4. λXTy\lambda X^T\mathbf{y}

Increasing the ridge parameter λ\lambda a lot leads to…

  1. overfitting
  2. underfitting: weights shrink towards 0
  3. no change
  4. sparse weights with exact zeros