-
Notifications
You must be signed in to change notification settings - Fork 27
Additional Resampling Methods #41
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
+362
−7
Merged
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| import numpy as np | ||
|
|
||
|
|
||
| def systematic_resample(weights): | ||
| """Systematic resampling with a single random offset. | ||
|
|
||
| Separates the sample space into N equal divisions and uses one | ||
| random offset for all divisions. Every sample is exactly 1/N apart. | ||
| Lowest variance among standard resampling methods. | ||
postylem marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| Adapted from FilterPy (R. Labbe): | ||
| https://filterpy.readthedocs.io/en/latest/monte_carlo/resampling.html | ||
|
|
||
| Args: | ||
| weights (array-like): Normalized probability weights summing to 1. | ||
|
|
||
| Returns: | ||
| ndarray: Integer array of ancestor indices. | ||
| """ | ||
| N = len(weights) | ||
| positions = (np.random.random() + np.arange(N)) / N | ||
|
|
||
| indexes = np.zeros(N, "i") | ||
| cumulative_sum = np.cumsum(weights) | ||
| cumulative_sum[-1] = 1.0 # avoid round-off errors | ||
| i, j = 0, 0 | ||
| while i < N: | ||
| if positions[i] < cumulative_sum[j]: | ||
| indexes[i] = j | ||
| i += 1 | ||
| else: | ||
| j += 1 | ||
| return indexes | ||
|
|
||
|
|
||
| def stratified_resample(weights): | ||
| """Stratified resampling with one random draw per stratum. | ||
|
|
||
| Divides the cumulative sum into N equal strata and draws one | ||
| sample uniformly from each. Guarantees samples are between | ||
| 0 and 2/N apart. | ||
postylem marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| Adapted from FilterPy (R. Labbe): | ||
| https://filterpy.readthedocs.io/en/latest/monte_carlo/resampling.html | ||
|
|
||
| Args: | ||
| weights (array-like): Normalized probability weights summing to 1. | ||
|
|
||
| Returns: | ||
| ndarray: Integer array of ancestor indices. | ||
| """ | ||
| N = len(weights) | ||
| positions = (np.random.random(N) + np.arange(N)) / N | ||
|
|
||
| indexes = np.zeros(N, "i") | ||
| cumulative_sum = np.cumsum(weights) | ||
| cumulative_sum[-1] = 1.0 | ||
| i, j = 0, 0 | ||
| while i < N: | ||
| if positions[i] < cumulative_sum[j]: | ||
| indexes[i] = j | ||
| i += 1 | ||
| else: | ||
| j += 1 | ||
| return indexes | ||
|
|
||
|
|
||
| def residual_resample(weights): | ||
| """Residual resampling: deterministic floor copies + multinomial remainder. | ||
|
|
||
| Takes floor(N * w_i) copies of each particle deterministically, | ||
| then resamples the remaining slots from the fractional residuals | ||
| using multinomial resampling. | ||
|
|
||
| Adapted from FilterPy (R. Labbe): | ||
| https://filterpy.readthedocs.io/en/latest/monte_carlo/resampling.html | ||
|
|
||
| Args: | ||
| weights (array-like): Normalized probability weights summing to 1. | ||
|
|
||
| Returns: | ||
| ndarray: Integer array of ancestor indices. | ||
| """ | ||
| N = len(weights) | ||
| weights = np.asarray(weights, dtype=float) | ||
| indexes = np.zeros(N, "i") | ||
|
|
||
| # Deterministic copies | ||
| num_copies = np.floor(N * weights).astype(int) | ||
| k = 0 | ||
| for i in range(N): | ||
| for _ in range(num_copies[i]): | ||
| indexes[k] = i | ||
| k += 1 | ||
|
|
||
| # Multinomial resample on the residual | ||
| if k < N: | ||
| residual = weights * N - num_copies | ||
| residual /= residual.sum() | ||
| cumulative_sum = np.cumsum(residual) | ||
| cumulative_sum[-1] = 1.0 | ||
| indexes[k:N] = np.searchsorted(cumulative_sum, np.random.random(N - k)) | ||
|
|
||
| return indexes | ||
|
|
||
|
|
||
| def multinomial_resample(weights): | ||
| """Multinomial resampling: independent categorical draws. | ||
|
|
||
| Each of the N ancestor indices is drawn independently from the | ||
| categorical distribution defined by the weights. | ||
|
|
||
| Args: | ||
| weights (array-like): Normalized probability weights summing to 1. | ||
|
|
||
| Returns: | ||
| ndarray: Integer array of ancestor indices. | ||
| """ | ||
| N = len(weights) | ||
| return np.array([ | ||
| np.random.choice(N, p=weights) for _ in range(N) | ||
| ], dtype=np.intp) | ||
postylem marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| RESAMPLING_METHODS = { | ||
| "systematic": systematic_resample, | ||
| "stratified": stratified_resample, | ||
| "residual": residual_resample, | ||
| "multinomial": multinomial_resample, | ||
| } | ||
|
|
||
|
|
||
| def get_resampling_fn(method): | ||
| """Get a resampling function by name. | ||
|
|
||
| Args: | ||
| method (str): One of 'systematic', 'stratified', 'residual', 'multinomial'. | ||
|
|
||
| Returns: | ||
| callable: Resampling function that takes weights and returns indices. | ||
|
|
||
| Raises: | ||
| ValueError: If method is not recognized. | ||
| """ | ||
| if method not in RESAMPLING_METHODS: | ||
| raise ValueError( | ||
| f"Unknown resampling method '{method}'. " | ||
| f"Must be one of: {', '.join(RESAMPLING_METHODS.keys())}" | ||
| ) | ||
| return RESAMPLING_METHODS[method] | ||
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
Oops, something went wrong.
Oops, something went wrong.
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.