|
| 1 | +import keras |
| 2 | +import numpy as np |
| 3 | +from keras.saving import ( |
| 4 | + register_keras_serializable as serializable, |
| 5 | +) |
| 6 | + |
| 7 | +from bayesflow.types import Tensor |
| 8 | +from bayesflow.utils import filter_kwargs, split_arrays, squeeze_inner_estimates_dict |
| 9 | +from .continuous_approximator import ContinuousApproximator |
| 10 | + |
| 11 | + |
| 12 | +@serializable(package="bayesflow.approximators") |
| 13 | +class PointApproximator(ContinuousApproximator): |
| 14 | + """ |
| 15 | + A workflow for fast amortized point estimation of a conditional distribution. |
| 16 | +
|
| 17 | + The distribution is approximated by point estimators, parameterized by a feed-forward `PointInferenceNetwork`. |
| 18 | + Conditions can be compressed by an optional `SummaryNetwork` or used directly as input to the inference network. |
| 19 | + """ |
| 20 | + |
| 21 | + def estimate( |
| 22 | + self, |
| 23 | + conditions: dict[str, np.ndarray], |
| 24 | + split: bool = False, |
| 25 | + **kwargs, |
| 26 | + ) -> dict[str, dict[str, np.ndarray]]: |
| 27 | + conditions = self._prepare_conditions(conditions, **kwargs) |
| 28 | + estimates = self._estimate(**conditions, **kwargs) |
| 29 | + estimates = self._apply_inverse_adapter_to_estimates(estimates, **kwargs) |
| 30 | + # Optionally split the arrays along the last axis. |
| 31 | + if split: |
| 32 | + estimates = split_arrays(estimates, axis=-1) |
| 33 | + # Reorder the nested dictionary so that original variable names are at the top. |
| 34 | + estimates = self._reorder_estimates(estimates) |
| 35 | + # Remove unnecessary nesting. |
| 36 | + estimates = self._squeeze_estimates(estimates) |
| 37 | + |
| 38 | + return estimates |
| 39 | + |
| 40 | + def sample( |
| 41 | + self, |
| 42 | + *, |
| 43 | + num_samples: int, |
| 44 | + conditions: dict[str, np.ndarray], |
| 45 | + split: bool = False, |
| 46 | + **kwargs, |
| 47 | + ) -> dict[str, np.ndarray]: |
| 48 | + conditions = self._prepare_conditions(conditions, **kwargs) |
| 49 | + samples = self._sample(num_samples, **conditions, **kwargs) |
| 50 | + samples = self._apply_inverse_adapter_to_samples(samples, **kwargs) |
| 51 | + # Optionally split the arrays along the last axis. |
| 52 | + if split: |
| 53 | + samples = split_arrays(samples, axis=-1) |
| 54 | + # Squeeze samples if there's only one key-value pair. |
| 55 | + samples = self._squeeze_samples(samples) |
| 56 | + |
| 57 | + return samples |
| 58 | + |
| 59 | + def _prepare_conditions(self, conditions: dict[str, np.ndarray], **kwargs) -> dict[str, Tensor]: |
| 60 | + """Adapts and converts the conditions to tensors.""" |
| 61 | + conditions = self.adapter(conditions, strict=False, stage="inference", **kwargs) |
| 62 | + return keras.tree.map_structure(keras.ops.convert_to_tensor, conditions) |
| 63 | + |
| 64 | + def _apply_inverse_adapter_to_estimates( |
| 65 | + self, estimates: dict[str, dict[str, Tensor]], **kwargs |
| 66 | + ) -> dict[str, dict[str, dict[str, np.ndarray]]]: |
| 67 | + """Applies the inverse adapter on each inner element of the _estimate output dictionary.""" |
| 68 | + estimates = keras.tree.map_structure(keras.ops.convert_to_numpy, estimates) |
| 69 | + processed = {} |
| 70 | + for score_key, score_val in estimates.items(): |
| 71 | + processed[score_key] = {} |
| 72 | + for head_key, estimate in score_val.items(): |
| 73 | + adapted = self.adapter( |
| 74 | + {"inference_variables": estimate}, |
| 75 | + inverse=True, |
| 76 | + strict=False, |
| 77 | + **kwargs, |
| 78 | + ) |
| 79 | + processed[score_key][head_key] = adapted |
| 80 | + return processed |
| 81 | + |
| 82 | + def _apply_inverse_adapter_to_samples( |
| 83 | + self, samples: dict[str, Tensor], **kwargs |
| 84 | + ) -> dict[str, dict[str, np.ndarray]]: |
| 85 | + """Applies the inverse adapter to a dictionary of samples.""" |
| 86 | + samples = keras.tree.map_structure(keras.ops.convert_to_numpy, samples) |
| 87 | + processed = {} |
| 88 | + for score_key, samples in samples.items(): |
| 89 | + processed[score_key] = self.adapter( |
| 90 | + {"inference_variables": samples}, |
| 91 | + inverse=True, |
| 92 | + strict=False, |
| 93 | + **kwargs, |
| 94 | + ) |
| 95 | + return processed |
| 96 | + |
| 97 | + def _reorder_estimates( |
| 98 | + self, estimates: dict[str, dict[str, dict[str, np.ndarray]]] |
| 99 | + ) -> dict[str, dict[str, dict[str, np.ndarray]]]: |
| 100 | + """Reorders the nested dictionary so that the inference variable names become the top-level keys.""" |
| 101 | + # Grab the variable names from one sample inner dictionary. |
| 102 | + sample_inner = next(iter(next(iter(estimates.values())).values())) |
| 103 | + variable_names = sample_inner.keys() |
| 104 | + reordered = {} |
| 105 | + for variable in variable_names: |
| 106 | + reordered[variable] = {} |
| 107 | + for score_key, inner_dict in estimates.items(): |
| 108 | + reordered[variable][score_key] = {inner_key: value[variable] for inner_key, value in inner_dict.items()} |
| 109 | + return reordered |
| 110 | + |
| 111 | + def _squeeze_estimates( |
| 112 | + self, estimates: dict[str, dict[str, dict[str, np.ndarray]]] |
| 113 | + ) -> dict[str, dict[str, np.ndarray]]: |
| 114 | + """Squeezes each inner estimate dictionary to remove unnecessary nesting.""" |
| 115 | + squeezed = {} |
| 116 | + for variable, variable_estimates in estimates.items(): |
| 117 | + squeezed[variable] = { |
| 118 | + score_key: squeeze_inner_estimates_dict(inner_estimate) |
| 119 | + for score_key, inner_estimate in variable_estimates.items() |
| 120 | + } |
| 121 | + return squeezed |
| 122 | + |
| 123 | + def _squeeze_samples(self, samples: dict[str, np.ndarray]) -> np.ndarray or dict[str, np.ndarray]: |
| 124 | + """Squeezes the samples dictionary to just the value if there is only one key-value pair.""" |
| 125 | + if len(samples) == 1: |
| 126 | + return next(iter(samples.values())) # Extract and return the only item's value |
| 127 | + return samples |
| 128 | + |
| 129 | + def _estimate( |
| 130 | + self, |
| 131 | + inference_conditions: Tensor = None, |
| 132 | + summary_variables: Tensor = None, |
| 133 | + **kwargs, |
| 134 | + ) -> dict[str, dict[str, Tensor]]: |
| 135 | + if self.summary_network is None: |
| 136 | + if summary_variables is not None: |
| 137 | + raise ValueError("Cannot use summary variables without a summary network.") |
| 138 | + else: |
| 139 | + if summary_variables is None: |
| 140 | + raise ValueError("Summary variables are required when a summary network is present.") |
| 141 | + |
| 142 | + summary_outputs = self.summary_network( |
| 143 | + summary_variables, **filter_kwargs(kwargs, self.summary_network.call) |
| 144 | + ) |
| 145 | + |
| 146 | + if inference_conditions is None: |
| 147 | + inference_conditions = summary_outputs |
| 148 | + else: |
| 149 | + inference_conditions = keras.ops.concatenate([inference_conditions, summary_outputs], axis=1) |
| 150 | + |
| 151 | + return self.inference_network( |
| 152 | + conditions=inference_conditions, |
| 153 | + **filter_kwargs(kwargs, self.inference_network.call), |
| 154 | + ) |
0 commit comments