Skip to content

Neural networks

posterior_nn(model, z_score_theta='independent', z_score_x='independent', hidden_features=50, num_transforms=5, num_bins=10, embedding_net=nn.Identity(), num_components=10, **kwargs)

Returns a function that builds a density estimator for learning the posterior.

This function will usually be used for SNPE. The returned function is to be passed to the inference class when using the flexible interface.

Parameters:

Name Type Description Default
model str

The type of density estimator that will be created. One of [mdn, made, maf, maf_rqs, nsf].

required
z_score_theta Optional[str]

Whether to z-score parameters \(\theta\) before passing them into the network, can take one of the following: - none, or None: do not z-score. - independent: z-score each dimension independently. - structured: treat dimensions as related, therefore compute mean and std over the entire batch, instead of per-dimension. Should be used when each sample is, for example, a time series or an image.

'independent'
z_score_x Optional[str]

Whether to z-score simulation outputs \(x\) before passing them into the network, same options as z_score_theta.

'independent'
hidden_features int

Number of hidden features.

50
num_transforms int

Number of transforms when a flow is used. Only relevant if density estimator is a normalizing flow (i.e. currently either a maf or a nsf). Ignored if density estimator is a mdn or made.

5
num_bins int

Number of bins used for the splines in nsf. Ignored if density estimator not nsf.

10
embedding_net Module

Optional embedding network for simulation outputs \(x\). This embedding net allows to learn features from potentially high-dimensional simulation outputs.

Identity()
num_components int

Number of mixture components for a mixture of Gaussians. Ignored if density estimator is not an mdn.

10
kwargs Any

additional custom arguments passed to downstream build functions.

{}
Source code in sbi/neural_nets/factory.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
def posterior_nn(
    model: str,
    z_score_theta: Optional[str] = "independent",
    z_score_x: Optional[str] = "independent",
    hidden_features: int = 50,
    num_transforms: int = 5,
    num_bins: int = 10,
    embedding_net: nn.Module = nn.Identity(),
    num_components: int = 10,
    **kwargs: Any,
) -> Callable:
    r"""
    Returns a function that builds a density estimator for learning the posterior.

    This function will usually be used for SNPE. The returned function is to be passed
    to the inference class when using the flexible interface.

    Args:
        model: The type of density estimator that will be created. One of [`mdn`,
            `made`, `maf`, `maf_rqs`, `nsf`].
        z_score_theta: Whether to z-score parameters $\theta$ before passing them into
            the network, can take one of the following:
            - `none`, or None: do not z-score.
            - `independent`: z-score each dimension independently.
            - `structured`: treat dimensions as related, therefore compute mean and std
            over the entire batch, instead of per-dimension. Should be used when each
            sample is, for example, a time series or an image.
        z_score_x: Whether to z-score simulation outputs $x$ before passing them into
            the network, same options as z_score_theta.
        hidden_features: Number of hidden features.
        num_transforms: Number of transforms when a flow is used. Only relevant if
            density estimator is a normalizing flow (i.e. currently either a `maf` or a
            `nsf`). Ignored if density estimator is a `mdn` or `made`.
        num_bins: Number of bins used for the splines in `nsf`. Ignored if density
            estimator not `nsf`.
        embedding_net: Optional embedding network for simulation outputs $x$. This
            embedding net allows to learn features from potentially high-dimensional
            simulation outputs.
        num_components: Number of mixture components for a mixture of Gaussians.
            Ignored if density estimator is not an mdn.
        kwargs: additional custom arguments passed to downstream build functions.
    """

    kwargs = dict(
        zip(
            (
                "z_score_x",
                "z_score_y",
                "hidden_features",
                "num_transforms",
                "num_bins",
                "embedding_net",
                "num_components",
            ),
            (
                z_score_theta,
                z_score_x,
                hidden_features,
                num_transforms,
                num_bins,
                embedding_net,
                num_components,
            ),
        ),
        **kwargs,
    )

    def build_fn_snpe_a(batch_theta, batch_x, num_components):
        """Build function for SNPE-A

        Extract the number of components from the kwargs, such that they are exposed as
        a kwargs, offering the possibility to later override this kwarg with
        `functools.partial`. This is necessary in order to make sure that the MDN in
        SNPE-A only has one component when running the Algorithm 1 part.
        """
        return build_mdn(
            batch_x=batch_theta,
            batch_y=batch_x,
            num_components=num_components,
            **kwargs,
        )

    def build_fn(batch_theta, batch_x):
        if model not in model_builders:
            raise NotImplementedError(f"Model {model} in not implemented")

        # The naming might be a bit confusing.
        # batch_x are the latent variables, batch_y the conditioned variables.
        # batch_theta are the parameters and batch_x the observable variables.
        return model_builders[model](batch_x=batch_theta, batch_y=batch_x, **kwargs)

    if model == "mdn_snpe_a":
        if num_components != 10:
            raise ValueError(
                "You set `num_components`. For SNPE-A, this has to be done at "
                "instantiation of the inference object, i.e. "
                "`inference = SNPE_A(..., num_components=20)`"
            )
        kwargs.pop("num_components")

    return build_fn_snpe_a if model == "mdn_snpe_a" else build_fn

