Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 nn times. It reuses one set of draws from the full posterior p(θ∣y)p(\theta \mid y) and gives each draw the importance ratio 1/p(yi∣θ)1/p(y_i \mid \theta). 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 k^\hat k tells the user when the estimate cannot be trusted. The cost is one sort per observation, Θ(nSlog⁡S)\Theta(n S \log S) for nn observations and SS 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 p(y∣θ)=∏i=1np(yi∣θ)p(y \mid \theta) = \prod_{i=1}^n p(y_i \mid \theta), so the observations are conditionally independent given θ\theta. Draws θ1,…,θS\theta^1, \ldots, \theta^S from the posterior p(θ∣y)p(\theta \mid y), for example from Hamiltonian Monte Carlo. The matrix ℓis=log⁡p(yi∣θs)\ell_{is} = \log p(y_i \mid \theta^s).

Output. An estimate of the expected log pointwise predictive density for new data,

elpdloo=∑i=1nlog⁡p(yi∣y−i),p(yi∣y−i)=∫p(yi∣θ) p(θ∣y−i) dθ,\mathrm{elpd}_{\mathrm{loo}} = \sum_{i=1}^n \log p(y_i \mid y_{-i}), \qquad p(y_i \mid y_{-i}) = \int p(y_i \mid \theta)\, p(\theta \mid y_{-i})\, d\theta,

where y−iy_{-i} is the data without point ii. Also its standard error, the effective number of parameters ploop_{\mathrm{loo}}, the shapes k^1,…,k^n\hat k_1, \ldots, \hat k_n, and the list of points whose k^i\hat k_i is too large.

The identity behind it. If p(yi∣θ)>0p(y_i \mid \theta) > 0 on the support of the posterior, then

p(yi∣y−i)=1E[ 1/p(yi∣θ)∣y ],p(y_i \mid y_{-i}) = \frac{1}{\mathbb{E}\big[\, 1/p(y_i \mid \theta) \mid y \,\big]},

so leave-one-out needs only expectations under the full posterior. With the ratios ris=1/p(yi∣θs)r_{is} = 1/p(y_i \mid \theta^s) this is importance sampling with the full posterior as the proposal and p(θ∣y−i)p(\theta \mid y_{-i}) 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).

  1. PSIS-LOO(ℓ) ▷ ℓ[i][s] = log p(yᵢ | θˢ), n rows, S draws from p(θ | y)
  2. 1M ← ⌊min(0.2 S, 3 √S)⌋ ▷ tail length
  3. 2for i ← 1 to n do
  4. 3ρₛ ← -ℓ[i][s] - maxₜ(-ℓ[i][t]) for every s ▷ log ratios, the largest is 0
  5. 4sort the draws by ρ; u ← exp(ρ at rank S - M) ▷ the threshold
  6. 5(k̂ᵢ, σ̂) ← GPD-FIT(exp(ρ) - u over the M largest draws)
  7. 6for z ← 1 to M do the z-th of the M largest draws gets weight min(u + F⁻¹((z - 1/2)/M; k̂ᵢ, σ̂), 1)
  8. 7the other S - M draws keep the weight exp(ρₛ); call all weights w̃ₛ
  9. 8eᵢ ← log Σₛ w̃ₛ exp(ℓ[i][s]) - log Σₛ w̃ₛ
  10. 9flagged ← { i : k̂ᵢ > min(1 - 1/log₁₀ S, 0.7) }
  11. 10elpd ← Σᵢ eᵢ
  12. 11se ← √(n · sample variance of e₁, ..., eₙ)
  13. 12return elpd, se, p_loo = Σᵢ log((1/S) Σₛ exp(ℓ[i][s])) - elpd, (k̂ᵢ), flagged
  14. GPD-FIT(x₁, ..., x_M) ▷ exceedances x ≥ 0, sorted, x_M > 0
  15. 13m ← 30 + ⌊√M⌋
  16. 14θⱼ ← 1/x_M + (1 - √(m/(j - 1/2)))/(3 x*) for j = 1, ..., m ▷ x* is the first quartile
  17. 15Lⱼ ← M (log(-θⱼ/κ(θⱼ)) - κ(θⱼ) - 1) with κ(θ) = (1/M) Σ log(1 - θ xₜ)
  18. 16πⱼ ← exp(Lⱼ) / Σₗ exp(Lₗ)
  19. 17θ̂ ← Σⱼ πⱼ θⱼ; k̂ ← κ(θ̂); σ̂ ← -k̂/θ̂
  20. 18k̂ ← (M k̂ + 10 · 0.5)/(M + 10); return (k̂, σ̂)

