Skip to content

Normal approximations: Laplace and expectation propagation

Two ways to summarize a posterior with a normal: fit it to the curvature at the mode (Laplace), or refine it factor by factor by matching moments (expectation propagation). Learn when each is close, and how each fails.

Advanced ~13 min9 steps

What runs in CodeSplash

You will be able to

  • Compute a Laplace approximation from a mode and a Hessian, and its evidence estimate
  • Explain why the transform of a bounded parameter matters for Laplace
  • Describe one EP site update (cavity, tilted distribution, moment match)
  • Contrast EP's local forward-KL matching with mean-field VI's reverse KL

Read first

01

A normal at the mode

Read

Near its peak, a smooth log posterior looks like a parabola, and the exponential of a parabola is a normal. The Laplace approximationLaplace approximation (normal at the mode)Approximates a posterior by a normal centered at its mode, with covariance from the inverse curvature (Hessian) there. takes that literally:

θ^=arg⁡max⁡θlog⁡p~(θ),H=−∇2log⁡p~(θ^),q(θ)=N(θ^, H−1),Z≈p~(θ^) (2π)d/2 ∣H∣−1/2.\hat\theta=\arg\max_\theta\log\tilde p(\theta),\quad H=-\nabla^2\log\tilde p(\hat\theta),\quad q(\theta)=\mathcal N\big(\hat\theta,\,H^{-1}\big),\quad Z\approx\tilde p(\hat\theta)\,(2\pi)^{d/2}\,|H|^{-1/2}.

It needs only an optimizer and second derivatives, so it is fast, and its last formula gives a rough evidenceBayesian evidence (marginal likelihood)The probability of the data averaged over the prior, p(y) = ∫ p(y | θ) p(θ) dθ; ratios of it between models are Bayes factors. for model comparison. The reference's example fits a logistic intercept from 10 successes in 15 trials with a standard-normal prior: mode 0.536, approximate posterior SD 0.472.

Reference · INF005 · Runs in CodeSplashLaplace approximationApproximates a posterior by a Gaussian centered at a mode, with covariance determined by local curvature. It can provide fast uncertainty summaries, approximate evidence, or a proposal for more accurate sampling when…
02

When Laplace is wrong

Read

Laplace assumes one interior mode with a positive-definite curvature, and a posterior that is roughly normal around it.

  • Skew and heavy tails. A normal is symmetric with thin tails; a posterior for a rare-event rate is neither.
  • Boundaries. A variance near zero sits against its bound. Fit on the log scale (with the Jacobian), then transform back.
  • Several modes. Laplace sees only the one it found.
  • A likelihood curvature is not a posterior. The inverse Hessian at a maximum-likelihood estimate is a frequentist variance, not a Bayesian posterior covariance, unless the prior is included.

If you stabilize HH by adding a ridge, you changed the approximation; report it. Compare against a grid in one or two dimensions, or against NUTS.

03

Laplace in CodeSplash

Read

Bayesian GLM uses an exact conjugate posterior for regression and a Laplace approximation at the posterior mode for binary and Poisson targets, so it reports intervals with no sampling, and Python and R agree exactly. Bayesian regression model (Stan) offers Laplace (normal at the mode) as an algorithm beside NUTS, and generalized linear mixed models use Laplace to integrate out random effects.

Bayesian GLMRecorded · Python and R agreeRecorded 2026-11-25 · 56 values compared
R

Bayesian GLM: cross-validated ROC AUC 0.855 ± 0.034 over 4 folds; ROC AUC on the locked test set 0.811 (n = 106).

CV ROC AUC
0.8553
SD across folds
0.0340
Test ROC AUC
0.8109

Plots

Posterior of the coefficientsHow large are several estimates, how precise, and which exclude the null?
View data
Posterior meanUpperTermLower
0.38480.7065npreg0.0630
1.1061.390glu0.8221
−0.17010.1011bp−0.4414
−0.01780.3232skin−0.3589
0.66321.021bmi0.3058
0.54600.8257ped0.2663
0.33260.6569age0.0083

Cross-validation

FoldRepeatnROC AUClog lossaccuracybalanced accuracy
111070.80790.51100.74770.6866
211070.88620.41050.77570.7077
311060.85550.48800.80190.8014
411060.87160.40420.83960.7861