likelihood_nn(model, z_score_theta='independent', z_score_x='independent', hidden_features=50, num_transforms=5, num_bins=10, embedding_net=nn.Identity(), num_components=10, **kwargs)

Returns a function that builds a density estimator for learning the likelihood.

This function will usually be used for SNLE. The returned function is to be passed to the inference class when using the flexible interface.

Parameters:

Name Type Description Default
model str

The type of density estimator that will be created. One of [mdn, made, maf, maf_rqs, nsf].

required
z_score_theta Optional[str]

Whether to z-score parameters \(\theta\) before passing them into the network, can take one of the following: - none, or None: do not z-score. - independent: z-score each dimension independently. - structured: treat dimensions as related, therefore compute mean and std over the entire batch, instead of per-dimension. Should be used when each sample is, for example, a time series or an image.

'independent'
z_score_x Optional[str]

Whether to z-score simulation outputs \(x\) before passing them into the network, same options as z_score_theta.

'independent'
hidden_features int

Number of hidden features.

50
num_transforms int

Number of transforms when a flow is used. Only relevant if density estimator is a normalizing flow (i.e. currently either a maf or a nsf). Ignored if density estimator is a mdn or made.

5
num_bins int

Number of bins used for the splines in nsf. Ignored if density estimator not nsf.

10
embedding_net Module

Optional embedding network for parameters \(\theta\).

Identity()
num_components int

Number of mixture components for a mixture of Gaussians. Ignored if density estimator is not an mdn.

10
kwargs Any

additional custom arguments passed to downstream build functions.

{}
Source code in sbi/neural_nets/factory.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def likelihood_nn(
    model: str,
    z_score_theta: Optional[str] = "independent",
    z_score_x: Optional[str] = "independent",
    hidden_features: int = 50,
    num_transforms: int = 5,
    num_bins: int = 10,
    embedding_net: nn.Module = nn.Identity(),
    num_components: int = 10,
    **kwargs: Any,
) -> Callable:
    r"""
    Returns a function that builds a density estimator for learning the likelihood.

    This function will usually be used for SNLE. The returned function is to be passed
    to the inference class when using the flexible interface.

    Args:
        model: The type of density estimator that will be created. One of [`mdn`,
            `made`, `maf`, `maf_rqs`, `nsf`].
        z_score_theta: Whether to z-score parameters $\theta$ before passing them into
            the network, can take one of the following:
            - `none`, or None: do not z-score.
            - `independent`: z-score each dimension independently.
            - `structured`: treat dimensions as related, therefore compute mean and std
            over the entire batch, instead of per-dimension. Should be used when each
            sample is, for example, a time series or an image.
        z_score_x: Whether to z-score simulation outputs $x$ before passing them into
            the network, same options as z_score_theta.
        hidden_features: Number of hidden features.
        num_transforms: Number of transforms when a flow is used. Only relevant if
            density estimator is a normalizing flow (i.e. currently either a `maf` or a
            `nsf`). Ignored if density estimator is a `mdn` or `made`.
        num_bins: Number of bins used for the splines in `nsf`. Ignored if density
            estimator not `nsf`.
        embedding_net: Optional embedding network for parameters $\theta$.
        num_components: Number of mixture components for a mixture of Gaussians.
            Ignored if density estimator is not an mdn.
        kwargs: additional custom arguments passed to downstream build functions.
    """

    kwargs = dict(
        zip(
            (
                "z_score_x",
                "z_score_y",
                "hidden_features",
                "num_transforms",
                "num_bins",
                "embedding_net",
                "num_components",
            ),
            (
                z_score_x,
                z_score_theta,
                hidden_features,
                num_transforms,
                num_bins,
                embedding_net,
                num_components,
            ),
        ),
        **kwargs,
    )

    def build_fn(batch_theta, batch_x):
        if model not in model_builders:
            raise NotImplementedError(f"Model {model} in not implemented")

        return model_builders[model](batch_x=batch_x, batch_y=batch_theta, **kwargs)

    return build_fn