F−1(p;k,σ)=σ((1−p)−k−1)/kF^{-1}(p; k, \sigma) = \sigma\big((1 - p)^{-k} - 1\big)/k is the quantile function of the generalized Pareto law with location 00, shape kk and scale σ\sigma, and −σlog⁡(1−p)-\sigma \log(1 - p) when k=0k = 0. Line L3 shifts the log ratios so that the largest raw ratio is 11; this changes no estimate, because L8 is a ratio. Line L6 replaces the MM 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 θ=−k/σ\theta = -k/\sigma; L16 and L17 average it over a grid, which is more stable than its maximum. Line L18 pulls k^\hat k toward 0.50.5 with the weight of 10 observations, which helps when MM 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 M<5M < 5 or all exceedances are 00, the implementation skips the smoothing and reports k^i=∞\hat k_i = \infty, as the reference implementations do.

Example

Five points. The model is yi∼N(θ,1)y_i \sim N(\theta, 1) with prior θ∼N(0,100)\theta \sim N(0, 100), and the data are y=(0.5,1,2,2.5,4)y = (0.5, 1, 2, 2.5, 4). The posterior is N(1.996,0.1996)N(1.996, 0.1996). Leave-one-out has a closed form here: p(yi∣y−i)p(y_i \mid y_{-i}) is the normal density at yiy_i with the mean and variance of the posterior from the other four points, plus 11 for the noise. We take S=4000S = 4000 draws with random.Random(1), so L1 gives M=⌊min⁡(800,189.7)⌋=189M = \lfloor \min(800, 189.7) \rfloor = 189.

Trace for the last point, y5=4y_5 = 4:

  1. L3 and L4: the threshold is u=0.1324u = 0.1324 times the largest ratio.
  2. L5: GPD-FIT on the 189189 exceedances gives k^5=0.421\hat k_5 = 0.421 and σ^=0.0723\hat\sigma = 0.0723.
  3. L6: the three largest ratios were 0.9260.926, 0.9850.985 and 11; after smoothing all three are at the cap 11. Kong's effective sample size of the weights goes from 11271127 to 11481148.
  4. L8: e5=−3.5044e_5 = -3.5044. Raw importance sampling gives −3.5076-3.5076, and the exact value is −3.5390-3.5390.
ii yiy_i k^i\hat k_i PSIS eie_i exact log⁡p(yi∣y−i)\log p(y_i \mid y_{-i})
1 0.5 0.352 −2.4210-2.4210 −2.4283-2.4283
2 1.0 0.292 −1.6476-1.6476 −1.6500-1.6500
3 2.0 0.165 −1.0279-1.0279 −1.0303-1.0303
4 2.5 0.235 −1.1831-1.1831 −1.1889-1.1889
5 4.0 0.421 −3.5044-3.5044 −3.5390-3.5390
sum −9.784-9.784 −9.8365-9.8365

L12 gives ploo=1.607p_{\mathrm{loo}} = 1.607. No point is flagged. All five errors have the same sign, because they use the same draws. WAIC from the same draws gives elpdwaic=−9.746\mathrm{elpd}_{\mathrm{waic}} = -9.746.

One outlier. Take 19 points from random.Random(7) (standard normal, rounded to 2 decimals) and add a last point y20y_{20}. The draws use random.Random(11), S=4000S = 4000.

y20y_{20} k^20\hat k_{20} flagged PSIS e20e_{20} exact e20e_{20} PSIS elpd exact elpd
a 20th normal point 0.077 none −26.649-26.649 −26.640-26.640
4 0.394 none −35.048-35.048 −35.037-35.037
6 0.564 none −45.276-45.276 −45.264-45.264
9 0.827 point 20 −40.367-40.367 −40.398-40.398 −68.104-68.104 −68.105-68.105
15 1.358 point 20 −109.110-109.110 −109.448-109.448 −140.493-140.493 −140.785-140.785

At y20=15y_{20} = 15 the error is 0.340.34 nats, and raw importance sampling (−109.117-109.117) is no better. Exact refitting is the fix. In this model the true tail of the ratios is light: r∝exp⁡((yi−θ)2/2)r \propto \exp((y_i - \theta)^2/2) with θ∼N(m,v)\theta \sim N(m, v) has finite moments of every order below 1/v≈201/v \approx 20. The large k^\hat k 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 0.80.8 or 1.41.4. This is what the diagnostic is meant to report.

Correctness

