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.
What runs in CodeSplash
- INF005Laplace approximation Runs in CodeSplash
- INF006Expectation propagation (EP) Explained here
- Bayesian GLM Verified in Python and R
- Bayesian regression model (Stan) Experimental
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
A normal at the mode
ReadNear 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:
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…When Laplace is wrong
ReadLaplace 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 by adding a ridge, you changed the approximation; report it. Compare against a grid in one or two dimensions, or against NUTS.
Laplace in CodeSplash
ReadBayesian 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 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
View data
| Posterior mean | Upper | Term | Lower |
|---|---|---|---|
| 0.3848 | 0.7065 | npreg | 0.0630 |
| 1.106 | 1.390 | glu | 0.8221 |
| −0.1701 | 0.1011 | bp | −0.4414 |
| −0.0178 | 0.3232 | skin | −0.3589 |
| 0.6632 | 1.021 | bmi | 0.3058 |
| 0.5460 | 0.8257 | ped | 0.2663 |
| 0.3326 | 0.6569 | age | 0.0083 |
Cross-validation
| Fold | Repeat | n | ROC AUC | log loss | accuracy | balanced accuracy |
|---|---|---|---|---|---|---|
| 1 | 1 | 107 | 0.8079 | 0.5110 | 0.7477 | 0.6866 |
| 2 | 1 | 107 | 0.8862 | 0.4105 | 0.7757 | 0.7077 |
| 3 | 1 | 106 | 0.8555 | 0.4880 | 0.8019 | 0.8014 |
| 4 | 1 | 106 | 0.8716 | 0.4042 | 0.8396 | 0.7861 |
Feature importance
| Feature | Importance |
|---|---|
| glu | 1.106 |
| bmi | 0.6632 |
| ped | 0.5460 |
| npreg | 0.3848 |
| age | 0.3326 |
| bp | 0.1701 |
| skin | 0.0178 |
Posterior of the coefficients
| Term | Mean | SD | 95% lower | 95% upper |
|---|---|---|---|---|
| (Intercept) | −1.011 | 0.1402 | −1.285 | −0.7359 |
| npreg | 0.3848 | 0.1642 | 0.0630 | 0.7065 |
| glu | 1.106 | 0.1448 | 0.8221 | 1.390 |
| bp | −0.1701 | 0.1384 | −0.4414 | 0.1011 |
| skin | −0.0178 | 0.1740 | −0.3589 | 0.3232 |
| bmi | 0.6632 | 0.1824 | 0.3058 | 1.021 |
| ped | 0.5460 | 0.1427 | 0.2663 | 0.8257 |
| age | 0.3326 | 0.1655 | 0.0083 | 0.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))
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
| Fold | Repeat | n | ROC AUC | log loss | accuracy | balanced accuracy |
|---|---|---|---|---|---|---|
| 1 | 1 | 107 | 0.8079 | 0.5110 | 0.7477 | 0.6866 |
| 2 | 1 | 107 | 0.8862 | 0.4105 | 0.7757 | 0.7077 |
| 3 | 1 | 106 | 0.8555 | 0.4880 | 0.8019 | 0.8014 |
| 4 | 1 | 106 | 0.8716 | 0.4042 | 0.8396 | 0.7861 |
Feature importance
| Feature | Importance |
|---|---|
| glu | 1.106 |
| bmi | 0.6632 |
| ped | 0.5460 |
| npreg | 0.3848 |
| age | 0.3326 |
| bp | 0.1701 |
| skin | 0.0178 |
Posterior of the coefficients
| Term | Mean | SD | 95% lower | 95% upper |
|---|---|---|---|---|
| (Intercept) | −1.011 | 0.1402 | −1.285 | −0.7359 |
| npreg | 0.3848 | 0.1642 | 0.0630 | 0.7065 |
| glu | 1.106 | 0.1448 | 0.8221 | 1.390 |
| bp | −0.1701 | 0.1384 | −0.4414 | 0.1011 |
| skin | −0.0178 | 0.1740 | −0.3589 | 0.3232 |
| bmi | 0.6632 | 0.1824 | 0.3058 | 1.021 |
| ped | 0.5460 | 0.1427 | 0.2663 | 0.8257 |
| age | 0.3326 | 0.1655 | 0.0083 | 0.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"])
)
Predict: a skewed posterior
PredictPredict 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?
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.
Expectation propagation
ReadExpectation 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, , and replace each hard factor with a simple normal site . Then, one site at a time:
- Cavity: remove the site, .
- Tilted distribution: put the exact factor back, .
- Match moments: find the normal with 's mean and variance, and set the new site to that normal divided by the cavity.
One site, by hand
ReadThe reference's example updates one probit site, , 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 has mean 0.335 and variance 0.811.
Matching moments locally minimizes a forward KL, , 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.
Where each idea stands in CodeSplash
Read| Entry | In 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 |
Check your understanding
CheckpointCheck 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.
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