classifier_nn(model, z_score_theta='independent', z_score_x='independent', hidden_features=50, embedding_net_theta=nn.Identity(), embedding_net_x=nn.Identity(), **kwargs)

Returns a function that builds a classifier for learning density ratios.

This function will usually be used for SNRE. The returned function is to be passed to the inference class when using the flexible interface.

Note that in the view of the SNRE classifier we build below, x=theta and y=x.

Parameters:

Name Type Description Default
model str

The type of classifier that will be created. One of [linear, mlp, resnet].

required
z_score_theta Optional[str]

Whether to z-score parameters \(\theta\) before passing them into the network, can take one of the following: - none, or None: do not z-score. - independent: z-score each dimension independently. - structured: treat dimensions as related, therefore compute mean and std over the entire batch, instead of per-dimension. Should be used when each sample is, for example, a time series or an image.

'independent'
z_score_x Optional[str]

Whether to z-score simulation outputs \(x\) before passing them into the network, same options as z_score_theta.

'independent'
hidden_features int

Number of hidden features.

50
embedding_net_theta Module

Optional embedding network for parameters \(\theta\).

Identity()
embedding_net_x Module

Optional embedding network for simulation outputs \(x\). This embedding net allows to learn features from potentially high-dimensional simulation outputs.

Identity()
kwargs Any

additional custom arguments passed to downstream build functions.

{}
Source code in sbi/neural_nets/factory.py
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def classifier_nn(
    model: str,
    z_score_theta: Optional[str] = "independent",
    z_score_x: Optional[str] = "independent",
    hidden_features: int = 50,
    embedding_net_theta: nn.Module = nn.Identity(),
    embedding_net_x: nn.Module = nn.Identity(),
    **kwargs: Any,
) -> Callable:
    r"""
    Returns a function that builds a classifier for learning density ratios.

    This function will usually be used for SNRE. The returned function is to be passed
    to the inference class when using the flexible interface.

    Note that in the view of the SNRE classifier we build below, x=theta and y=x.

    Args:
        model: The type of classifier that will be created. One of [`linear`, `mlp`,
            `resnet`].
        z_score_theta: Whether to z-score parameters $\theta$ before passing them into
            the network, can take one of the following:
            - `none`, or None: do not z-score.
            - `independent`: z-score each dimension independently.
            - `structured`: treat dimensions as related, therefore compute mean and std
            over the entire batch, instead of per-dimension. Should be used when each
            sample is, for example, a time series or an image.
        z_score_x: Whether to z-score simulation outputs $x$ before passing them into
            the network, same options as z_score_theta.
        hidden_features: Number of hidden features.
        embedding_net_theta:  Optional embedding network for parameters $\theta$.
        embedding_net_x:  Optional embedding network for simulation outputs $x$. This
            embedding net allows to learn features from potentially high-dimensional
            simulation outputs.
        kwargs: additional custom arguments passed to downstream build functions.
    """

    kwargs = dict(
        zip(
            (
                "z_score_x",
                "z_score_y",
                "hidden_features",
                "embedding_net_x",
                "embedding_net_y",
            ),
            (
                z_score_theta,
                z_score_x,
                hidden_features,
                embedding_net_theta,
                embedding_net_x,
            ),
        ),
        **kwargs,
    )

    def build_fn(batch_theta, batch_x):
        if model == "linear":
            return build_linear_classifier(
                batch_x=batch_theta, batch_y=batch_x, **kwargs
            )
        if model == "mlp":
            return build_mlp_classifier(batch_x=batch_theta, batch_y=batch_x, **kwargs)
        if model == "resnet":
            return build_resnet_classifier(
                batch_x=batch_theta, batch_y=batch_x, **kwargs
            )
        else:
            raise NotImplementedError

    return build_fn