Feature importance

FeatureImportance
glu1.106
bmi0.6632
ped0.5460
npreg0.3848
age0.3326
bp0.1701
skin0.0178

Posterior of the coefficients

TermMeanSD95% lower95% upper
(Intercept)−1.0110.1402−1.285−0.7359
npreg0.38480.16420.06300.7065
glu1.1060.14480.82211.390
bp−0.17010.1384−0.44140.1011
skin−0.01780.1740−0.35890.3232
bmi0.66320.18240.30581.021
ped0.54600.14270.26630.8257
age0.33260.16550.00830.6569
The exact R script · R R version 4.5.1 (2025-06-13)
# Bayesian GLM
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.bayes_glm 1.0.0 · spec a07c3e223d32ca27
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data and split plan
TARGET <- "diabetic"
FEATURES <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
TASK <- "binary"
CLASSES <- c("false", "true")
POSITIVE <- "true"
METRIC <- "roc_auc"
SEED <- 42
PARAMS <- list(
  prior_scale = 1,
  intercept_scale = 10,
  noise_shape = 0.01,
  noise_rate = 0.01,
  credible_level = 0.95
)

df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-8142/learn.bayes_glm/binary_pima/folds.parquet")  # host-written folds: identical in Python and R
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    npreg = "numeric",
    glu = "numeric",
    bp = "numeric",
    skin = "numeric",
    bmi = "numeric",
    ped = "numeric",
    age = "numeric"
  ),
  levels = list(
  ),
  impute = "median",
  scale = "standard",
  indicators = FALSE
)
target <- cs_ml_encode_target(df[[TARGET]], TASK, CLASSES, POSITIVE)
y <- target$fit
y_index <- target$index
weights <- cs_ml_class_weights(y_index, TASK, "none", plan$train)
run <- cs_ml_run(TASK, CLASSES, POSITIVE, METRIC)
out <- cs_ml_out_dir("target/academy-parity/run-8142/learn.bayes_glm/binary_pima/out-r")
warnings <- list()
sample_weights <- function(rows) if (is.null(weights)) NULL else weights[rows + 1L]
rows_of <- function(rows) df[rows + 1L, , drop = FALSE]
RESAMPLE <- "none"
if (RESAMPLE != "none" && TASK == "regression") {
  warnings <- c(warnings, list("Resampling applies to classification only — ignored for this regression target."))
}
resampled <- NULL  # the final model's resampling summary
notes <- list()
# A fit's design matrix, targets and weights: training rows only, resampled when asked
# (cs_ml_resample — the same rows in Python, from the shared random stream).
training_set <- function(X, rows, fold_id, repeat_) {
  yy <- y[rows + 1L]
  ww <- sample_weights(rows)
  if (RESAMPLE == "none" || TASK == "regression") return(list(X = X, y = yy, w = ww))
  r <- cs_ml_resample(X, yy, ww, RESAMPLE, ratio = 1, k = as.integer(5),
                      seed = cs_ml_resample_seed(SEED, fold_id, repeat_))
  if (fold_id == 0) resampled <<- r$info
  r
}
fit_on <- function(s) fit_model(s$X, s$y, s$w)

# %% Model
# Closed-form (regression) or Laplace (binary, Poisson) posterior; the same algebra in Python and R.
OBJECTIVE <- NULL

fit_model <- function(X, y, w) {
  cs_ml_bglm_fit(X, y, w, TASK, OBJECTIVE, PARAMS$prior_scale, PARAMS$intercept_scale, PARAMS$noise_shape, PARAMS$noise_rate)
}

predict_model <- function(model, X) cs_ml_bglm_predict(model, X)$mean
predict_sd <- function(model, X) cs_ml_bglm_predict(model, X)$sd

feature_importance <- function(model, names) cs_ml_coef_importance(names, model$mean[-1])

save_model <- function(model, directory) {
  path <- file.path(directory, "model.rds")
  saveRDS(model, path)
  list(list(key = "model", path = path, format = "rds"))
}

load_model <- function(directory) readRDS(file.path(directory, "model.rds"))

