Skip to content
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

SMC: replace multinomial sampling with systematic sampling #6162

Merged
merged 2 commits into from
Sep 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 31 additions & 3 deletions pymc/smc/smc.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,9 +274,7 @@ def update_beta_and_weights(self):

def resample(self):
"""Resample particles based on importance weights"""
self.resampling_indexes = self.rng.choice(
np.arange(self.draws), size=self.draws, p=self.weights
)
self.resampling_indexes = systematic_resampling(self.weights, self.rng)

self.tempered_posterior = self.tempered_posterior[self.resampling_indexes]
self.prior_logp = self.prior_logp[self.resampling_indexes]
Expand Down Expand Up @@ -546,6 +544,36 @@ def sample_settings(self):
return stats


def systematic_resampling(weights, rng):
"""
Systematic resampling.

Parameters
----------
weights :
The weights should be probabilities and the total sum should be 1.

Returns
-------
new_indices: array
A vector of indices in the interval 0, ..., len(normalized_weights)
"""
lnw = len(weights)
arange = np.arange(lnw)
uniform = (rng.random(1) + arange) / lnw

idx = 0
weight_accu = weights[0]
new_indices = np.empty(lnw, dtype=int)
for i in arange:
while uniform[i] > weight_accu:
idx += 1
weight_accu += weights[idx]
new_indices[i] = idx

return new_indices


def _logp_forw(point, out_vars, in_vars, shared):
"""Compile Aesara function of the model and the input and output variables.

Expand Down
8 changes: 8 additions & 0 deletions pymc/tests/test_smc.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,3 +286,11 @@ def test_proposal_dist_shape(self):
kernel=pm.smc.MH,
return_inferencedata=False,
)


def test_systematic():
rng = np.random.default_rng(seed=34)
weights = [0.33, 0.33, 0.33]
np.testing.assert_array_equal(pm.smc.systematic_resampling(weights, rng), [0, 1, 2])
weights = [0.99, 0.01]
np.testing.assert_array_equal(pm.smc.systematic_resampling(weights, rng), [0, 0])