DensityEstimator

Bases: Module

Base class for density estimators.

The density estimator class is a wrapper around neural networks that allows to evaluate the log_prob, sample, and provide the loss of \(\theta,x\) pairs. Here \(\theta\) would be the input and \(x\) would be the condition.

Note

We assume that the input to the density estimator is a tensor of shape (batch_size, input_size), where input_size is the dimensionality of the input. The condition is a tensor of shape (batch_size, *condition_shape), where condition_shape is the shape of the condition tensor.

Source code in sbi/neural_nets/density_estimators/base.py
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
class DensityEstimator(nn.Module):
    r"""Base class for density estimators.

    The density estimator class is a wrapper around neural networks that
    allows to evaluate the `log_prob`, `sample`, and provide the `loss` of $\theta,x$
    pairs. Here $\theta$ would be the `input` and $x$ would be the `condition`.

    Note:
        We assume that the input to the density estimator is a tensor of shape
        (batch_size, input_size), where input_size is the dimensionality of the input.
        The condition is a tensor of shape (batch_size, *condition_shape), where
        condition_shape is the shape of the condition tensor.

    """

    def __init__(self, net: nn.Module, condition_shape: torch.Size) -> None:
        r"""Base class for density estimators.

        Args:
            net: Neural network.
            condition_shape: Shape of the condition. If not provided, it will assume a
                            1D input.
        """
        super().__init__()
        self.net = net
        self._condition_shape = condition_shape

    @property
    def embedding_net(self) -> Optional[nn.Module]:
        r"""Return the embedding network if it exists."""
        return None

    def log_prob(self, input: Tensor, condition: Tensor, **kwargs) -> Tensor:
        r"""Return the log probabilities of the inputs given a condition or multiple
        i.e. batched conditions.

        Args:
            input: Inputs to evaluate the log probability on of shape
                    (*batch_shape1, input_size).
            condition: Conditions of shape (*batch_shape2, *condition_shape).

        Raises:
            RuntimeError: If batch_shape1 and batch_shape2 are not broadcastable.

        Returns:
            Sample-wise log probabilities.

        Note:
            This function should support PyTorch's automatic broadcasting. This means
            the function should behave as follows for different input and condition
            shapes:
            - (input_size,) + (batch_size,*condition_shape) -> (batch_size,)
            - (batch_size, input_size) + (*condition_shape) -> (batch_size,)
            - (batch_size, input_size) + (batch_size, *condition_shape) -> (batch_size,)
            - (batch_size1, input_size) + (batch_size2, *condition_shape)
                                                  -> RuntimeError i.e. not broadcastable
            - (batch_size1,1, input_size) + (batch_size2, *condition_shape)
                                                  -> (batch_size1,batch_size2)
            - (batch_size1, input_size) + (batch_size2,1, *condition_shape)
                                                  -> (batch_size2,batch_size1)
        """

        raise NotImplementedError

    def loss(self, input: Tensor, condition: Tensor, **kwargs) -> Tensor:
        r"""Return the loss for training the density estimator.

        Args:
            input: Inputs to evaluate the loss on of shape (batch_size, input_size).
            condition: Conditions of shape (batch_size, *condition_shape).

        Returns:
            Loss of shape (batch_size,)
        """

        raise NotImplementedError

    def sample(self, sample_shape: torch.Size, condition: Tensor, **kwargs) -> Tensor:
        r"""Return samples from the density estimator.

        Args:
            sample_shape: Shape of the samples to return.
            condition: Conditions of shape (*batch_shape, *condition_shape).

        Returns:
            Samples of shape (*batch_shape, *sample_shape, input_size).

        Note:
            This function should support batched conditions and should admit the
            following behavior for different condition shapes:
            - (*condition_shape) -> (*sample_shape, input_size)
            - (*batch_shape, *condition_shape)
                                        -> (*batch_shape, *sample_shape, input_size)
        """

        raise NotImplementedError

    def sample_and_log_prob(
        self, sample_shape: torch.Size, condition: Tensor, **kwargs
    ) -> Tuple[Tensor, Tensor]:
        r"""Return samples and their density from the density estimator.

        Args:
            sample_shape: Shape of the samples to return.
            condition: Conditions of shape (*batch_shape, *condition_shape).

        Returns:
            Samples and associated log probabilities.


        Note:
            For some density estimators, computing log_probs for samples is
            more efficient than computing them separately. This method should
            then be overwritten to provide a more efficient implementation.
        """

        samples = self.sample(sample_shape, condition, **kwargs)
        log_probs = self.log_prob(samples, condition, **kwargs)
        return samples, log_probs

    def _check_condition_shape(self, condition: Tensor):
        r"""This method checks whether the condition has the correct shape.

        Args:
            condition: Conditions of shape (*batch_shape, *condition_shape).

        Raises:
            ValueError: If the condition has a dimensionality that does not match
                        the expected input dimensionality.
            ValueError: If the shape of the condition does not match the expected
                        input dimensionality.
        """
        if len(condition.shape) < len(self._condition_shape):
            raise ValueError(
                f"Dimensionality of condition is to small and does not match the\
                expected input dimensionality {len(self._condition_shape)}, as provided\
                by condition_shape."
            )
        else:
            condition_shape = condition.shape[-len(self._condition_shape) :]
            if tuple(condition_shape) != tuple(self._condition_shape):
                raise ValueError(
                    f"Shape of condition {tuple(condition_shape)} does not match the \
                    expected input dimensionality {tuple(self._condition_shape)}, as \
                    provided by condition_shape. Please reshape it accordingly."
                )