# %% Cross-validation
folds <- if (0 > 0) utils::head(plan$folds, 0) else plan$folds
progress <- cs_progress("Cross-validating", total = length(folds))
for (i in seq_along(folds)) {
  fold <- folds[[i]]
  prep <- cs_ml_design_fit(design, rows_of(fold$train))
  model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(fold$train)), fold$train, fold$id, fold$repeat_))
  cs_ml_add(run, fold$id, fold$repeat_, "valid", fold$valid, y, y_index,
            predict_model(model, cs_ml_design_apply(prep, rows_of(fold$valid))))
  cs_progress_update(progress, i, sprintf("Fold %d of %d", i, length(folds)))
}
cs_ml_lap(run, "cv_seconds")

# %% Final model
artifacts <- list()
importance <- NULL
prep <- cs_ml_design_fit(design, rows_of(plan$train))
names_ <- cs_ml_design_names(prep)
if (TRUE) {
  model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(plan$train)), plan$train, 0L, 0L))
  if (!is.null(resampled)) {
    warnings <- c(warnings, as.list(resampled$notes))
    notes <- c(notes, list(cs_ml_resample_describe(resampled)))
  }
  if (length(plan$test)) {
    cs_ml_add(run, 0L, 0L, "test", plan$test, y, y_index,
              predict_model(model, cs_ml_design_apply(prep, rows_of(plan$test))))
  }
  importance <- feature_importance(model, names_)
  artifacts[[length(artifacts) + 1L]] <- list(
    key = "design", path = cs_ml_save_json(cs_ml_design_json(prep), file.path(out, "design.json")), format = "json"
  )
  artifacts <- c(artifacts, save_model(model, out))
  cs_ml_lap(run, "final_seconds")
}
artifacts[[length(artifacts) + 1L]] <- list(key = "predictions", path = cs_ml_write(run, out), format = "parquet")
cs_progress_done(progress)

# %% Result
cs_publish(cs_ml_bglm_extend(cs_ml_result(
  run,
  title = "Bayesian GLM",
  engine = cs_engine_info("nanoparquet"),
  n_features = length(names_),
  n_train = length(plan$train),
  n_test = length(plan$test),
  params = PARAMS,
  features = names_,
  importance = importance,
  artifacts = artifacts,
  warnings = warnings,
  notes = notes
), model, names_, PARAMS$credible_level))
Python

Bayesian GLM: cross-validated ROC AUC 0.855 ± 0.034 over 4 folds; ROC AUC on the locked test set 0.811 (n = 106).

CV ROC AUC
0.8553
SD across folds
0.0340
Test ROC AUC
0.8109

To keep this page light, the plots are shown once, under the R tab.

Cross-validation

FoldRepeatnROC AUClog lossaccuracybalanced accuracy
111070.80790.51100.74770.6866
211070.88620.41050.77570.7077
311060.85550.48800.80190.8014
411060.87160.40420.83960.7861

Feature importance

FeatureImportance
glu1.106
bmi0.6632
ped0.5460
npreg0.3848
age0.3326
bp0.1701
skin0.0178

Posterior of the coefficients

TermMeanSD95% lower95% upper
(Intercept)−1.0110.1402−1.285−0.7359
npreg0.38480.16420.06300.7065
glu1.1060.14480.82211.390
bp−0.17010.1384−0.44140.1011
skin−0.01780.1740−0.35890.3232
bmi0.66320.18240.30581.021
ped0.54600.14270.26630.8257
age0.33260.16550.00830.6569
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Bayesian GLM
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.bayes_glm 1.0.0 · spec a07c3e223d32ca27
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import bayes_glm as csbayes
from codesplash.ml import linear as cslin

# %% Data and split plan
TARGET = "diabetic"
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
TASK = "binary"
CLASSES = ["false", "true"]
POSITIVE = "true"
METRIC = "roc_auc"
SEED = 42
PARAMS = {
    "prior_scale": 1,
    "intercept_scale": 10,
    "noise_shape": 0.01,
    "noise_rate": 0.01,
    "credible_level": 0.95,
}

