-
Notifications
You must be signed in to change notification settings - Fork 78
Add Nnpe adapter class #488
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 8 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
0af7303
Add NNPE adapter
elseml 3a98176
Add NNPE adapter tests
elseml e2f93dc
Only apply NNPE during training
elseml cf05da9
Integrate stage differentiation into tests
elseml 612123c
Improve test coverage
elseml 6c8744b
Fix inverse and add to tests
elseml 4931fac
Adjust class name and add docstring to forward method
elseml 5bbeefe
Enable compatibility with #486 by adjusting scales automatically
elseml ad04ebb
Add dimensionwise noise application
elseml 6e6ca4f
Update exception handling
elseml 8da10dc
Fix tests
elseml 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,97 @@ | ||
| import numpy as np | ||
|
|
||
| from bayesflow.utils.serialization import serializable, serialize | ||
|
|
||
| from .elementwise_transform import ElementwiseTransform | ||
|
|
||
|
|
||
| @serializable("bayesflow.adapters") | ||
| class NNPE(ElementwiseTransform): | ||
| """Implements noisy neural posterior estimation (NNPE) as described in [1], which adds noise following a | ||
| spike-and-slab distribution to the training data as a mild form of data augmentation to robustify against noisy | ||
| real-world data (see [1, 2] for benchmarks). | ||
|
|
||
| [1] Ward, D., Cannon, P., Beaumont, M., Fasiolo, M., & Schmon, S. (2022). Robust neural posterior estimation and | ||
| statistical model criticism. Advances in Neural Information Processing Systems, 35, 33845-33859. | ||
| [2] Elsemüller, L., Pratz, V., von Krause, M., Voss, A., Bürkner, P. C., & Radev, S. T. (2025). Does Unsupervised | ||
| Domain Adaptation Improve the Robustness of Amortized Bayesian Inference? A Systematic Evaluation. arXiv preprint | ||
| arXiv:2502.04949. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| spike_scale : float or None | ||
| The scale of the spike (Normal) distribution. Automatically determined if None (see “Notes” section). | ||
| slab_scale : float or None | ||
| The scale of the slab (Cauchy) distribution. Automatically determined if None (see “Notes” section). | ||
| seed : int or None | ||
| The seed for the random number generator. If None, a random seed is used. Used instead of np.random.Generator | ||
| here to enable easy serialization. | ||
|
|
||
| Notes | ||
| ----- | ||
| The spike-and-slab distribution consists of a mixture of a Normal distribution (spike) and Cauchy distribution | ||
| (slab), which are applied based on a Bernoulli random variable with p=0.5. | ||
|
|
||
| The scales of the spike and slab distributions can be set manually, or they are automatically determined by scaling | ||
| the default scales of [1] (which expect standardized data) by the standard deviation of the input data. | ||
|
|
||
| Examples | ||
| -------- | ||
| >>> adapter = bf.Adapter().nnpe(["x"]) | ||
| """ | ||
|
|
||
| DEFAULT_SLAB = 0.25 | ||
| DEFAULT_SPIKE = 0.01 | ||
|
|
||
| def __init__(self, *, spike_scale: float | None = None, slab_scale: float | None = None, seed: int | None = None): | ||
| super().__init__() | ||
| self.spike_scale = spike_scale | ||
| self.slab_scale = slab_scale | ||
| self.seed = seed | ||
| self.rng = np.random.default_rng(seed) | ||
|
|
||
| def forward(self, data: np.ndarray, stage: str = "inference", **kwargs) -> np.ndarray: | ||
| """ | ||
| Add spike‐and‐slab noise to `data` during training, using automatic scale determination if not provided (see | ||
| “Notes” section of the class docstring for details). | ||
|
|
||
| Parameters | ||
| ---------- | ||
| data : np.ndarray | ||
| Input array to be perturbed. | ||
| stage : str, default='inference' | ||
| If 'training', noise is added; else data is returned unchanged. | ||
| **kwargs | ||
| Unused keyword arguments. | ||
|
|
||
| Returns | ||
| ------- | ||
| np.ndarray | ||
| Noisy data when `stage` is 'training', otherwise the original input. | ||
| """ | ||
| if stage != "training": | ||
| return data | ||
|
|
||
| # Check data validity | ||
| if not np.all(np.isfinite(data)): | ||
| raise ValueError("NNPE.forward: `data` contains NaN or infinite values.") | ||
|
|
||
| # Automatically determine scales if not provided | ||
| if self.spike_scale is None or self.slab_scale is None: | ||
| data_std = np.std(data) | ||
| spike_scale = self.spike_scale if self.spike_scale is not None else self.DEFAULT_SPIKE * data_std | ||
| slab_scale = self.slab_scale if self.slab_scale is not None else self.DEFAULT_SLAB * data_std | ||
|
|
||
| # Apply spike-and-slab noise | ||
| mixture_mask = self.rng.binomial(n=1, p=0.5, size=data.shape).astype(bool) | ||
| noise_spike = self.rng.standard_normal(size=data.shape) * spike_scale | ||
| noise_slab = self.rng.standard_cauchy(size=data.shape) * slab_scale | ||
| noise = np.where(mixture_mask, noise_slab, noise_spike) | ||
| return data + noise | ||
|
|
||
| def inverse(self, data: np.ndarray, **kwargs) -> np.ndarray: | ||
| """Non-invertible transform.""" | ||
| return data | ||
|
|
||
| def get_config(self) -> dict: | ||
| return serialize({"spike_scale": self.spike_scale, "slab_scale": self.slab_scale, "seed": self.seed}) | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This will lead to different scales for each batch, I'm not sure if this is desirable. If we choose to do this, we should state it more explicitly in the docstring.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is an alternative solution:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for checking! Yes, this is the drawback of that solution. I still think it is preferable to more complex solutions, since the method is more about adding some noise at all rather than adding a very specific amount of noise (the default scales by Ward et al. also seem quite heuristically chosen to me). If you agree on this, I can add some more info in the docstring.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would we want to do the automatic scaling globally or per dimension? I think this would be the main difference in what @stefanradev93 proposed and how it is implemented now, right?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The way Lasse explained to me, the approach explicitly wants that scale(original) < scale(transformed). In that case, I think fluctuations between batches are fine, as the downstream Standardize layer (which will be part of approximators) will take care of that.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Then the question still is how we want to automatically determine the scale, globally or per dimension? If dimensions don't have equal magnitude, we might accidentally erase some of them completely. On the other hand, some dimensions might have zero variation (e.g. in image datasets like MNIST), so we would have to decide how to deal with those...
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good question. I would scale dimensionwise.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I implemented it globally following the original NNPE implementation, but agree that dimensionwise scaling would be valuable in many situations and will implement it as an option. I think dimensions with zero variation are not problematic since in that case nothings breaks, there will simply be no noise added. Dimensionwise instead of global scaling will increase the variability of the std calculation between batches though.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks! Only to make sure, please set dimensionwise as the default, and make global scaling the option.