embedding_net: Optional[nn.Module] property

Return the embedding network if it exists.

__init__(net, condition_shape)

Base class for density estimators.

Parameters:

Name Type Description Default
net Module

Neural network.

required
condition_shape Size

Shape of the condition. If not provided, it will assume a 1D input.

required
Source code in sbi/neural_nets/density_estimators/base.py
22
23
24
25
26
27
28
29
30
31
32
def __init__(self, net: nn.Module, condition_shape: torch.Size) -> None:
    r"""Base class for density estimators.

    Args:
        net: Neural network.
        condition_shape: Shape of the condition. If not provided, it will assume a
                        1D input.
    """
    super().__init__()
    self.net = net
    self._condition_shape = condition_shape

log_prob(input, condition, **kwargs)

Return the log probabilities of the inputs given a condition or multiple i.e. batched conditions.

Parameters:

Name Type Description Default
input Tensor

Inputs to evaluate the log probability on of shape (*batch_shape1, input_size).

required
condition Tensor

Conditions of shape (*batch_shape2, *condition_shape).

required

Raises:

Type Description
RuntimeError

If batch_shape1 and batch_shape2 are not broadcastable.

Returns:

Type Description
Tensor

Sample-wise log probabilities.

Note

This function should support PyTorch’s automatic broadcasting. This means the function should behave as follows for different input and condition shapes: - (input_size,) + (batch_size,*condition_shape) -> (batch_size,) - (batch_size, input_size) + (*condition_shape) -> (batch_size,) - (batch_size, input_size) + (batch_size, *condition_shape) -> (batch_size,) - (batch_size1, input_size) + (batch_size2, *condition_shape) -> RuntimeError i.e. not broadcastable - (batch_size1,1, input_size) + (batch_size2, *condition_shape) -> (batch_size1,batch_size2) - (batch_size1, input_size) + (batch_size2,1, *condition_shape) -> (batch_size2,batch_size1)

