|
| 1 | +""" |
| 2 | +This module provides functions for computing distances between observation samples and reference samples with distance |
| 3 | +distributions within the reference samples for hypothesis testing. |
| 4 | +""" |
| 5 | + |
| 6 | +from collections.abc import Mapping, Callable |
| 7 | + |
| 8 | +import numpy as np |
| 9 | +from keras.ops import convert_to_numpy, convert_to_tensor |
| 10 | + |
| 11 | +from bayesflow.approximators import ContinuousApproximator |
| 12 | +from bayesflow.metrics.functional import maximum_mean_discrepancy |
| 13 | +from bayesflow.types import Tensor |
| 14 | + |
| 15 | + |
| 16 | +def bootstrap_comparison( |
| 17 | + observed_samples: np.ndarray, |
| 18 | + reference_samples: np.ndarray, |
| 19 | + comparison_fn: Callable[[Tensor, Tensor], Tensor], |
| 20 | + num_null_samples: int = 100, |
| 21 | +) -> tuple[float, np.ndarray]: |
| 22 | + """Computes the distance between observed and reference samples and generates a distribution of null sample |
| 23 | + distances by bootstrapping for hypothesis testing. |
| 24 | +
|
| 25 | + Parameters |
| 26 | + ---------- |
| 27 | + observed_samples : np.ndarray) |
| 28 | + Observed samples, shape (num_observed, ...). |
| 29 | + reference_samples : np.ndarray |
| 30 | + Reference samples, shape (num_reference, ...). |
| 31 | + comparison_fn : Callable[[Tensor, Tensor], Tensor] |
| 32 | + Function to compute the distance metric. |
| 33 | + num_null_samples : int |
| 34 | + Number of null samples to generate for hypothesis testing. Default is 100. |
| 35 | +
|
| 36 | + Returns |
| 37 | + ------- |
| 38 | + distance_observed : float |
| 39 | + The distance value between observed and reference samples. |
| 40 | + distance_null : np.ndarray |
| 41 | + A distribution of distance values under the null hypothesis. |
| 42 | +
|
| 43 | + Raises |
| 44 | + ------ |
| 45 | + ValueError |
| 46 | + - If the number of number of observed samples exceeds the number of reference samples |
| 47 | + - If the shapes of observed and reference samples do not match on dimensions besides the first one. |
| 48 | + """ |
| 49 | + num_observed: int = observed_samples.shape[0] |
| 50 | + num_reference: int = reference_samples.shape[0] |
| 51 | + |
| 52 | + if num_observed > num_reference: |
| 53 | + raise ValueError( |
| 54 | + f"Number of observed samples ({num_observed}) cannot exceed" |
| 55 | + f"the number of reference samples ({num_reference}) for bootstrapping." |
| 56 | + ) |
| 57 | + if observed_samples.shape[1:] != reference_samples.shape[1:]: |
| 58 | + raise ValueError( |
| 59 | + f"Expected observed and reference samples to have the same shape, " |
| 60 | + f"but got {observed_samples.shape[1:]} != {reference_samples.shape[1:]}." |
| 61 | + ) |
| 62 | + |
| 63 | + observed_samples_tensor: Tensor = convert_to_tensor(observed_samples, dtype="float32") |
| 64 | + reference_samples_tensor: Tensor = convert_to_tensor(reference_samples, dtype="float32") |
| 65 | + |
| 66 | + distance_null_samples: np.ndarray = np.zeros(num_null_samples, dtype=np.float64) |
| 67 | + for i in range(num_null_samples): |
| 68 | + bootstrap_idx: np.ndarray = np.random.randint(0, num_reference, size=num_observed) |
| 69 | + bootstrap_samples: np.ndarray = reference_samples[bootstrap_idx] |
| 70 | + bootstrap_samples_tensor: Tensor = convert_to_tensor(bootstrap_samples, dtype="float32") |
| 71 | + distance_null_samples[i] = convert_to_numpy(comparison_fn(bootstrap_samples_tensor, reference_samples_tensor)) |
| 72 | + |
| 73 | + distance_observed_tensor: Tensor = comparison_fn( |
| 74 | + observed_samples_tensor, |
| 75 | + reference_samples_tensor, |
| 76 | + ) |
| 77 | + |
| 78 | + distance_observed: float = float(convert_to_numpy(distance_observed_tensor)) |
| 79 | + |
| 80 | + return distance_observed, distance_null_samples |
| 81 | + |
| 82 | + |
| 83 | +def summary_space_comparison( |
| 84 | + observed_data: Mapping[str, np.ndarray], |
| 85 | + reference_data: Mapping[str, np.ndarray], |
| 86 | + approximator: ContinuousApproximator, |
| 87 | + num_null_samples: int = 100, |
| 88 | + comparison_fn: Callable = maximum_mean_discrepancy, |
| 89 | + **kwargs, |
| 90 | +) -> tuple[float, np.ndarray]: |
| 91 | + """Computes the distance between observed and reference data in the summary space and |
| 92 | + generates a distribution of distance values under the null hypothesis to assess model misspecification. |
| 93 | +
|
| 94 | + By default, the Maximum Mean Discrepancy (MMD) is used as a distance function. |
| 95 | +
|
| 96 | + [1] M. Schmitt, P.-C. Bürkner, U. Köthe, and S. T. Radev, "Detecting model misspecification in amortized Bayesian |
| 97 | + inference with neural networks," arXiv e-prints, Dec. 2021, Art. no. arXiv:2112.08866. |
| 98 | + URL: https://arxiv.org/abs/2112.08866 |
| 99 | +
|
| 100 | + Parameters |
| 101 | + ---------- |
| 102 | + observed_data : dict[str, np.ndarray] |
| 103 | + Dictionary of observed data as NumPy arrays, which will be preprocessed by the approximators adapter and passed |
| 104 | + through its summary network. |
| 105 | + reference_data : dict[str, np.ndarray] |
| 106 | + Dictionary of reference data as NumPy arrays, which will be preprocessed by the approximators adapter and passed |
| 107 | + through its summary network. |
| 108 | + approximator : ContinuousApproximator |
| 109 | + An instance of :py:class:`~bayesflow.approximators.ContinuousApproximator` used to compute summary statistics |
| 110 | + from the data. |
| 111 | + num_null_samples : int, optional |
| 112 | + Number of null samples to generate for hypothesis testing. Default is 100. |
| 113 | + comparison_fn : Callable, optional |
| 114 | + Distance function to compare the data in the summary space. |
| 115 | + **kwargs : dict |
| 116 | + Additional keyword arguments for the adapter and sampling process. |
| 117 | +
|
| 118 | + Returns |
| 119 | + ------- |
| 120 | + distance_observed : float |
| 121 | + The MMD value between observed and reference summaries. |
| 122 | + distance_null : np.ndarray |
| 123 | + A distribution of MMD values under the null hypothesis. |
| 124 | +
|
| 125 | + Raises |
| 126 | + ------ |
| 127 | + ValueError |
| 128 | + If approximator is not an instance of ContinuousApproximator or does not have a summary network. |
| 129 | + """ |
| 130 | + |
| 131 | + if not isinstance(approximator, ContinuousApproximator): |
| 132 | + raise ValueError("The approximator must be an instance of ContinuousApproximator.") |
| 133 | + |
| 134 | + if not hasattr(approximator, "summary_network") or approximator.summary_network is None: |
| 135 | + comparison_fn_name = ( |
| 136 | + "bayesflow.metrics.functional.maximum_mean_discrepancy" |
| 137 | + if comparison_fn is maximum_mean_discrepancy |
| 138 | + else comparison_fn.__name__ |
| 139 | + ) |
| 140 | + raise ValueError( |
| 141 | + "The approximator must have a summary network. If you have manually crafted summary " |
| 142 | + "statistics, or want to compare raw data and not summary statistics, please use the " |
| 143 | + f"`bootstrap_comparison` function with `comparison_fn={comparison_fn_name}` on the respective arrays." |
| 144 | + ) |
| 145 | + observed_summaries = convert_to_numpy(approximator.summaries(observed_data)) |
| 146 | + reference_summaries = convert_to_numpy(approximator.summaries(reference_data)) |
| 147 | + |
| 148 | + distance_observed, distance_null = bootstrap_comparison( |
| 149 | + observed_samples=observed_summaries, |
| 150 | + reference_samples=reference_summaries, |
| 151 | + comparison_fn=comparison_fn, |
| 152 | + num_null_samples=num_null_samples, |
| 153 | + ) |
| 154 | + |
| 155 | + return distance_observed, distance_null |
0 commit comments