Four facts, proved in proofs/correctness.md:

  1. The identity. p(yi∣y−i)=1/E[1/p(yi∣θ)∣y]p(y_i \mid y_{-i}) = 1/\mathbb{E}[1/p(y_i \mid \theta) \mid y] when the observations are conditionally independent given θ\theta and p(yi∣θ)>0p(y_i \mid \theta) > 0 on the support of the posterior. In particular E[1/p(yi∣θ)∣y]\mathbb{E}[1/p(y_i \mid \theta) \mid y] 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.
  2. 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).
  3. Smoothing keeps the order and the cap. Only the MM largest ratios change; they stay in the same order, at least uu and at most the largest raw ratio.
  4. L15 is the profile likelihood. For a fixed θ=−k/σ\theta = -k/\sigma the generalized Pareto log-likelihood is maximized at k=κ(θ)k = \kappa(\theta), and its value there is L(θ)L(\theta) 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 SS grows, and that it is reliable when k^<min⁡(1−1/log⁡10S,0.7)\hat k < \min(1 - 1/\log_{10} S, 0.7) (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 p(y∣θ)=∏ip(yi∣θ)p(y \mid \theta) = \prod_i p(y_i \mid \theta), a prior p(θ)p(\theta), and posterior p(θ∣y)∝p(θ)p(y∣θ)p(\theta \mid y) \propto p(\theta) p(y \mid \theta). Write y−iy_{-i} for the data without point ii.

Claim 1 (the identity). Assume p(yi∣θ)>0p(y_i \mid \theta) > 0 for every θ\theta in the support of p(θ∣y−i)p(\theta \mid y_{-i}). Then

E[1p(yi∣θ) ∣ y]=1p(yi∣y−i).\mathbb{E}\Big[\frac{1}{p(y_i \mid \theta)} \,\Big|\, y\Big] = \frac{1}{p(y_i \mid y_{-i})}.

Proof. Conditional independence gives p(y∣θ)=p(yi∣θ) p(y−i∣θ)p(y \mid \theta) = p(y_i \mid \theta)\, p(y_{-i} \mid \theta). By Bayes's theorem applied twice,

p(θ∣y)=p(θ) p(y−i∣θ) p(yi∣θ)p(y)=p(θ∣y−i) p(yi∣θ)p(yi∣y−i),p(\theta \mid y) = \frac{p(\theta)\, p(y_{-i} \mid \theta)\, p(y_i \mid \theta)}{p(y)} = \frac{p(\theta \mid y_{-i})\, p(y_i \mid \theta)}{p(y_i \mid y_{-i})},

because p(θ)p(y−i∣θ)=p(θ∣y−i)p(y−i)p(\theta)p(y_{-i} \mid \theta) = p(\theta \mid y_{-i}) p(y_{-i}) and p(y)/p(y−i)=p(yi∣y−i)p(y)/p(y_{-i}) = p(y_i \mid y_{-i}). Multiply by 1/p(yi∣θ)1/p(y_i \mid \theta) and integrate over θ\theta:

∫p(θ∣y)p(yi∣θ) dθ=1p(yi∣y−i)∫p(θ∣y−i) dθ=1p(yi∣y−i).\int \frac{p(\theta \mid y)}{p(y_i \mid \theta)}\, d\theta = \frac{1}{p(y_i \mid y_{-i})} \int p(\theta \mid y_{-i})\, d\theta = \frac{1}{p(y_i \mid y_{-i})}.

The positivity assumption makes the division valid on the support of p(θ∣y−i)p(\theta \mid y_{-i}), and p(θ∣y)p(\theta \mid y) is zero wherever p(yi∣θ)=0p(y_i \mid \theta) = 0. □\square

The same computation with a function gg gives the importance sampling identity

E[g(θ)∣y−i]=E[g(θ) ri(θ)∣y]E[ri(θ)∣y],ri(θ)=1p(yi∣θ),\mathbb{E}[g(\theta) \mid y_{-i}] = \frac{\mathbb{E}[g(\theta)\, r_i(\theta) \mid y]}{\mathbb{E}[r_i(\theta) \mid y]}, \qquad r_i(\theta) = \frac{1}{p(y_i \mid \theta)},

so rir_i is the importance ratio from the proposal p(θ∣y)p(\theta \mid y) to the target p(θ∣y−i)p(\theta \mid y_{-i}), up to a constant.

Claim 2 (raw importance sampling is consistent). Let θ1,θ2,…\theta^1, \theta^2, \ldots be independent draws from p(θ∣y)p(\theta \mid y). Then S/∑s=1Sri(θs)→p(yi∣y−i)S / \sum_{s=1}^S r_i(\theta^s) \to p(y_i \mid y_{-i}) almost surely.

Proof. By Claim 1, E[ri(θ)∣y]=1/p(yi∣y−i)\mathbb{E}[r_i(\theta) \mid y] = 1/p(y_i \mid y_{-i}), which is finite and positive. The strong law of large numbers gives 1S∑sri(θs)→1/p(yi∣y−i)\frac1S \sum_s r_i(\theta^s) \to 1/p(y_i \mid y_{-i}) almost surely, and x↦1/xx \mapsto 1/x is continuous at a positive limit. □\square

With raw weights w~s=ri(θs)\tilde w_s = r_i(\theta^s), line L8 computes log⁡∑sri(θs)p(yi∣θs)−log⁡∑sri(θs)=log⁡S−log⁡∑sri(θs)\log \sum_s r_i(\theta^s) p(y_i \mid \theta^s) - \log \sum_s r_i(\theta^s) = \log S - \log \sum_s r_i(\theta^s), 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: E[ri2∣y]\mathbb{E}[r_i^2 \mid y] can be infinite, and then the central limit theorem fails and the error decreases more slowly than 1/S1/\sqrt S. This is the reason for the smoothing.

Claim 3 (the code is Algorithm 1). Line L1 computes M=⌊min⁡(0.2S,3S)⌋M = \lfloor \min(0.2 S, 3\sqrt S) \rfloor. Line L3 computes ρs=log⁡ri(θs)−max⁡tlog⁡ri(θt)\rho_s = \log r_i(\theta^s) - \max_t \log r_i(\theta^t), so exp⁡(ρs)=ri(θs)/max⁡tri(θt)\exp(\rho_s) = r_i(\theta^s)/\max_t r_i(\theta^t); a common factor cancels in L8. Line L4 sorts and sets uu to the ratio of rank S−MS - M, so the MM draws of ranks S−M+1,…,SS - M + 1, \ldots, S form the tail and exp⁡(ρ)−u≥0\exp(\rho) - u \ge 0 on the tail. Line L5 fits the generalized Pareto law to these exceedances. Line L6 gives the draw of rank S−M+zS - M + z the weight min⁡(u+F−1((z−1/2)/M),1)\min(u + F^{-1}((z - 1/2)/M), 1), and 11 is the largest raw ratio after the shift. Line L9 uses the threshold min⁡(1−1/log⁡10S,0.7)\min(1 - 1/\log_{10} S, 0.7). 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 n\sqrt{n} times their sample standard deviation, and L12 computes ploo=lppd−elpdloop_{\mathrm{loo}} = \mathrm{lppd} - \mathrm{elpd}_{\mathrm{loo}} with lppd=∑ilog⁡1S∑sp(yi∣θs)\mathrm{lppd} = \sum_i \log \frac1S \sum_s p(y_i \mid \theta^s). □\square

Claim 4 (order and cap). After L6 and L7, the S−MS - M smallest weights are unchanged, and the MM tail weights are nondecreasing in the rank and lie in [u,1][u, 1].

Proof. Lines L6 and L7 change only the draws of ranks S−M+1S - M + 1 to SS. For k≠0k \ne 0 and σ>0\sigma > 0 the function p↦F−1(p;k,σ)=σ((1−p)−k−1)/kp \mapsto F^{-1}(p; k, \sigma) = \sigma((1 - p)^{-k} - 1)/k has derivative σ(1−p)−k−1>0\sigma (1 - p)^{-k - 1} > 0 on [0,1)[0, 1), and F−1(0)=0F^{-1}(0) = 0; the case k=0k = 0 is −σlog⁡(1−p)-\sigma \log(1 - p), also increasing with value 00 at 00. The points (z−1/2)/M(z - 1/2)/M increase with zz and lie in (0,1)(0, 1). So u+F−1((z−1/2)/M)u + F^{-1}((z - 1/2)/M) is at least uu and increases with zz, and the minimum with 11 keeps both facts and adds the upper bound. The draw of rank S−M+zS - M + z gets the zz-th value, so the order of the draws is kept. Since the largest raw ratio is 11 and u≤1u \le 1, every weight lies in [0,1][0, 1]. □\square

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 00, shape k≠0k \ne 0 and scale σ>0\sigma > 0 has density 1σ(1+kx/σ)−1/k−1\frac1\sigma (1 + kx/\sigma)^{-1/k - 1} on its support. For exceedances x1,…,xMx_1, \ldots, x_M and fixed θ=−k/σ\theta = -k/\sigma with 1−θxt>01 - \theta x_t > 0 for all tt and κ(θ)≠0\kappa(\theta) \ne 0, the maximum of the log-likelihood over kk is M(log⁡(−θ/κ(θ))−κ(θ)−1)M(\log(-\theta/\kappa(\theta)) - \kappa(\theta) - 1), attained at k=κ(θ)=1M∑tlog⁡(1−θxt)k = \kappa(\theta) = \frac1M \sum_t \log(1 - \theta x_t).

Proof. With σ=−k/θ\sigma = -k/\theta we have 1+kx/σ=1−θx1 + kx/\sigma = 1 - \theta x, so the log-likelihood is

ℓ(k)=−Mlog⁡(−kθ)−(1k+1)Mκ(θ).\ell(k) = -M \log\Big(-\frac{k}{\theta}\Big) - \Big(\frac1k + 1\Big) M \kappa(\theta).

Here kk and θ\theta have opposite signs because σ>0\sigma > 0. The derivative in kk is −M/k+Mκ(θ)/k2-M/k + M\kappa(\theta)/k^2, which is zero only at k=κ(θ)k = \kappa(\theta). On the side of 00 where kθ<0k\theta < 0 the second term dominates near 00 and the first term dominates at infinity, so this point is the maximum. Substituting k=κ(θ)k = \kappa(\theta) gives −Mlog⁡(−κ/θ)−M−Mκ=M(log⁡(−θ/κ)−κ−1)-M\log(-\kappa/\theta) - M - M\kappa = M(\log(-\theta/\kappa) - \kappa - 1). □\square

The grid of L14 satisfies θj<1/xM\theta_j < 1/x_M, because m/(j−1/2)>1\sqrt{m/(j - 1/2)} > 1 for j≤mj \le m. So 1−θjxt>01 - \theta_j x_t > 0 for every exceedance, and L15 is defined. Lines L16 and L17 average θ\theta 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 S→∞S \to \infty, and that its error is small when the true tail shape is below about 0.70.7. 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 nn rows: L3 is Θ(S)\Theta(S), the sort in L4 is Θ(Slog⁡S)\Theta(S \log S), GPD-FIT costs Θ(M(30+M))=O(S)\Theta(M (30 + \sqrt M)) = O(S) because M≤3SM \le 3\sqrt S, and L6 to L8 are Θ(S)\Theta(S). The total is Θ(nSlog⁡S)\Theta(n S \log S) in the best and the worst case. A selection of the MM largest ratios instead of a full sort lowers this to Θ(nS)\Theta(n S) expected time. Extra space is Θ(S)\Theta(S) for one row of weights plus Θ(n)\Theta(n) for the outputs. The input matrix itself has nSnS entries, and computing it costs nSnS likelihood evaluations, which usually dominates. Exact leave-one-out would cost nn extra posterior fits.

Properties

  • Deterministic given the draws. All randomness is in the posterior draws.
  • Not exact. It is a Monte Carlo estimate of elpdloo\mathrm{elpd}_{\mathrm{loo}}. Each eie_i is biased upward for finite SS, because log⁡\log is concave (Jensen's inequality); the bias falls like 1/S1/S 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. k^i\hat k_i is computed for every point at no extra cost. A large k^i\hat k_i 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 elpd\mathrm{elpd} 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 3S/Reff3\sqrt{S/R_{\mathrm{eff}}} in the tail length, where ReffR_{\mathrm{eff}} 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 S\sqrt S 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 k^\hat k 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 elpdloo\mathrm{elpd}_{\mathrm{loo}} 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 k^\hat k 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 k^\hat k. A large k^\hat k 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 SS the tail has few draws, the threshold falls (it is 0.50.5 at S=100S = 100), and the estimate is noisy.
  • The wrong unit. Hierarchical models with one observation per group can have large k^\hat k 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 exp⁡(100)\exp(100) are common.
  • Small differences. A difference of elpd\mathrm{elpd} 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.

pareto_smoothed_importance_sampling_loo.pyI0RawGitHub
# 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 min⁡(1−1/log⁡10S,0.7)\min(1 - 1/\log_{10} S, 0.7) appeared in the Journal of Machine Learning Research in 2024. The R package loo and the Python package ArviZ implement it.

References

  1. 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)
  2. 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)
  3. 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)
  4. Gelfand, Dey and Chang 1992, the estimate of the leave-one-out predictive density by importance sampling from the full posterior (general locator)
  5. Epifani, MacEachern and Peruggia 2008, conditions under which the raw case-deletion importance weights have finite variance (general locator)
  6. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example