Source code in sbi/neural_nets/density_estimators/base.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def log_prob(self, input: Tensor, condition: Tensor, **kwargs) -> Tensor:
    r"""Return the log probabilities of the inputs given a condition or multiple
    i.e. batched conditions.

    Args:
        input: Inputs to evaluate the log probability on of shape
                (*batch_shape1, input_size).
        condition: Conditions of shape (*batch_shape2, *condition_shape).

    Raises:
        RuntimeError: If batch_shape1 and batch_shape2 are not broadcastable.

    Returns:
        Sample-wise log probabilities.

    Note:
        This function should support PyTorch's automatic broadcasting. This means
        the function should behave as follows for different input and condition
        shapes:
        - (input_size,) + (batch_size,*condition_shape) -> (batch_size,)
        - (batch_size, input_size) + (*condition_shape) -> (batch_size,)
        - (batch_size, input_size) + (batch_size, *condition_shape) -> (batch_size,)
        - (batch_size1, input_size) + (batch_size2, *condition_shape)
                                              -> RuntimeError i.e. not broadcastable
        - (batch_size1,1, input_size) + (batch_size2, *condition_shape)
                                              -> (batch_size1,batch_size2)
        - (batch_size1, input_size) + (batch_size2,1, *condition_shape)
                                              -> (batch_size2,batch_size1)
    """

    raise NotImplementedError

loss(input, condition, **kwargs)

Return the loss for training the density estimator.

Parameters:

Name Type Description Default
input Tensor

Inputs to evaluate the loss on of shape (batch_size, input_size).

required
condition Tensor

Conditions of shape (batch_size, *condition_shape).

required

Returns:

Type Description
Tensor

Loss of shape (batch_size,)

Source code in sbi/neural_nets/density_estimators/base.py
71
72
73
74
75
76
77
78
79
80
81
82
def loss(self, input: Tensor, condition: Tensor, **kwargs) -> Tensor:
    r"""Return the loss for training the density estimator.

    Args:
        input: Inputs to evaluate the loss on of shape (batch_size, input_size).
        condition: Conditions of shape (batch_size, *condition_shape).

    Returns:
        Loss of shape (batch_size,)
    """

    raise NotImplementedError

sample(sample_shape, condition, **kwargs)

Return samples from the density estimator.

Parameters:

Name Type Description Default
sample_shape Size

Shape of the samples to return.

required
condition Tensor

Conditions of shape (*batch_shape, *condition_shape).

required

Returns:

Type Description
Tensor

Samples of shape (*batch_shape, *sample_shape, input_size).

Note

This function should support batched conditions and should admit the following behavior for different condition shapes: - (*condition_shape) -> (*sample_shape, input_size) - (*batch_shape, *condition_shape) -> (*batch_shape, *sample_shape, input_size)

Source code in sbi/neural_nets/density_estimators/base.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def sample(self, sample_shape: torch.Size, condition: Tensor, **kwargs) -> Tensor:
    r"""Return samples from the density estimator.

    Args:
        sample_shape: Shape of the samples to return.
        condition: Conditions of shape (*batch_shape, *condition_shape).

    Returns:
        Samples of shape (*batch_shape, *sample_shape, input_size).

    Note:
        This function should support batched conditions and should admit the
        following behavior for different condition shapes:
        - (*condition_shape) -> (*sample_shape, input_size)
        - (*batch_shape, *condition_shape)
                                    -> (*batch_shape, *sample_shape, input_size)
    """

    raise NotImplementedError

sample_and_log_prob(sample_shape, condition, **kwargs)

Return samples and their density from the density estimator.

Parameters:

Name Type Description Default
sample_shape Size

Shape of the samples to return.

required
condition Tensor

Conditions of shape (*batch_shape, *condition_shape).

required

Returns:

Type Description
Tuple[Tensor, Tensor]

Samples and associated log probabilities.

Note

For some density estimators, computing log_probs for samples is more efficient than computing them separately. This method should then be overwritten to provide a more efficient implementation.

Source code in sbi/neural_nets/density_estimators/base.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def sample_and_log_prob(
    self, sample_shape: torch.Size, condition: Tensor, **kwargs
) -> Tuple[Tensor, Tensor]:
    r"""Return samples and their density from the density estimator.

    Args:
        sample_shape: Shape of the samples to return.
        condition: Conditions of shape (*batch_shape, *condition_shape).

    Returns:
        Samples and associated log probabilities.


    Note:
        For some density estimators, computing log_probs for samples is
        more efficient than computing them separately. This method should
        then be overwritten to provide a more efficient implementation.
    """

    samples = self.sample(sample_shape, condition, **kwargs)
    log_probs = self.log_prob(samples, condition, **kwargs)
    return samples, log_probs