-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add resample method to resample from log_weights
- Loading branch information
1 parent
327e301
commit f5398eb
Showing
2 changed files
with
27 additions
and
1 deletion.
There are no files selected for viewing
This file contains 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 |
---|---|---|
@@ -1 +1 @@ | ||
all = ["importance_weights"] | ||
all = ["importance_weights", "resampling"] |
This file contains 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,26 @@ | ||
import numpy as np | ||
import cmdstanpy | ||
from retrospectr.importance_weights import extract_samples | ||
|
||
|
||
def resample(samples, log_weights, seed=0): | ||
|
||
if isinstance(samples, cmdstanpy.CmdStanMCMC): | ||
samples = extract_samples(samples) | ||
|
||
rng = np.random.default_rng(seed=seed) | ||
niters = log_weights.shape[0] | ||
nchains = log_weights.shape[1] | ||
nparams = samples.shape[2] | ||
|
||
nsamples = niters*nchains | ||
flat_log_weights = log_weights.reshape((nsamples)) | ||
|
||
resampled_iterations = rng.choice( | ||
nsamples, | ||
size=nsamples, | ||
p=np.exp(flat_log_weights)) | ||
|
||
flat_samples = samples.reshape(nsamples, 1, nparams) | ||
resampled_samples = flat_samples[resampled_iterations, :] | ||
return resampled_samples |