|
| 1 | +from collections.abc import Sequence |
| 2 | + |
| 3 | +import keras |
| 4 | +import numpy as np |
| 5 | +from keras.saving import ( |
| 6 | + deserialize_keras_object as deserialize, |
| 7 | + register_keras_serializable as serializable, |
| 8 | + serialize_keras_object as serialize, |
| 9 | +) |
| 10 | + |
| 11 | +from bayesflow.adapters import Adapter |
| 12 | +from bayesflow.networks import PointInferenceNetwork, SummaryNetwork |
| 13 | +from bayesflow.types import Tensor |
| 14 | +from bayesflow.utils import logging, split_arrays |
| 15 | +from .approximator import Approximator |
| 16 | + |
| 17 | + |
| 18 | +@serializable(package="bayesflow.approximators") |
| 19 | +class ContinuousPointApproximator(Approximator): |
| 20 | + """ |
| 21 | + Defines a workflow for performing fast posterior or likelihood inference. |
| 22 | + The distribution is approximated by a point with an feed-forward network and an optional summary network. |
| 23 | + """ |
| 24 | + |
| 25 | + def __init__( |
| 26 | + self, |
| 27 | + *, |
| 28 | + adapter: Adapter, |
| 29 | + inference_network: PointInferenceNetwork, |
| 30 | + summary_network: SummaryNetwork = None, |
| 31 | + **kwargs, |
| 32 | + ): |
| 33 | + super().__init__(**kwargs) |
| 34 | + self.adapter = adapter |
| 35 | + self.inference_network = inference_network |
| 36 | + self.summary_network = summary_network |
| 37 | + |
| 38 | + @classmethod |
| 39 | + def build_adapter( |
| 40 | + cls, |
| 41 | + inference_variables: Sequence[str], |
| 42 | + inference_conditions: Sequence[str] = None, |
| 43 | + summary_variables: Sequence[str] = None, |
| 44 | + ) -> Adapter: |
| 45 | + adapter = Adapter.create_default(inference_variables) |
| 46 | + |
| 47 | + if inference_conditions is not None: |
| 48 | + adapter = adapter.concatenate(inference_conditions, into="inference_conditions") |
| 49 | + |
| 50 | + if summary_variables is not None: |
| 51 | + adapter = adapter.as_set(summary_variables).concatenate(summary_variables, into="summary_variables") |
| 52 | + |
| 53 | + adapter = adapter.keep(["inference_variables", "inference_conditions", "summary_variables"]).standardize() |
| 54 | + |
| 55 | + return adapter |
| 56 | + |
| 57 | + def compile( |
| 58 | + self, |
| 59 | + *args, |
| 60 | + inference_metrics: Sequence[keras.Metric] = None, |
| 61 | + summary_metrics: Sequence[keras.Metric] = None, |
| 62 | + **kwargs, |
| 63 | + ): |
| 64 | + if inference_metrics: |
| 65 | + self.inference_network._metrics = inference_metrics |
| 66 | + |
| 67 | + if summary_metrics: |
| 68 | + if self.summary_network is None: |
| 69 | + logging.warning("Ignoring summary metrics because there is no summary network.") |
| 70 | + else: |
| 71 | + self.summary_network._metrics = summary_metrics |
| 72 | + |
| 73 | + return super().compile(*args, **kwargs) |
| 74 | + |
| 75 | + def compute_metrics( |
| 76 | + self, |
| 77 | + inference_variables: Tensor, |
| 78 | + inference_conditions: Tensor = None, |
| 79 | + summary_variables: Tensor = None, |
| 80 | + stage: str = "training", |
| 81 | + ) -> dict[str, Tensor]: |
| 82 | + if self.summary_network is None: |
| 83 | + if summary_variables is not None: |
| 84 | + raise ValueError("Cannot compute summary metrics without a summary network.") |
| 85 | + |
| 86 | + summary_metrics = {} |
| 87 | + else: |
| 88 | + if summary_variables is None: |
| 89 | + raise ValueError("Summary variables are required when a summary network is present.") |
| 90 | + |
| 91 | + summary_metrics = self.summary_network.compute_metrics(summary_variables, stage=stage) |
| 92 | + summary_outputs = summary_metrics.pop("outputs") |
| 93 | + |
| 94 | + # append summary outputs to inference conditions |
| 95 | + if inference_conditions is None: |
| 96 | + inference_conditions = summary_outputs |
| 97 | + else: |
| 98 | + inference_conditions = keras.ops.concatenate([inference_conditions, summary_outputs], axis=-1) |
| 99 | + |
| 100 | + inference_metrics = self.inference_network.compute_metrics( |
| 101 | + inference_variables, conditions=inference_conditions, stage=stage |
| 102 | + ) |
| 103 | + |
| 104 | + loss = inference_metrics.get("loss", keras.ops.zeros(())) + summary_metrics.get("loss", keras.ops.zeros(())) |
| 105 | + |
| 106 | + inference_metrics = {f"{key}/inference_{key}": value for key, value in inference_metrics.items()} |
| 107 | + summary_metrics = {f"{key}/summary_{key}": value for key, value in summary_metrics.items()} |
| 108 | + |
| 109 | + metrics = {"loss": loss} | inference_metrics | summary_metrics |
| 110 | + |
| 111 | + return metrics |
| 112 | + |
| 113 | + def fit(self, *args, **kwargs): |
| 114 | + return super().fit(*args, **kwargs, adapter=self.adapter) |
| 115 | + |
| 116 | + @classmethod |
| 117 | + def from_config(cls, config, custom_objects=None): |
| 118 | + config["adapter"] = deserialize(config["adapter"], custom_objects=custom_objects) |
| 119 | + config["inference_network"] = deserialize(config["inference_network"], custom_objects=custom_objects) |
| 120 | + config["summary_network"] = deserialize(config["summary_network"], custom_objects=custom_objects) |
| 121 | + |
| 122 | + return super().from_config(config, custom_objects=custom_objects) |
| 123 | + |
| 124 | + def get_config(self): |
| 125 | + base_config = super().get_config() |
| 126 | + config = { |
| 127 | + "adapter": serialize(self.adapter), |
| 128 | + "inference_network": serialize(self.inference_network), |
| 129 | + "summary_network": serialize(self.summary_network), |
| 130 | + } |
| 131 | + |
| 132 | + return base_config | config |
| 133 | + |
| 134 | + def estimate( |
| 135 | + self, |
| 136 | + *, |
| 137 | + conditions: dict[str, np.ndarray], |
| 138 | + split: bool = False, |
| 139 | + **kwargs, |
| 140 | + ) -> dict[str, np.ndarray]: |
| 141 | + conditions = self.adapter(conditions, strict=False, stage="inference", **kwargs) |
| 142 | + conditions = keras.tree.map_structure(keras.ops.convert_to_tensor, conditions) |
| 143 | + conditions = {"inference_variables": self._estimate(**conditions)} |
| 144 | + conditions = keras.tree.map_structure(keras.ops.convert_to_numpy, conditions) |
| 145 | + conditions = self.adapter(conditions, inverse=True, strict=False, **kwargs) |
| 146 | + |
| 147 | + if split: |
| 148 | + conditions = split_arrays(conditions, axis=-1) |
| 149 | + return conditions |
| 150 | + |
| 151 | + def _estimate( |
| 152 | + self, |
| 153 | + inference_conditions: Tensor = None, |
| 154 | + summary_variables: Tensor = None, |
| 155 | + ) -> Tensor: |
| 156 | + if self.summary_network is None: |
| 157 | + if summary_variables is not None: |
| 158 | + raise ValueError("Cannot use summary variables without a summary network.") |
| 159 | + else: |
| 160 | + if summary_variables is None: |
| 161 | + raise ValueError("Summary variables are required when a summary network is present.") |
| 162 | + |
| 163 | + summary_outputs = self.summary_network(summary_variables) |
| 164 | + |
| 165 | + if inference_conditions is None: |
| 166 | + inference_conditions = summary_outputs |
| 167 | + else: |
| 168 | + inference_conditions = keras.ops.concatenate([inference_conditions, summary_outputs], axis=1) |
| 169 | + |
| 170 | + return self.inference_network.estimate(conditions=inference_conditions) |
0 commit comments