-
Notifications
You must be signed in to change notification settings - Fork 52
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix sampling and get rid of tensorflow_probability for default Gaussians
- Loading branch information
Radev
committed
May 24, 2024
1 parent
08e5b31
commit f566250
Showing
3 changed files
with
35 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
15 changes: 2 additions & 13 deletions
15
bayesflow/experimental/simulation/distributions/__init__.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
30 changes: 30 additions & 0 deletions
30
bayesflow/experimental/simulation/distributions/spherical_gaussian.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
|
||
import math | ||
|
||
import keras | ||
from keras import ops | ||
|
||
from bayesflow.experimental.types import Shape, Distribution, Tensor | ||
|
||
|
||
class SphericalGaussian(Distribution): | ||
"""Utility class for a backend-agnostic spherical Gaussian distribution. | ||
Note: | ||
- ``log_unnormalized_pdf`` method is used as a loss function | ||
- ``log_pdf`` is used for density computation | ||
""" | ||
def __init__(self, shape: Shape): | ||
self.shape = shape | ||
self.dim = int(self.shape[0]) | ||
self._norm_const = 0.5 * self.dim * math.log(2.0 * math.pi) | ||
|
||
def sample(self, batch_shape: Shape): | ||
return keras.random.normal(shape=batch_shape + self.shape, mean=0.0, stddev=1.0) | ||
|
||
def log_unnormalized_prob(self, tensor: Tensor): | ||
return -0.5 * ops.sum(ops.square(tensor), axis=-1) | ||
|
||
def log_prob(self, tensor: Tensor): | ||
log_unnorm_pdf = self.log_unnormalized_prob(tensor) | ||
return log_unnorm_pdf - self._norm_const |