Skip to content

Commit b49b543

Browse files
committed
Merge branch 'dev' of https://github.com/bayesflow-org/bayesflow into dev
2 parents 91d3f8b + 11b6956 commit b49b543

17 files changed

+57
-23
lines changed

bayesflow/adapters/transforms/as_set.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import numpy as np
21
from keras.saving import register_keras_serializable as serializable
2+
import numpy as np
33

44
from .elementwise_transform import ElementwiseTransform
55

bayesflow/adapters/transforms/sqrt.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import numpy as np
21
from keras.saving import register_keras_serializable as serializable
2+
import numpy as np
33

44
from .elementwise_transform import ElementwiseTransform
55

bayesflow/links/ordered.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ def __init__(self, axis: int, anchor_index: int, **kwargs):
1212
super().__init__(**keras_kwargs(kwargs))
1313
self.axis = axis
1414
self.anchor_index = anchor_index
15+
self.group_indices = None
1516

1617
self.config = {"axis": axis, "anchor_index": anchor_index, **kwargs}
1718

@@ -22,9 +23,9 @@ def get_config(self):
2223
def build(self, input_shape):
2324
super().build(input_shape)
2425

25-
assert self.anchor_index % input_shape[self.axis] != 0 and self.anchor_index != -1, (
26-
"anchor should not be first or last index."
27-
)
26+
if self.anchor_index % input_shape[self.axis] == 0 or self.anchor_index == -1:
27+
raise RuntimeError("Anchor should not be first or last index.")
28+
2829
self.group_indices = dict(
2930
below=list(range(0, self.anchor_index)),
3031
above=list(range(self.anchor_index + 1, input_shape[self.axis])),

bayesflow/links/ordered_quantiles.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -44,16 +44,17 @@ def build(self, input_shape):
4444
else:
4545
# choose quantile level closest to median as anchor index
4646
self.anchor_index = keras.ops.argmin(keras.ops.abs(keras.ops.convert_to_tensor(self.q) - 0.5))
47-
msg = (
48-
"Length of `q` does not coincide with input shape: "
49-
f"len(q)={len(self.q)}, position {self.axis} of shape={input_shape}"
50-
)
51-
assert num_quantile_levels == len(self.q), msg
5247

53-
msg = (
54-
"The link function `OrderedQuantiles` expects at least 3 quantile levels,"
55-
f" but only {num_quantile_levels} were given."
56-
)
57-
assert self.anchor_index not in (0, -1, num_quantile_levels - 1), msg
48+
if len(self.q) != num_quantile_levels:
49+
raise RuntimeError(
50+
f"Length of `q` does not coincide with input shape: len(q)={len(self.q)}, "
51+
f"position {self.axis} of shape={input_shape}"
52+
)
53+
54+
if self.anchor_index in [0, -1, num_quantile_levels - 1]:
55+
raise RuntimeError(
56+
f"The link function `OrderedQuantiles` expects at least 3 quantile levels, "
57+
f"but only {num_quantile_levels} were given."
58+
)
5859

5960
super().build(input_shape)

bayesflow/links/positive_semi_definite.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import keras
2+
from keras.saving import register_keras_serializable as serializable
23

34
from bayesflow.utils import keras_kwargs
45

56

7+
@serializable(package="bayesflow.links")
68
class PositiveSemiDefinite(keras.Layer):
79
"""Activation function to link from any square matrix to a positive semidefinite matrix."""
810

bayesflow/networks/consistency_models/consistency_model.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,10 @@ def build(self, xz_shape, conditions_shape=None):
178178
# First, we calculate all unique numbers of discretization steps n
179179
# in a loop, as self.total_steps might be large
180180
self.max_n = int(self._schedule_discretization(self.total_steps))
181-
assert self.max_n == self.s1 + 1
181+
182+
if self.max_n != self.s1 + 1:
183+
raise ValueError("The maximum number of discretization steps must be equal to s1 + 1.")
184+
182185
unique_n = set()
183186
for step in range(int(self.total_steps)):
184187
unique_n.add(int(self._schedule_discretization(step)))

bayesflow/networks/embeddings/fourier_embedding.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,10 @@ def __init__(
3939
"""
4040

4141
super().__init__(**kwargs)
42-
assert embed_dim % 2 == 0, f"Embedding dimension must be even, but is {embed_dim}."
42+
43+
if embed_dim % 2 != 0:
44+
raise ValueError(f"Embedding dimension must be even, but is {embed_dim}.")
45+
4346
self.w = self.add_weight(initializer=initializer, shape=(embed_dim // 2,), trainable=trainable)
4447
self.scale = scale
4548
self.embed_dim = embed_dim

bayesflow/scores/mean_score.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
from keras.saving import register_keras_serializable as serializable
2+
13
from .normed_difference_score import NormedDifferenceScore
24

35

6+
@serializable(package="bayesflow.scores")
47
class MeanScore(NormedDifferenceScore):
58
r""":math:`S(\hat \theta, \theta) = | \hat \theta - \theta |^2`
69

bayesflow/scores/median_score.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
from keras.saving import register_keras_serializable as serializable
2+
13
from .normed_difference_score import NormedDifferenceScore
24

35

6+
@serializable(package="bayesflow.scores")
47
class MedianScore(NormedDifferenceScore):
58
r""":math:`S(\hat \theta, \theta) = | \hat \theta - \theta |`
69

bayesflow/scores/multivariate_normal_score.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import math
22

33
import keras
4+
from keras.saving import register_keras_serializable as serializable
45

56
from bayesflow.types import Shape, Tensor
67
from bayesflow.links import PositiveSemiDefinite
@@ -9,6 +10,7 @@
910
from .parametric_distribution_score import ParametricDistributionScore
1011

1112

13+
@serializable(package="bayesflow.scores")
1214
class MultivariateNormalScore(ParametricDistributionScore):
1315
r""":math:`S(\hat p_{\mu, \Sigma}, \theta; k) = \log( \mathcal N (\theta; \mu, \Sigma))`
1416
@@ -96,9 +98,14 @@ def sample(self, batch_shape: Shape, mean: Tensor, covariance: Tensor) -> Tensor
9698
A tensor of shape (batch_size, num_samples, D) containing the generated samples.
9799
"""
98100
batch_size, num_samples = batch_shape
99-
dim = mean.shape[-1]
100-
assert mean.shape == (batch_size, dim), "mean must have shape (batch_size, D)"
101-
assert covariance.shape == (batch_size, dim, dim), "covariance must have shape (batch_size, D, D)"
101+
dim = keras.ops.shape(mean)[-1]
102+
if keras.ops.shape(mean) != (batch_size, dim):
103+
raise ValueError(f"mean must have shape (batch_size, {dim}), but got {keras.ops.shape(mean)}")
104+
105+
if keras.ops.shape(covariance) != (batch_size, dim, dim):
106+
raise ValueError(
107+
f"covariance must have shape (batch_size, {dim}, {dim}), but got {keras.ops.shape(covariance)}"
108+
)
102109

103110
# Use Cholesky decomposition to generate samples
104111
cholesky_factor = keras.ops.cholesky(covariance)

0 commit comments

Comments
 (0)