Algorithmresearch
Pareto smoothed importance sampling leave-one-out cross-validation
Also called PSIS-LOO, PSIS leave-one-out.
Estimates leave-one-out predictive accuracy from one set of posterior draws, by importance weights whose tail is smoothed with a fitted generalized Pareto law.
- Time
- Θ(n S log S) worst · best
- Space
- Θ(n + S) extra
- Where
- S = the number of posterior draws; n = the number of observations
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Aki Vehtari, Andrew Gelman, Jonah Gabry, Daniel Simpson, Yuling Yao, 2015
PSIS-LOO estimates how well a Bayesian model predicts each data point when that point is left out, without refitting the model times. It reuses one set of draws from the full posterior and gives each draw the importance ratio . Raw ratios can have a very heavy tail, so the method replaces the largest ones by quantiles of a fitted generalized Pareto law, and the fitted shape tells the user when the estimate cannot be trusted. The cost is one sort per observation, for observations and draws.
In plain words
To check a model honestly, you want to predict each data point from a model fitted without it. Refitting for every point is slow. A shortcut is to reweight the draws you already have: draws that explain the left-out point badly get more weight, because the model without that point would favour them. A few draws can get huge weights, and then the answer is noisy. PSIS keeps the small weights as they are and replaces the largest ones by smooth values from a fitted tail curve. The steepness of that curve is a warning light: if it is too heavy, the shortcut is not reliable for that point, and you should refit or use a better model.
The problem
Input. A model with likelihood , so the observations are conditionally independent given . Draws from the posterior , for example from Hamiltonian Monte Carlo. The matrix .
Output. An estimate of the expected log pointwise predictive density for new data,
where is the data without point . Also its standard error, the effective number of parameters , the shapes , and the list of points whose is too large.
The identity behind it. If on the support of the posterior, then
so leave-one-out needs only expectations under the full posterior. With the ratios this is importance sampling with the full posterior as the proposal and as the target. The proof is in Correctness.
The algorithm
The outer routine runs once per observation. GPD-FIT is the shape and scale estimate of Zhang and Stephens (2009), with the shrinkage of Vehtari et al. (2024, Appendix G).
PSIS-LOO(ℓ) ▷ ℓ[i][s] = log p(yᵢ | θˢ), n rows, S draws from p(θ | y)- 1
M ← ⌊min(0.2 S, 3 √S)⌋ ▷ tail length - 2
for i ← 1 to n do - 3
ρₛ ← -ℓ[i][s] - maxₜ(-ℓ[i][t]) for every s ▷ log ratios, the largest is 0 - 4
sort the draws by ρ; u ← exp(ρ at rank S - M) ▷ the threshold - 5
(k̂ᵢ, σ̂) ← GPD-FIT(exp(ρ) - u over the M largest draws) - 6
for z ← 1 to M do the z-th of the M largest draws gets weight min(u + F⁻¹((z - 1/2)/M; k̂ᵢ, σ̂), 1) - 7
the other S - M draws keep the weight exp(ρₛ); call all weights w̃ₛ - 8
eᵢ ← log Σₛ w̃ₛ exp(ℓ[i][s]) - log Σₛ w̃ₛ - 9
flagged ← { i : k̂ᵢ > min(1 - 1/log₁₀ S, 0.7) } - 10
elpd ← Σᵢ eᵢ - 11
se ← √(n · sample variance of e₁, ..., eₙ) - 12
return elpd, se, p_loo = Σᵢ log((1/S) Σₛ exp(ℓ[i][s])) - elpd, (k̂ᵢ), flagged GPD-FIT(x₁, ..., x_M) ▷ exceedances x ≥ 0, sorted, x_M > 0- 13
m ← 30 + ⌊√M⌋ - 14
θⱼ ← 1/x_M + (1 - √(m/(j - 1/2)))/(3 x*) for j = 1, ..., m ▷ x* is the first quartile - 15
Lⱼ ← M (log(-θⱼ/κ(θⱼ)) - κ(θⱼ) - 1) with κ(θ) = (1/M) Σ log(1 - θ xₜ) - 16
πⱼ ← exp(Lⱼ) / Σₗ exp(Lₗ) - 17
θ̂ ← Σⱼ πⱼ θⱼ; k̂ ← κ(θ̂); σ̂ ← -k̂/θ̂ - 18
k̂ ← (M k̂ + 10 · 0.5)/(M + 10); return (k̂, σ̂)
is the quantile function of the generalized Pareto law with location , shape and scale , and when . Line L3 shifts the log ratios so that the largest raw ratio is ; this changes no estimate, because L8 is a ratio. Line L6 replaces the largest ratios by the expected order statistics of the fitted tail, in the same order, and caps them at the largest raw ratio. Line L8 is self-normalized importance sampling. Line L15 is the profile log-likelihood of the generalized Pareto law in ; L16 and L17 average it over a grid, which is more stable than its maximum. Line L18 pulls toward with the weight of 10 observations, which helps when is small. Sums of exponentials use the log-sum-exp trick: subtract the largest term before exponentiating, and add it back after the logarithm.
If or all exceedances are , the implementation skips the smoothing and reports , as the reference implementations do.
Example
Five points. The model is with prior , and the data are . The posterior is . Leave-one-out has a closed form here: is the normal density at with the mean and variance of the posterior from the other four points, plus for the noise. We take draws with random.Random(1), so L1 gives .
Trace for the last point, :
- L3 and L4: the threshold is times the largest ratio.
- L5: GPD-FIT on the exceedances gives and .
- L6: the three largest ratios were , and ; after smoothing all three are at the cap . Kong's effective sample size of the weights goes from to .
- L8: . Raw importance sampling gives , and the exact value is .
| PSIS | exact | |||
|---|---|---|---|---|
| 1 | 0.5 | 0.352 | ||
| 2 | 1.0 | 0.292 | ||
| 3 | 2.0 | 0.165 | ||
| 4 | 2.5 | 0.235 | ||
| 5 | 4.0 | 0.421 | ||
| sum |
L12 gives . No point is flagged. All five errors have the same sign, because they use the same draws. WAIC from the same draws gives .
One outlier. Take 19 points from random.Random(7) (standard normal, rounded to 2 decimals) and add a last point . The draws use random.Random(11), .
| flagged | PSIS | exact | PSIS elpd | exact elpd | ||
|---|---|---|---|---|---|---|
| a 20th normal point | 0.077 | none | ||||
| 4 | 0.394 | none | ||||
| 6 | 0.564 | none | ||||
| 9 | 0.827 | point 20 | ||||
| 15 | 1.358 | point 20 |
At the error is nats, and raw importance sampling () is no better. Exact refitting is the fix. In this model the true tail of the ratios is light: with has finite moments of every order below . The large is a finite-sample effect: in the range of ratios that 4000 draws can reach, the tail behaves like a Pareto tail with shape near or . This is what the diagnostic is meant to report.
Correctness
Four facts, proved in proofs/correctness.md:
- The identity. when the observations are conditionally independent given and on the support of the posterior. In particular is always finite, so raw importance sampling is consistent by the law of large numbers for independent draws (or the ergodic theorem for a Markov chain). The variance of the raw ratios can still be infinite.
- The code is Algorithm 1. Lines L1 to L12 compute the tail length, threshold, quantiles and cap of Algorithm 1 of Vehtari et al. (2024).
- Smoothing keeps the order and the cap. Only the largest ratios change; they stay in the same order, at least and at most the largest raw ratio.
- L15 is the profile likelihood. For a fixed the generalized Pareto log-likelihood is maximized at , and its value there is of line L15.
What is proved: the four facts above, and the tests check them on exact cases. What is only cited: that the smoothed estimate has finite variance and is consistent as grows, and that it is reliable when (Vehtari et al. 2024, Section 3). These come from the theory of the generalized Pareto tail and from experiments. On this page they are only measured, in the tables above.
Proof: The leave-one-out identity, and what PSIS-LOO computesfull
We use the pseudocode of the page. The model has , a prior , and posterior . Write for the data without point .
Claim 1 (the identity). Assume for every in the support of . Then
Proof. Conditional independence gives . By Bayes's theorem applied twice,
because and . Multiply by and integrate over :
The positivity assumption makes the division valid on the support of , and is zero wherever .
The same computation with a function gives the importance sampling identity
so is the importance ratio from the proposal to the target , up to a constant.
Claim 2 (raw importance sampling is consistent). Let be independent draws from . Then almost surely.
Proof. By Claim 1, , which is finite and positive. The strong law of large numbers gives almost surely, and is continuous at a positive limit.
With raw weights , line L8 computes , which is this estimate. For an ergodic Markov chain the ergodic theorem replaces the law of large numbers. Claim 2 says nothing about the variance: can be infinite, and then the central limit theorem fails and the error decreases more slowly than . This is the reason for the smoothing.
Claim 3 (the code is Algorithm 1). Line L1 computes . Line L3 computes , so ; a common factor cancels in L8. Line L4 sorts and sets to the ratio of rank , so the draws of ranks form the tail and on the tail. Line L5 fits the generalized Pareto law to these exceedances. Line L6 gives the draw of rank the weight , and is the largest raw ratio after the shift. Line L9 uses the threshold . These are the steps of Algorithm 1 and Eq. 13 of Vehtari, Simpson, Gelman, Yao and Gabry (2024). Line L10 sums the pointwise values, L11 computes times their sample standard deviation, and L12 computes with .
Claim 4 (order and cap). After L6 and L7, the smallest weights are unchanged, and the tail weights are nondecreasing in the rank and lie in .
Proof. Lines L6 and L7 change only the draws of ranks to . For and the function has derivative on , and ; the case is , also increasing with value at . The points increase with and lie in . So is at least and increases with , and the minimum with keeps both facts and adds the upper bound. The draw of rank gets the -th value, so the order of the draws is kept. Since the largest raw ratio is and , every weight lies in .
As a consequence, no single draw can get a weight above the largest raw ratio, and the weights of the body of the distribution are exactly the raw ones.
Claim 5 (L15 is the profile log-likelihood). The generalized Pareto law with location , shape and scale has density on its support. For exceedances and fixed with for all and , the maximum of the log-likelihood over is , attained at .
Proof. With we have , so the log-likelihood is
Here and have opposite signs because . The derivative in is , which is zero only at . On the side of where the second term dominates near and the first term dominates at infinity, so this point is the maximum. Substituting gives .
The grid of L14 satisfies , because for . So for every exceedance, and L15 is defined. Lines L16 and L17 average with weights proportional to the profile likelihood, which is the estimate of Zhang and Stephens (2009) with their grid and prior, and L18 is the shrinkage of Appendix G of Vehtari et al. (2024).
What is not proved here. Vehtari et al. (2024, Section 3) argue that the PSIS estimate has finite variance and is consistent as , and that its error is small when the true tail shape is below about . These statements rest on the asymptotic theory of the generalized Pareto approximation to a tail and on simulation. This page cites them. The tests measure the error against exact leave-one-out in a conjugate normal model, and check Claims 1, 3 and 4 directly.
Complexity
For each of the rows: L3 is , the sort in L4 is , GPD-FIT costs because , and L6 to L8 are . The total is in the best and the worst case. A selection of the largest ratios instead of a full sort lowers this to expected time. Extra space is for one row of weights plus for the outputs. The input matrix itself has entries, and computing it costs likelihood evaluations, which usually dominates. Exact leave-one-out would cost extra posterior fits.
Properties
- Deterministic given the draws. All randomness is in the posterior draws.
- Not exact. It is a Monte Carlo estimate of . Each is biased upward for finite , because is concave (Jensen's inequality); the bias falls like when the ratios have finite variance.
- Pointwise. It needs a likelihood that factorizes over the units that you want to leave out. For time series or spatial data, leaving out one point is often the wrong question.
- Diagnostic included. is computed for every point at no extra cost. A large marks a point that is very influential for the posterior, often an outlier or a sign of a misspecified model.
- Same target as WAIC. Both estimate for new data from the same process. They agree to first order in regular models (Watanabe 2010), but PSIS-LOO has a diagnostic and is more robust when the posterior is far from normal (Vehtari, Gelman and Gabry 2017).
- Not the marginal likelihood. PSIS-LOO measures prediction of each point from the others. The marginal likelihood and the Bayes factor measure prediction of all data from the prior. The two can rank models differently.
Variants and improvements
- MCMC draws. With correlated draws, Appendix H of Vehtari et al. (2024) uses in the tail length, where is the relative effective sample size of the ratios.
- Rounding. The paper takes the floor in L1. The reference implementations take the ceiling. The difference is one draw in the tail.
- Moment matching. For flagged points, transform the existing draws so that their moments match the leave-one-out posterior, then recompute the weights (Paananen and coauthors, 2021).
- Exact refits for flagged points. Refit the model without each flagged point and use the exact value for those points only. This is cheap when few points are flagged.
- K-fold. If many points are flagged, use K-fold cross-validation with refits.
- Truncated importance sampling. Ionides (2008) truncates the ratios at times their mean. It also bounds the variance, but has more bias than PSIS when the tail is light.
- PSIS outside LOO. The same smoothing stabilizes importance sampling in general, and checks variational approximations (Yao and coauthors, 2018).
When to use it
Use it to compare Bayesian models by their predictive accuracy when you already have posterior draws and a pointwise log-likelihood. Report with its standard error, and for a comparison of two models use the standard error of the pointwise differences, not the difference of the two standard errors. Check for every point. Prefer it to WAIC, which has no diagnostic. Do not use it to test a hypothesis; for that question, see the Bayes factor page, which has a different target.
Pitfalls
- Ignoring . A large means that the estimate for that point can be far off, as in the outlier table. Raw importance sampling does not fix it.
- Thinning and too few draws. With small the tail has few draws, the threshold falls (it is at ), and the estimate is noisy.
- The wrong unit. Hierarchical models with one observation per group can have large for most points, because removing one point changes its group parameter a lot. Leave out whole groups, or integrate the group parameter out.
- Dependent data. Leave-one-out for a time series uses the future to predict the past. Use leave-future-out or block designs.
- Overflow. Use logarithms. Ratios like are common.
- Small differences. A difference of smaller than a few standard errors of the difference does not show that one model is better.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pareto-smoothed-importance-sampling-loo/. The authors are listed in prov/NR2Y7A.jsonl.
"""Pareto smoothed importance sampling (PSIS) and PSIS leave-one-out cross-validation.
The input of psis_loo and waic is a log-likelihood matrix: loglik[i][s] is
log p(y_i | theta^s) for observation i = 0, ..., n - 1 and posterior draw
s = 0, ..., S - 1. The draws must come from the full-data posterior.
The smoothing follows Algorithm 1 of Vehtari, Simpson, Gelman, Yao and Gabry
(2024): the tail length is M = floor(min(0.2 S, 3 sqrt(S))), the threshold is
the (S - M)-th smallest ratio, the M largest ratios are replaced by quantiles
of a fitted generalized Pareto law at (z - 1/2)/M, and no smoothed weight may
exceed the largest raw ratio. The shape estimate uses the method of Zhang and
Stephens (2009), followed by the shrinkage toward 0.5 with the weight of 10
observations that the paper describes in its Appendix G.
"""
import math
from typing import Sequence
def log_sum_exp(xs: Sequence[float]) -> float:
"""log(sum(exp(x))) without overflow: subtract the largest term first."""
m = max(xs)
if m == -math.inf:
return -math.inf
return m + math.log(math.fsum(math.exp(x - m) for x in xs))
def tail_length(s: int) -> int:
"""M = floor(min(0.2 S, 3 sqrt(S))), the number of ratios in the fitted tail."""
return int(math.floor(min(0.2 * s, 3.0 * math.sqrt(s))))
def khat_threshold(s: int) -> float:
"""min(1 - 1/log10(S), 0.7): above it the PSIS estimate is flagged as unreliable."""
return min(1.0 - 1.0 / math.log10(s), 0.7)
def gpd_fit(x: Sequence[float], min_grid: int = 30, prior: float = 3.0,
shrink_n: float = 10.0, shrink_to: float = 0.5) -> tuple[float, float]:
"""Estimate (k, sigma) of a generalized Pareto law with location 0 from exceedances x >= 0.
Zhang and Stephens (2009): the profile log-likelihood in theta = -k/sigma is
n (log(-theta/k(theta)) - k(theta) - 1) with k(theta) = mean(log(1 - theta x)).
It is averaged over a grid of theta values, weighted by the normalized profile
likelihood, and k is recomputed at the averaged theta. Then k is shrunk toward
shrink_to with the weight of shrink_n observations. Positive k is a heavy tail.
"""
xs = sorted(float(v) for v in x)
n = len(xs)
if n == 0 or xs[-1] <= 0.0:
raise ValueError("gpd_fit needs at least one positive exceedance")
m = min_grid + int(math.floor(math.sqrt(n))) # @line L13
xstar = xs[int(math.floor(n / 4.0 + 0.5)) - 1] # first quartile
if xstar <= 0.0:
xstar = next(v for v in xs if v > 0.0)
thetas = [1.0 / xs[-1] + (1.0 - math.sqrt(m / (j - 0.5))) / (prior * xstar) # @line L14
for j in range(1, m + 1)]
prof = []
for th in thetas:
k = math.fsum(math.log1p(-th * v) for v in xs) / n
prof.append(n * (math.log(-th / k) - k - 1.0)) # @line L15
top = log_sum_exp(prof)
wts = [math.exp(p - top) for p in prof] # @line L16
th_hat = math.fsum(w * t for w, t in zip(wts, thetas))
k_hat = math.fsum(math.log1p(-th_hat * v) for v in xs) / n # @line L17
sigma = -k_hat / th_hat
k_hat = (n * k_hat + shrink_n * shrink_to) / (n + shrink_n) # @line L18
return k_hat, sigma
def gpd_quantile(p: float, k: float, sigma: float) -> float:
"""The p-quantile of the generalized Pareto law with location 0, shape k, scale sigma."""
if abs(k) < 1e-12:
return -sigma * math.log1p(-p)
return sigma * math.expm1(-k * math.log1p(-p)) / k
def psis_smooth(log_ratios: Sequence[float]) -> tuple[list[float], float]:
"""Pareto smooth the importance ratios exp(log_ratios).
Returns the smoothed log weights (shifted so that the largest raw log ratio is
0, not normalized) and the shape estimate k-hat. If the tail has fewer than 5
draws, or all its exceedances are 0, the weights are returned unchanged and
k-hat is reported as infinity, as the reference implementations do.
"""
s = len(log_ratios)
m = tail_length(s) # @line L1
top = max(log_ratios)
lw = [v - top for v in log_ratios] # @line L3
order = sorted(range(s), key=lambda j: lw[j]) # @line L4
if m < 5:
return lw, math.inf
u = math.exp(lw[order[s - m - 1]])
tail = [math.exp(lw[j]) - u for j in order[s - m:]]
if tail[-1] <= 0.0:
return lw, math.inf
k, sigma = gpd_fit(tail) # @line L5
if not math.isfinite(k):
return lw, math.inf
for z in range(1, m + 1): # @line L6
w = min(u + gpd_quantile((z - 0.5) / m, k, sigma), 1.0)
lw[order[s - m + z - 1]] = math.log(w)
return lw, k # @line L7
def _variance(xs: Sequence[float]) -> float:
"""Sample variance with divisor len(xs) - 1."""
n = len(xs)
mean = math.fsum(xs) / n
return math.fsum((v - mean) ** 2 for v in xs) / (n - 1)
def psis_loo(loglik: Sequence[Sequence[float]]) -> dict:
"""PSIS-LOO estimate of the expected log pointwise predictive density.
Returns a dict with elpd_loo, se_elpd_loo (sqrt(n) times the sample standard
deviation of the pointwise values), p_loo = lppd - elpd_loo, looic = -2 elpd_loo,
the pointwise elpd values, the k-hat values, and the indices whose k-hat is
above min(1 - 1/log10(S), 0.7).
Cost: Theta(n S log S) time for the sorts, Theta(S) extra memory per row.
"""
n = len(loglik)
s = len(loglik[0])
limit = khat_threshold(s)
pointwise, khats, lppd_i = [], [], []
for row in loglik: # @line L2
if len(row) != s:
raise ValueError("every row needs the same number of draws")
lw, k = psis_smooth([-v for v in row])
num = log_sum_exp([a + b for a, b in zip(lw, row)]) # @line L8
pointwise.append(num - log_sum_exp(lw))
khats.append(k)
lppd_i.append(log_sum_exp(row) - math.log(s))
elpd = math.fsum(pointwise) # @line L10
lppd = math.fsum(lppd_i)
se = math.sqrt(n * _variance(pointwise)) if n > 1 else math.nan # @line L11
return { # @line L12
"elpd_loo": elpd,
"se_elpd_loo": se,
"p_loo": lppd - elpd,
"looic": -2.0 * elpd,
"pointwise": pointwise,
"k_hat": khats,
"flagged": [i for i, k in enumerate(khats) if k > limit], # @line L9
}
def is_loo_raw(loglik: Sequence[Sequence[float]]) -> list[float]:
"""Plain importance sampling LOO: elpd_i = -log((1/S) sum_s 1/p(y_i | theta^s))."""
out = []
for row in loglik:
out.append(math.log(len(row)) - log_sum_exp([-v for v in row]))
return out
def waic(loglik: Sequence[Sequence[float]]) -> dict:
"""WAIC from draws: lppd - p_waic, with p_waic the sum of sample variances (divisor S - 1)."""
n = len(loglik)
s = len(loglik[0])
pts, pen, lp = [], [], []
for row in loglik:
a = log_sum_exp(row) - math.log(s)
v = _variance(row)
lp.append(a)
pen.append(v)
pts.append(a - v)
elpd = math.fsum(pts)
return {
"lppd": math.fsum(lp),
"p_waic": math.fsum(pen),
"elpd_waic": elpd,
"waic": -2.0 * elpd,
"se_elpd_waic": math.sqrt(n * _variance(pts)) if n > 1 else math.nan,
"pointwise": pts,
}
test_pareto_smoothed_importance_sampling_loo.py 198 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pareto-smoothed-importance-sampling-loo/. The authors are listed in prov/NR2Y7A.jsonl.
"""Tests for PSIS-LOO: exact identities, a conjugate normal model with exact LOO, and the GPD fit."""
import math
import random
import unittest
from fractions import Fraction as F
from pareto_smoothed_importance_sampling_loo import (
gpd_fit,
gpd_quantile,
is_loo_raw,
khat_threshold,
psis_loo,
psis_smooth,
tail_length,
waic,
)
LOG2PI = math.log(2.0 * math.pi)
def lnorm(x, m, v):
return -0.5 * (LOG2PI + math.log(v) + (x - m) ** 2 / v)
def posterior(ys, sig2=1.0, mu0=0.0, t02=100.0):
prec = 1.0 / t02 + len(ys) / sig2
return (mu0 / t02 + sum(ys) / sig2) / prec, 1.0 / prec
def exact_loo(ys, sig2=1.0):
out = []
for i in range(len(ys)):
m, v = posterior(ys[:i] + ys[i + 1:], sig2)
out.append(lnorm(ys[i], m, v + sig2))
return out
def exact_waic(ys, sig2=1.0):
m, v = posterior(ys, sig2)
lppd = sum(lnorm(y, m, v + sig2) for y in ys)
p = sum((2 * v * v + 4 * (y - m) ** 2 * v) / (4 * sig2 * sig2) for y in ys)
return lppd, p, lppd - p
def draws_matrix(ys, s, seed, sig2=1.0):
rng = random.Random(seed)
m, v = posterior(ys, sig2)
th = [rng.gauss(m, math.sqrt(v)) for _ in range(s)]
return [[lnorm(y, t, sig2) for t in th] for y in ys]
def outlier_data(last):
rng = random.Random(7)
base = [round(rng.gauss(0.0, 1.0), 2) for _ in range(19)]
return base + [last]
class HarmonicIdentity(unittest.TestCase):
"""p(y_i | y_-i) = 1 / E_post[1 / p(y_i | theta)], checked exactly on a discrete model."""
def setUp(self):
self.thetas = [F(1, 4), F(1, 2), F(3, 4)]
self.post = [F(1, 4), F(1, 2), F(1, 4)]
self.ys = [1, 0, 1]
def lik(t, y):
return t if y == 1 else 1 - t
self.lik = lik
full = [math.prod(lik(t, y) for y in self.ys) for t in self.thetas]
prior = [p / L for p, L in zip(self.post, full)]
total = sum(prior)
self.prior = [p / total for p in prior]
def exact(self, i):
rest = self.ys[:i] + self.ys[i + 1:]
w = [p * math.prod(self.lik(t, y) for y in rest) for p, t in zip(self.prior, self.thetas)]
return sum(a * self.lik(t, self.ys[i]) for a, t in zip(w, self.thetas)) / sum(w)
def test_identity_in_fractions(self):
for i, y in enumerate(self.ys):
harmonic = 1 / sum(p / self.lik(t, y) for p, t in zip(self.post, self.thetas))
self.assertEqual(harmonic, self.exact(i))
def test_raw_is_exact_on_weighted_draws(self):
draws = [F(1, 4)] + [F(1, 2)] * 2 + [F(3, 4)]
ll = [[math.log(self.lik(t, y)) for t in draws] for y in self.ys]
for i, got in enumerate(is_loo_raw(ll)):
self.assertAlmostEqual(got, math.log(self.exact(i)), places=12)
class Helpers(unittest.TestCase):
def test_tail_length(self):
self.assertEqual(tail_length(100), 20)
self.assertEqual(tail_length(1000), 94)
self.assertEqual(tail_length(4000), 189)
def test_threshold(self):
self.assertAlmostEqual(khat_threshold(100), 0.5)
self.assertAlmostEqual(khat_threshold(1000), 2.0 / 3.0)
self.assertEqual(khat_threshold(4000), 0.7)
def test_gpd_quantile_inverts_cdf(self):
for k in (0.0, 0.4, -0.3):
for p in (0.1, 0.5, 0.9):
x = gpd_quantile(p, k, 2.0)
cdf = 1 - math.exp(-x / 2.0) if k == 0 else 1 - (1 + k * x / 2.0) ** (-1 / k)
self.assertAlmostEqual(cdf, p, places=12)
def test_gpd_fit_recovers_shape(self):
rng = random.Random(3)
for k in (0.0, 0.3, 0.5, 0.8):
xs = []
for _ in range(2000):
u = rng.random()
xs.append(-math.log(u) if k == 0 else (u ** (-k) - 1) / k)
khat, sigma = gpd_fit(xs)
self.assertLess(abs(khat - k), 0.1)
self.assertLess(abs(sigma - 1.0), 0.15)
class Smoothing(unittest.TestCase):
def test_only_tail_changes_and_cap_holds(self):
rng = random.Random(5)
s = 1000
raw = [rng.gauss(0.0, 1.5) for _ in range(s)]
lw, k = psis_smooth(raw)
top = max(raw)
m = tail_length(s)
order = sorted(range(s), key=lambda j: raw[j])
for j in order[: s - m]:
self.assertEqual(lw[j], raw[j] - top)
threshold = raw[order[s - m - 1]] - top
for j in order[s - m:]:
self.assertGreaterEqual(lw[j], threshold)
self.assertLessEqual(lw[j], 0.0)
self.assertTrue(math.isfinite(k))
def test_short_input_is_not_smoothed(self):
lw, k = psis_smooth([0.0, 1.0, 2.0])
self.assertEqual(lw, [-2.0, -1.0, 0.0])
self.assertEqual(k, math.inf)
class ConjugateNormal(unittest.TestCase):
"""y_i ~ N(theta, 1), theta ~ N(0, 100): leave-one-out has a closed form."""
def test_five_points(self):
ys = [0.5, 1.0, 2.0, 2.5, 4.0]
res = psis_loo(draws_matrix(ys, 4000, 1))
ex = exact_loo(ys)
for got, want in zip(res["pointwise"], ex):
self.assertLess(abs(got - want), 0.06)
self.assertLess(abs(res["elpd_loo"] - sum(ex)), 0.15)
self.assertEqual(res["flagged"], [])
self.assertAlmostEqual(res["looic"], -2 * res["elpd_loo"])
def test_no_outlier_no_flag(self):
rng = random.Random(7)
base = [round(rng.gauss(0.0, 1.0), 2) for _ in range(19)]
ys = base + [round(rng.gauss(0.0, 1.0), 2)]
res = psis_loo(draws_matrix(ys, 4000, 11))
self.assertEqual(res["flagged"], [])
self.assertLess(abs(res["elpd_loo"] - sum(exact_loo(ys))), 0.05)
def test_outlier_is_flagged(self):
ys = outlier_data(9.0)
res = psis_loo(draws_matrix(ys, 4000, 11))
self.assertIn(19, res["flagged"])
self.assertGreater(res["k_hat"][19], 0.7)
self.assertEqual(max(res["k_hat"][:19]) < 0.7, True)
def test_waic_against_closed_form(self):
ys = [0.5, 1.0, 2.0, 2.5, 4.0]
w = waic(draws_matrix(ys, 4000, 1))
lppd, p, elpd = exact_waic(ys)
self.assertLess(abs(w["lppd"] - lppd), 0.01)
self.assertLess(abs(w["p_waic"] - p), 0.1)
self.assertLess(abs(w["elpd_waic"] - elpd), 0.1)
self.assertAlmostEqual(w["waic"], -2 * w["elpd_waic"])
def test_waic_matches_its_definition(self):
ll = [[-1.0, -2.0, -3.0], [0.0, 0.0, 0.0]]
w = waic(ll)
lppd0 = math.log((math.exp(-1) + math.exp(-2) + math.exp(-3)) / 3)
self.assertAlmostEqual(w["lppd"], lppd0, places=12)
self.assertAlmostEqual(w["p_waic"], 1.0, places=12)
def test_unequal_rows_raise(self):
with self.assertRaises(ValueError):
psis_loo([[0.0] * 10, [0.0] * 9])
if __name__ == "__main__":
unittest.main()
History
Geisser and Eddy (1979) and Gelfand, Dey and Chang (1992) introduced predictive model checks from leave-one-out densities, and Gelfand and coauthors estimated them by importance sampling from the full posterior, which gives the harmonic mean formula of the identity. Epifani, MacEachern and Peruggia (2008) showed when the raw case-deletion weights have finite variance. Ionides (2008) proposed truncated importance sampling. Vehtari and Gelman posted Pareto smoothed importance sampling in 2015, Vehtari, Gelman and Gabry (2017) applied it to leave-one-out cross-validation and compared it with WAIC, and the full treatment with the threshold appeared in the Journal of Machine Learning Research in 2024. The R package loo and the Python package ArviZ implement it.
References
- Vehtari, Simpson, Gelman, Yao and Gabry 2024, Section 2.1 and Algorithm 1 (tail length M = floor(min(0.2 S, 3 sqrt(S))), the threshold, the quantiles at (z - 1/2)/M and the cap at the largest raw ratio); Section 3 (k-hat as a diagnostic, Eq. 13 for the threshold min(1 - 1/log10 S, 0.7)); Appendix G (shrinkage of k-hat toward 0.5); Appendix H (MCMC draws)
- Aki Vehtari, Andrew Gelman and Jonah Gabry, Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC, Statistics and Computing 27(5), 2017, pages 1413 to 1432 (PSIS-LOO, its standard error, p_loo, and the comparison with WAIC; general locator)
- Jin Zhang and Michael A. Stephens, A new and efficient estimation method for the generalized Pareto distribution, Technometrics 51(3), 2009, pages 316 to 325 (the profile likelihood in theta = -k/sigma, the grid of theta values and the weighted estimate; general locator)
- Gelfand, Dey and Chang 1992, the estimate of the leave-one-out predictive density by importance sampling from the full posterior (general locator)
- Epifani, MacEachern and Peruggia 2008, conditions under which the raw case-deletion importance weights have finite variance (general locator)
- Andrew Gelman, John B. Carlin, Hal S. Stern, David B. Dunson, Aki Vehtari and Donald B. Rubin, Bayesian Data Analysis, 3rd edition, CRC Press, 2013, Chapter 7, Sections 7.1 and 7.2 (log predictive density, leave-one-out cross-validation and WAIC)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag NR2Y7A Edit this page History Report an error Markdown