|
| 1 | +from collections.abc import Mapping, Sequence |
| 2 | + |
| 3 | +import numpy as np |
| 4 | +from scipy.stats import binom |
| 5 | + |
| 6 | +from ...utils.dict_utils import dicts_to_arrays |
| 7 | + |
| 8 | + |
| 9 | +def calibration_log_gamma( |
| 10 | + estimates: Mapping[str, np.ndarray] | np.ndarray, |
| 11 | + targets: Mapping[str, np.ndarray] | np.ndarray, |
| 12 | + variable_keys: Sequence[str] = None, |
| 13 | + variable_names: Sequence[str] = None, |
| 14 | + num_null_draws: int = 1000, |
| 15 | + quantile: float = 0.05, |
| 16 | +): |
| 17 | + """ |
| 18 | + Compute the log gamma discrepancy statistic to test posterior calibration, |
| 19 | + see [1] for additional information. |
| 20 | + Log gamma is log(gamma/gamma_null), where gamma_null is the 5th percentile of the |
| 21 | + null distribution under uniformity of ranks. |
| 22 | + That is, if adopting a hypothesis testing framework,then log_gamma < 0 implies |
| 23 | + a rejection of the hypothesis of uniform ranks at the 5% level. |
| 24 | + This diagnostic is typically more sensitive than the Kolmogorov-Smirnoff test or |
| 25 | + ChiSq test. |
| 26 | +
|
| 27 | + [1] Martin Modrák. Angie H. Moon. Shinyoung Kim. Paul Bürkner. Niko Huurre. |
| 28 | + Kateřina Faltejsková. Andrew Gelman. Aki Vehtari. |
| 29 | + "Simulation-Based Calibration Checking for Bayesian Computation: |
| 30 | + The Choice of Test Quantities Shapes Sensitivity." |
| 31 | + Bayesian Anal. 20 (2) 461 - 488, June 2025. https://doi.org/10.1214/23-BA1404 |
| 32 | +
|
| 33 | + Parameters |
| 34 | + ---------- |
| 35 | + estimates : np.ndarray of shape (num_datasets, num_draws, num_variables) |
| 36 | + The random draws from the approximate posteriors over ``num_datasets`` |
| 37 | + targets : np.ndarray of shape (num_datasets, num_variables) |
| 38 | + The corresponding ground-truth values sampled from the prior |
| 39 | + variable_keys : Sequence[str], optional (default = None) |
| 40 | + Select keys from the dictionaries provided in estimates and targets. |
| 41 | + By default, select all keys. |
| 42 | + variable_names : Sequence[str], optional (default = None) |
| 43 | + Optional variable names to show in the output. |
| 44 | + quantile : float in (0, 1), optional, default 0.05 |
| 45 | + The quantile from the null distribution to be used as a threshold. |
| 46 | + A lower quantile increases sensitivity to deviations from uniformity. |
| 47 | +
|
| 48 | + Returns |
| 49 | + ------- |
| 50 | + result : dict |
| 51 | + Dictionary containing: |
| 52 | +
|
| 53 | + - "values" : float or np.ndarray |
| 54 | + The log gamma values per variable |
| 55 | + - "metric_name" : str |
| 56 | + The name of the metric ("Log Gamma"). |
| 57 | + - "variable_names" : str |
| 58 | + The (inferred) variable names. |
| 59 | + """ |
| 60 | + samples = dicts_to_arrays( |
| 61 | + estimates=estimates, |
| 62 | + targets=targets, |
| 63 | + variable_keys=variable_keys, |
| 64 | + variable_names=variable_names, |
| 65 | + ) |
| 66 | + |
| 67 | + num_ranks = samples["estimates"].shape[0] |
| 68 | + num_post_draws = samples["estimates"].shape[1] |
| 69 | + |
| 70 | + # rank statistics |
| 71 | + ranks = np.sum(samples["estimates"] < samples["targets"][:, None], axis=1) |
| 72 | + |
| 73 | + # null distribution and threshold |
| 74 | + null_distribution = gamma_null_distribution(num_ranks, num_post_draws, num_null_draws) |
| 75 | + null_quantile = np.quantile(null_distribution, quantile) |
| 76 | + |
| 77 | + # compute log gamma for each parameter |
| 78 | + log_gammas = np.empty(ranks.shape[-1]) |
| 79 | + |
| 80 | + for i in range(ranks.shape[-1]): |
| 81 | + gamma = gamma_discrepancy(ranks[:, i], num_post_draws=num_post_draws) |
| 82 | + log_gammas[i] = np.log(gamma / null_quantile) |
| 83 | + |
| 84 | + output = { |
| 85 | + "values": log_gammas, |
| 86 | + "metric_name": "Log Gamma", |
| 87 | + "variable_names": samples["estimates"].variable_names, |
| 88 | + } |
| 89 | + |
| 90 | + return output |
| 91 | + |
| 92 | + |
| 93 | +def gamma_null_distribution(num_ranks: int, num_post_draws: int = 1000, num_null_draws: int = 1000) -> np.ndarray: |
| 94 | + """ |
| 95 | + Computes the distribution of expected gamma values under uniformity of ranks. |
| 96 | +
|
| 97 | + Parameters |
| 98 | + ---------- |
| 99 | + num_ranks : int |
| 100 | + Number of ranks to use for each gamma. |
| 101 | + num_post_draws : int, optional, default 1000 |
| 102 | + Number of posterior draws that were used to calculate the rank distribution. |
| 103 | + num_null_draws : int, optional, default 1000 |
| 104 | + Number of returned gamma values under uniformity of ranks. |
| 105 | +
|
| 106 | + Returns |
| 107 | + ------- |
| 108 | + result : np.ndarray |
| 109 | + Array of shape (num_null_draws,) containing gamma values under uniformity of ranks. |
| 110 | + """ |
| 111 | + z_i = np.arange(1, num_post_draws + 2) / (num_post_draws + 1) |
| 112 | + gamma = np.empty(num_null_draws) |
| 113 | + |
| 114 | + # loop non-vectorized to reduce memory footprint |
| 115 | + for i in range(num_null_draws): |
| 116 | + u = np.random.uniform(size=num_ranks) |
| 117 | + F_z = np.mean(u[:, None] < z_i, axis=0) |
| 118 | + bin_1 = binom.cdf(num_ranks * F_z, num_ranks, z_i) |
| 119 | + bin_2 = 1 - binom.cdf(num_ranks * F_z - 1, num_ranks, z_i) |
| 120 | + |
| 121 | + gamma[i] = 2 * np.min(np.minimum(bin_1, bin_2)) |
| 122 | + |
| 123 | + return gamma |
| 124 | + |
| 125 | + |
| 126 | +def gamma_discrepancy(ranks: np.ndarray, num_post_draws: int = 100) -> float: |
| 127 | + """ |
| 128 | + Quantifies deviation from uniformity by the likelihood of observing the |
| 129 | + most extreme point on the empirical CDF of the given rank distribution |
| 130 | + according to [1] (equation 7). |
| 131 | +
|
| 132 | + [1] Martin Modrák. Angie H. Moon. Shinyoung Kim. Paul Bürkner. Niko Huurre. |
| 133 | + Kateřina Faltejsková. Andrew Gelman. Aki Vehtari. |
| 134 | + "Simulation-Based Calibration Checking for Bayesian Computation: |
| 135 | + The Choice of Test Quantities Shapes Sensitivity." |
| 136 | + Bayesian Anal. 20 (2) 461 - 488, June 2025. https://doi.org/10.1214/23-BA1404 |
| 137 | +
|
| 138 | + Parameters |
| 139 | + ---------- |
| 140 | + ranks : array of shape (num_ranks,) |
| 141 | + Empirical rank distribution |
| 142 | + num_post_draws : int, optional, default 100 |
| 143 | + Number of posterior draws used to generate ranks. |
| 144 | +
|
| 145 | + Returns |
| 146 | + ------- |
| 147 | + result : float |
| 148 | + Gamma discrepancy values for each parameter. |
| 149 | + """ |
| 150 | + num_ranks = len(ranks) |
| 151 | + |
| 152 | + # observed count of ranks smaller than i |
| 153 | + R_i = np.array([sum(ranks < i) for i in range(1, num_post_draws + 2)]) |
| 154 | + |
| 155 | + # expected proportion of ranks smaller than i |
| 156 | + z_i = np.arange(1, num_post_draws + 2) / (num_post_draws + 1) |
| 157 | + |
| 158 | + bin_1 = binom.cdf(R_i, num_ranks, z_i) |
| 159 | + bin_2 = 1 - binom.cdf(R_i - 1, num_ranks, z_i) |
| 160 | + |
| 161 | + # likelihood of obtaining the most extreme point on the empirical CDF |
| 162 | + # if the rank distribution was indeed uniform |
| 163 | + return float(2 * np.min(np.minimum(bin_1, bin_2))) |
0 commit comments