df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-8142/learn.bayes_glm/binary_pima/folds.parquet")  # host-written folds: identical in Python and R
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "npreg": "numeric",
        "glu": "numeric",
        "bp": "numeric",
        "skin": "numeric",
        "bmi": "numeric",
        "ped": "numeric",
        "age": "numeric",
    },
    levels={
    },
    impute="median",
    scale="standard",
    indicators=False,
)
y, y_index = csml.encode_target(df[TARGET], TASK, CLASSES, POSITIVE)
weights = csml.class_weights(y_index, TASK, "none", plan.train)
run = csml.LearnerRun(TASK, CLASSES, POSITIVE, METRIC)
out = csml.out_dir("target/academy-parity/run-8142/learn.bayes_glm/binary_pima/out-python")
warnings = []


def sample_weights(rows):
    return None if weights is None else weights[rows]


RESAMPLE = "none"
if RESAMPLE != "none" and TASK == "regression":
    warnings.append("Resampling applies to classification only — ignored for this regression target.")
resampled = None  # the final model's resampling summary
notes = []


def training_set(X, rows, fold_id, repeat):
    """A fit's design matrix, targets and weights: training rows only, resampled when asked
    (codesplash.ml.resample — the same rows in R, from the shared random stream)."""
    yy, ww = y[rows], sample_weights(rows)
    if RESAMPLE == "none" or TASK == "regression":
        return X, yy, ww
    from codesplash.ml import resample as csres

    X2, y2, w2, info = csres.resample(
        X, yy, ww, RESAMPLE, ratio=1, k=5, seed=csres.resample_seed(SEED, fold_id, repeat)
    )
    if fold_id == 0:
        global resampled
        resampled = info
    return X2, y2, w2


# %% Model
# Closed-form (regression) or Laplace (binary, Poisson) posterior; the same algebra in Python and R.
OBJECTIVE = None


def fit_model(X, y, w):
    return csbayes.fit(X, y, w, TASK, OBJECTIVE, PARAMS["prior_scale"], PARAMS["intercept_scale"], PARAMS["noise_shape"], PARAMS["noise_rate"])


def predict_model(model, X):
    return csbayes.predict(model, X)[0]


def predict_sd(model, X):
    return csbayes.predict(model, X)[1]


def feature_importance(model, names):
    return cslin.coef_importance(names, model["mean"][1:])


def save_model(model, directory):
    import joblib

    path = os.path.join(directory, "model.joblib")
    joblib.dump(model, path)
    return [{"key": "model", "path": path, "format": "joblib"}]


def load_model(directory):
    import joblib

    return joblib.load(os.path.join(directory, "model.joblib"))


# %% Cross-validation
folds = plan.folds[: 0] if 0 else plan.folds
progress = cs.progress("Cross-validating", total=len(folds))
for i, fold in enumerate(folds):
    prep = design.fit(df.iloc[fold.train])
    model = fit_model(*training_set(prep.transform(df.iloc[fold.train]), fold.train, fold.id, fold.repeat))
    run.add(fold.id, fold.repeat, "valid", fold.valid, y, y_index, predict_model(model, prep.transform(df.iloc[fold.valid])))
    progress.update(i + 1, f"Fold {i + 1} of {len(folds)}")
run.lap("cv_seconds")

# %% Final model
artifacts = []
importance = None
prep = design.fit(df.iloc[plan.train])
names = prep.names
if True:
    model = fit_model(*training_set(prep.transform(df.iloc[plan.train]), plan.train, 0, 0))
    if resampled is not None:
        from codesplash.ml import resample as csres

        warnings.extend(resampled["notes"])
        notes.append(csres.describe(resampled))
    if len(plan.test):
        run.add(0, 0, "test", plan.test, y, y_index, predict_model(model, prep.transform(df.iloc[plan.test])))
    importance = feature_importance(model, names)
    artifacts.append({"key": "design", "path": csml.save_json(prep.to_json(), os.path.join(out, "design.json")), "format": "json"})
    artifacts.extend(save_model(model, out))
    run.lap("final_seconds")
artifacts.append({"key": "predictions", "path": run.write(out), "format": "parquet"})
progress.done()

# %% Result
cs.publish(
    csbayes.extend_result(run.result(
        title="Bayesian GLM",
        engine=cs.engine_info("scipy", "numpy", "pandas"),
        n_features=len(names),
        n_train=len(plan.train),
        n_test=len(plan.test),
        params=PARAMS,
        features=names,
        importance=importance,
        artifacts=artifacts,
        warnings=warnings,
        notes=notes,
    ), model, names, PARAMS["credible_level"])
)
04

