|
| 1 | +from collections.abc import Sequence |
1 | 2 | import numpy as np |
2 | 3 |
|
3 | | -from .elementwise_transform import ElementwiseTransform |
| 4 | +from keras.saving import ( |
| 5 | + deserialize_keras_object as deserialize, |
| 6 | + register_keras_serializable as serializable, |
| 7 | + serialize_keras_object as serialize, |
| 8 | +) |
4 | 9 |
|
| 10 | +from .transform import Transform |
5 | 11 |
|
6 | | -class Broadcast(ElementwiseTransform): |
| 12 | + |
| 13 | +@serializable(package="bayesflow.adapters") |
| 14 | +class Broadcast(Transform): |
7 | 15 | """ |
8 | | - Broadcasts array to a given batch size. |
| 16 | + Broadcasts arrays or scalars to the shape of a given other array. |
| 17 | +
|
| 18 | + Parameters: |
| 19 | +
|
| 20 | + expand: Where should new dimensions be added to match the number of dimensions in `to`? |
| 21 | + Can be "left", "right", or an integer or tuple containing the indices of the new dimensions. |
| 22 | + The latter is needed if we want to include a dimension in the middle, which will be required |
| 23 | + for more advanced cases. By default we expand left. |
| 24 | +
|
| 25 | + exclude: Which dimensions (of the dimensions after expansion) should retain their size, |
| 26 | + rather than being broadcasted to the corresponding dimension size of `to`? |
| 27 | + By default we exclude the last dimension (usually the data dimension) from broadcasting the size. |
| 28 | +
|
9 | 29 | Examples: |
10 | | - >>> bc = Broadcast() |
11 | | - >>> bc(np.array(5), batch_size=3) |
12 | | - array([[5], [5], [5]]) |
13 | | - >>> bc(np.array(5), batch_size=3).shape |
14 | | - (3, 1) |
15 | | - >>> bc(np.array([1, 2, 3]), batch_size=3) |
16 | | - array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) |
17 | | - >>> bc(np.array([1, 2, 3]), batch_size=3).shape |
18 | | - (3, 3) |
19 | | -
|
20 | | - You can opt out of expanding scalars: |
21 | | - >>> bc = Broadcast(expand_scalars=False) |
22 | | - >>> bc(np.array(5), batch_size=3) |
23 | | - np.array([5, 5, 5]) |
24 | | - >>> bc(np.array(5), batch_size=3).shape |
25 | | - (3,) |
| 30 | + shape (1, ) array: |
| 31 | + >>> a = np.array((1,)) |
| 32 | + shape (2, 3) array: |
| 33 | + >>> b = np.array([[1, 2, 3], [4, 5, 6]]) |
| 34 | + shape (2, 2, 3) array: |
| 35 | + >>> c = np.array([[[1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3]]]) |
| 36 | + >>> dat = dict(a=a, b=b, c=c) |
| 37 | +
|
| 38 | + >>> bc = bf.adapters.transforms.Broadcast("a", to="b") |
| 39 | + >>> new_dat = bc.forward(dat) |
| 40 | + >>> new_dat["a"].shape |
| 41 | + (2, 1) |
| 42 | +
|
| 43 | + >>> bc = bf.adapters.transforms.Broadcast("a", to="b", exclude=None) |
| 44 | + >>> new_dat = bc.forward(dat) |
| 45 | + >>> new_dat["a"].shape |
| 46 | + (2, 3) |
| 47 | +
|
| 48 | + >>> bc = bf.adapters.transforms.Broadcast("b", to="c", expand=1) |
| 49 | + >>> new_dat = bc.forward(dat) |
| 50 | + >>> new_dat["b"].shape |
| 51 | + (2, 2, 3) |
26 | 52 |
|
27 | 53 | It is recommended to precede this transform with a :class:`bayesflow.adapters.transforms.ToArray` transform. |
28 | 54 | """ |
29 | 55 |
|
30 | | - def __init__(self, *, expand_scalars: bool = True): |
| 56 | + def __init__(self, keys: Sequence[str], *, to: str, expand: str | int | tuple = "left", exclude: int | tuple = -1): |
31 | 57 | super().__init__() |
| 58 | + self.keys = keys |
| 59 | + self.to = to |
32 | 60 |
|
33 | | - self.expand_scalars = expand_scalars |
| 61 | + if isinstance(expand, int): |
| 62 | + expand = (expand,) |
34 | 63 |
|
35 | | - # noinspection PyMethodOverriding |
36 | | - def forward(self, data: np.ndarray, *, batch_size: int, **kwargs): |
37 | | - data = np.repeat(data[None], batch_size, axis=0) |
| 64 | + self.expand = expand |
38 | 65 |
|
39 | | - if self.expand_scalars and data.ndim == 1: |
40 | | - data = data[:, None] |
| 66 | + if isinstance(exclude, int): |
| 67 | + exclude = (exclude,) |
41 | 68 |
|
42 | | - return data |
| 69 | + self.exclude = exclude |
| 70 | + |
| 71 | + @classmethod |
| 72 | + def from_config(cls, config: dict, custom_objects=None) -> "Broadcast": |
| 73 | + return cls( |
| 74 | + keys=deserialize(config["keys"], custom_objects), |
| 75 | + to=deserialize(config["to"], custom_objects), |
| 76 | + expand=deserialize(config["expand"], custom_objects), |
| 77 | + exclude=deserialize(config["exclude"], custom_objects), |
| 78 | + ) |
| 79 | + |
| 80 | + def get_config(self) -> dict: |
| 81 | + return { |
| 82 | + "keys": serialize(self.keys), |
| 83 | + "to": serialize(self.to), |
| 84 | + "expand": serialize(self.expand), |
| 85 | + "exclude": serialize(self.exclude), |
| 86 | + } |
43 | 87 |
|
44 | 88 | # noinspection PyMethodOverriding |
45 | | - def inverse(self, data: np.ndarray, **kwargs) -> np.ndarray: |
46 | | - data = data[0] |
| 89 | + def forward(self, data: dict[str, np.ndarray], **kwargs) -> dict[str, np.ndarray]: |
| 90 | + target_shape = data[self.to].shape |
| 91 | + |
| 92 | + data = data.copy() |
| 93 | + |
| 94 | + for k in self.keys: |
| 95 | + # ensure that .shape is defined |
| 96 | + data[k] = np.asarray(data[k]) |
| 97 | + len_diff = len(target_shape) - len(data[k].shape) |
| 98 | + |
| 99 | + if self.expand == "left": |
| 100 | + data[k] = np.expand_dims(data[k], axis=tuple(np.arange(0, len_diff))) |
| 101 | + elif self.expand == "right": |
| 102 | + data[k] = np.expand_dims(data[k], axis=tuple(-np.arange(1, len_diff + 1))) |
| 103 | + elif isinstance(self.expand, tuple): |
| 104 | + if len(self.expand) is not len_diff: |
| 105 | + raise ValueError("Length of `expand` must match the length difference of the involed arrays.") |
| 106 | + data[k] = np.expand_dims(data[k], axis=self.expand) |
47 | 107 |
|
48 | | - if self.expand_scalars: |
49 | | - data = np.squeeze(data, axis=0) |
| 108 | + new_shape = target_shape |
| 109 | + if self.exclude is not None: |
| 110 | + new_shape = np.array(new_shape, dtype=int) |
| 111 | + old_shape = np.array(data[k].shape, dtype=int) |
| 112 | + exclude = list(self.exclude) |
| 113 | + new_shape[exclude] = old_shape[exclude] |
| 114 | + new_shape = tuple(new_shape) |
50 | 115 |
|
| 116 | + data[k] = np.broadcast_to(data[k], new_shape) |
| 117 | + |
| 118 | + return data |
| 119 | + |
| 120 | + # noinspection PyMethodOverriding |
| 121 | + def inverse(self, data: dict[str, np.ndarray], **kwargs) -> dict[str, np.ndarray]: |
| 122 | + # TODO: add inverse |
| 123 | + # we will likely never actually need the inverse broadcasting in practice |
| 124 | + # so adding this method is not high priority |
51 | 125 | return data |
0 commit comments