-
Notifications
You must be signed in to change notification settings - Fork 78
add replace nan adapter #459
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
1b2aeae
add replace nan adapter
arrjon c51fa03
Merge branch 'dev' into adapater_nan
arrjon 7db72bb
improved naming
arrjon 93cf09f
_mask as additional key
arrjon 4b776f0
update test
arrjon 3a8e313
improve
arrjon c963b5b
Merge branch 'dev' into adapater_nan
arrjon a2eadd9
fix serializable
arrjon b5c946b
changed name to return_mask
arrjon e076518
add mask naming
arrjon b1e32f7
Merge branch 'dev' into adapater_nan
arrjon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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,91 @@ | ||
| import numpy as np | ||
|
|
||
| from bayesflow.utils.serialization import serializable, serialize | ||
| from .elementwise_transform import ElementwiseTransform | ||
|
|
||
|
|
||
| @serializable | ||
| class ReplaceNaN(ElementwiseTransform): | ||
| """ | ||
| Replace NaNs with a default value, and optionally encode a missing‐data mask. | ||
|
|
||
| This is based on "Missing data in amortized simulation-based neural posterior estimation" by Wang et al. (2024). | ||
|
|
||
| Parameters | ||
| ---------- | ||
| default_value : float | ||
| Value to substitute wherever data is NaN. | ||
| encode_mask : bool, default=False | ||
| If True, the forward pass will expand the array by one new axis and | ||
| concatenate a binary mask (0 for originally-NaN entries, 1 otherwise). | ||
| axis : int or None | ||
| Axis along which to add the new dimension for mask encoding. | ||
| If None, defaults to `data.ndim` (i.e., a new trailing axis). | ||
|
|
||
| Examples | ||
| -------- | ||
| >>> a = np.array([1.0, np.nan, 3.0]) | ||
| >>> r_nan = bf.adapters.transforms.ReplaceNaN(default_value=0.0) | ||
| >>> r_nan.forward(a) | ||
| array([1., 0., 3.]) | ||
|
|
||
| >>> # With mask encoding along a new last axis: | ||
| >>> r_nan = bf.adapters.transforms.ReplaceNaN(default_value=-1.0, encode_mask=True, axis=-1) | ||
| >>> enc = r_nan.forward(a) | ||
| >>> enc.shape | ||
| (3, 2) | ||
|
|
||
| It’s recommended to precede this with a ToArray transform if your data | ||
| might not already be a NumPy array. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| default_value: float = 0.0, | ||
| encode_mask: bool = False, | ||
| axis: int | None = None, | ||
arrjon marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| ): | ||
| super().__init__() | ||
| self.default_value = default_value | ||
| self.encode_mask = encode_mask | ||
| self.axis = axis | ||
|
|
||
| def get_config(self) -> dict: | ||
| return serialize( | ||
| { | ||
| "default_value": self.default_value, | ||
| "encode_mask": self.encode_mask, | ||
| "axis": self.axis, | ||
| } | ||
| ) | ||
|
|
||
| def forward(self, data: np.ndarray, **kwargs) -> np.ndarray: | ||
| # Create mask of where data is NaN | ||
| mask = np.isnan(data) | ||
| # Fill NaNs with the default value | ||
| filled = np.where(mask, self.default_value, data) | ||
arrjon marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| if not self.encode_mask: | ||
| return filled | ||
|
|
||
| # Decide where to insert the new axis | ||
| ax = self.axis if self.axis is not None else data.ndim | ||
| # Expand dims for both filled data and mask | ||
| filled_exp = np.expand_dims(filled, axis=ax) | ||
| mask_exp = 1 - np.expand_dims(mask.astype(np.int8), axis=ax) | ||
| # Concatenate along that axis: [..., value, mask] | ||
| return np.concatenate([filled_exp, mask_exp], axis=ax) | ||
|
|
||
| def inverse(self, data: np.ndarray, **kwargs) -> np.ndarray: | ||
arrjon marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if not self.encode_mask: | ||
| # No mask was encoded, so nothing to undo | ||
| return data | ||
|
|
||
| ax = self.axis if self.axis is not None else data.ndim - 1 | ||
arrjon marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| # Extract the two “channels” | ||
| values = np.take(data, indices=0, axis=ax) | ||
| mask = np.take(data, indices=1, axis=ax).astype(bool) | ||
| # Restore NaNs where mask == 1 | ||
| values[mask] = np.nan | ||
| return values | ||
This file contains hidden or 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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.