Predict: a skewed posterior

Predict

Predict first

A rate's posterior has a long right tail. Its Laplace approximation gives a symmetric 95% interval. How does it compare with the real posterior interval?

About right: the mode and curvature capture itToo short on the long side and too long on the short side
Reveal

Too short on the long side, too long on the short side. A normal can't be skewed. Fitting on the log scale often helps, since the log of a positive rate is closer to normal; check against draws from NUTS.

05

Expectation propagation

Read

Expectation propagationExpectation propagationReplaces each hard likelihood factor by a simple site, refining one site at a time by matching moments of a local tilted distribution. (EP) builds a normal differently. Write the posterior as a prior times factors, p0(θ)∏ifi(θ)p_0(\theta)\prod_i f_i(\theta), and replace each hard factor with a simple normal site f~i\tilde f_i. Then, one site at a time:

  1. Cavity: remove the site, q−i∝q/f~iq_{-i}\propto q/\tilde f_i.
  2. Tilted distribution: put the exact factor back, p^i∝q−i fi\hat p_i\propto q_{-i}\,f_i.
  3. Match moments: find the normal with p^i\hat p_i's mean and variance, and set the new site to that normal divided by the cavity.
Reference · INF006 · Explained hereExpectation propagation (EP)Approximates a factorized probability model by replacing difficult factors with tractable sites, repeatedly matching moments of local tilted distributions.
06

One site, by hand

Read

The reference's example updates one probit site, f(θ)=Φ(θ)f(\theta)=\Phi(\theta), with a standard-normal cavity, whose tilted moments have a formula. With damping one half (blend old and new site parameters), the new site's precision is 0.233, and the updated qq has mean 0.335 and variance 0.811.

Matching moments locally minimizes a forward KL, KL(p^i ∥ q)\mathrm{KL}(\hat p_i\,\|\,q), so EP tends to cover a factor's mass instead of hugging the peak. That often makes it more accurate than mean-field VI for probit and Gaussian-process classifiers. But EP isn't guaranteed to converge, a cavity can get a negative variance, and damping helps without proving anything.

07

Where each idea stands in CodeSplash

Read
EntryIn CodeSplash
Laplace approximation (INF005)Runs in CodeSplash: Bayesian GLM (binary and Poisson targets), Bayesian regression model (Stan) with algorithm Laplace, and generalized linear mixed models
Expectation propagation (INF006)Explained here: no EP method; the reference's one-site update is a verified component check
08

Check your understanding

Checkpoint

Check yourself

Where does the Laplace approximation's covariance come from?

Show the answer

Answer: b

Curvature at the peak sets the spread: sharp curvature, narrow normal. Include the log prior in the Hessian, or you get a likelihood-only variance.

Check yourself

A group SD's posterior piles up near zero. What should you do before using a Laplace approximation?

Show the answer

Answer: b

A normal on the original scale would put mass below zero and miss the skew. Coordinates matter for Laplace.

Check yourself

Two models' Laplace evidence estimates are compared. One posterior is bimodal. What's the risk?

Show the answer

Answer: b

The evidence formula integrates a single normal bump. Missing modes, a wrong prior normalization or a skewed posterior all distort it.

Check yourself

In one EP update, what is the tilted distribution?

Show the answer

Answer: b

EP then projects the tilted distribution onto a normal by matching moments, and divides out the cavity to get the new site.

Check yourself

How does EP's moment matching differ from mean-field VI's objective?

Show the answer

Answer: b

Different KL directions give different failure styles: VI tends to be too narrow, EP tends to cover, and EP's convergence isn't guaranteed.

09

Recap

Recap
  • Laplace: a normal at the mode with covariance from the inverse curvature; fast, rough for skew, bounds and several modes.
  • Transform bounded parameters first, and include the prior in the Hessian.
  • EP refines one normal site at a time by matching moments of a tilted distribution.
  • Laplace runs in CodeSplash (Bayesian GLM, Stan's Laplace option); EP is explained here.

Concepts in this lesson