-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
add weighted ppc #2273
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
add weighted ppc #2273
Changes from 2 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
8ef4dc5
add weighted ppc
aloctavodia 2852edc
separated function for weighted ppc
aloctavodia dad7d7f
add example, fix minor issues
aloctavodia 97f4b35
Merge branch 'master' into sample_ppc_ma
aloctavodia db0da22
Create sampling.py
aloctavodia 7485aa0
Merge branch 'aloctavodia-sample_ppc_ma'
aloctavodia e282df2
rename
aloctavodia 4cca6df
Merge remote-tracking branch 'upstream/master'
aloctavodia f231a13
Merge branch 'master' into sample_ppc_ma
aloctavodia 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 |
---|---|---|
|
@@ -18,7 +18,7 @@ | |
import sys | ||
sys.setrecursionlimit(10000) | ||
|
||
__all__ = ['sample', 'iter_sample', 'sample_ppc', 'init_nuts'] | ||
__all__ = ['sample', 'iter_sample', 'sample_ppc', 'sample_ppc_w', 'init_nuts'] | ||
|
||
STEP_METHODS = (NUTS, HamiltonianMC, Metropolis, BinaryMetropolis, | ||
BinaryGibbsMetropolis, Slice, CategoricalGibbsMetropolis) | ||
|
@@ -484,14 +484,15 @@ def _update_start_vals(a, b, model): | |
|
||
a.update({k: v for k, v in b.items() if k not in a}) | ||
|
||
|
||
def sample_ppc(trace, samples=None, model=None, vars=None, size=None, | ||
random_seed=None, progressbar=True): | ||
"""Generate posterior predictive samples from a model given a trace. | ||
|
||
Parameters | ||
---------- | ||
trace : backend, list, or MultiTrace | ||
Trace generated from MCMC sampling | ||
Trace generated from MCMC sampling. | ||
samples : int | ||
Number of posterior predictive samples to generate. Defaults to the | ||
length of `trace` | ||
|
@@ -503,12 +504,20 @@ def sample_ppc(trace, samples=None, model=None, vars=None, size=None, | |
size : int | ||
The number of random draws from the distribution specified by the | ||
parameters in each sample of the trace. | ||
random_seed : int | ||
Seed for the random number generator. | ||
progressbar : bool | ||
Whether or not to display a progress bar in the command line. The | ||
bar shows the percentage of completion, the sampling speed in | ||
samples per second (SPS), and the estimated remaining time until | ||
completion ("expected time of arrival"; ETA). | ||
|
||
Returns | ||
------- | ||
samples : dict | ||
Dictionary with the variables as keys. The values corresponding | ||
to the posterior predictive samples. | ||
Dictionary with the variables as keys. The values corresponding to the | ||
posterior predictive samples. If a set of weights and a matching number | ||
of traces are provided, then the samples will be weighted. | ||
""" | ||
if samples is None: | ||
samples = len(trace) | ||
|
@@ -521,10 +530,9 @@ def sample_ppc(trace, samples=None, model=None, vars=None, size=None, | |
|
||
seed(random_seed) | ||
|
||
indices = randint(0, len(trace), samples) | ||
if progressbar: | ||
indices = tqdm(randint(0, len(trace), samples), total=samples) | ||
else: | ||
indices = randint(0, len(trace), samples) | ||
indices = tqdm(indices, total=samples) | ||
|
||
ppc = defaultdict(list) | ||
for idx in indices: | ||
|
@@ -536,6 +544,100 @@ def sample_ppc(trace, samples=None, model=None, vars=None, size=None, | |
return {k: np.asarray(v) for k, v in ppc.items()} | ||
|
||
|
||
def sample_ppc_w(traces, samples=None, models=None, size=None, weights=None, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. IMO Your approach before was better - why adding a new function instead? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think it could be potentially confusing for the user. |
||
random_seed=None, progressbar=True): | ||
"""Generate weighted posterior predictive samples from a list of models and | ||
a list of traces according to a set of weights. | ||
|
||
Parameters | ||
---------- | ||
traces : list | ||
List of traces generated from MCMC sampling. The number of traces should | ||
be equal to the number of weights. | ||
samples : int | ||
Number of posterior predictive samples to generate. Defaults to the | ||
length of the shorter trace in traces. | ||
models : list | ||
List of models used to generate the list of traces. The number of models | ||
should be equal to the number of weights and the number of observed RVs | ||
should be the same for all models. | ||
By default a single model will be inferred from `with` context, in this | ||
case results will only be meaningful if all models share the same | ||
distributions for the observed RVs. | ||
size : int | ||
The number of random draws from the distributions specified by the | ||
parameters in each sample of the trace. | ||
weights: array-like | ||
Individual weights for each trace. Default, same weight for each model. | ||
random_seed : int | ||
Seed for the random number generator. | ||
progressbar : bool | ||
Whether or not to display a progress bar in the command line. The | ||
bar shows the percentage of completion, the sampling speed in | ||
samples per second (SPS), and the estimated remaining time until | ||
completion ("expected time of arrival"; ETA). | ||
|
||
Returns | ||
------- | ||
samples : dict | ||
Dictionary with the variables as keys. The values corresponding to the | ||
posterior predictive samples from the weighted models. | ||
""" | ||
seed(random_seed) | ||
|
||
if models is None: | ||
models = [modelcontext(models)] * len(traces) | ||
|
||
if weights is None: | ||
weights = [1] * len(traces) | ||
|
||
if len(traces) != len(weights): | ||
raise ValueError('The number of traces and weights should be the same') | ||
|
||
if len(models) != len(weights): | ||
raise ValueError('The number of models and weights should be the same') | ||
|
||
lenght_morv = len(models[0].observed_RVs) | ||
if not all(len(i.observed_RVs) == lenght_morv for i in models): | ||
raise ValueError( | ||
'The number of observed RVs should be the same for all models') | ||
|
||
weights = np.asarray(weights) | ||
p = weights / np.sum(weights) | ||
|
||
min_tr = min([len(i) for i in traces]) | ||
|
||
n = (min_tr * p).astype('int') | ||
# ensure n sum up to min_tr | ||
idx = np.argmax(n) | ||
n[idx] = n[idx] + min_tr - np.sum(n) | ||
|
||
trace = np.concatenate([np.random.choice(traces[i], j) | ||
for i, j in enumerate(n)]) | ||
|
||
variables = [] | ||
for i, m in enumerate(models): | ||
variables.extend(m.observed_RVs * n[i]) | ||
|
||
len_trace = len(trace) | ||
|
||
if samples is None: | ||
samples = len_trace | ||
|
||
indices = randint(0, len_trace, samples) | ||
|
||
if progressbar: | ||
indices = tqdm(indices, total=samples) | ||
|
||
ppc = defaultdict(list) | ||
for idx in indices: | ||
param = trace[idx] | ||
var = variables[idx] | ||
ppc[var.name].append(var.distribution.random(point=param, size=size)) | ||
|
||
return {k: np.asarray(v) for k, v in ppc.items()} | ||
|
||
|
||
def init_nuts(init='ADVI', njobs=1, n_init=500000, model=None, | ||
random_seed=-1, progressbar=True, **kwargs): | ||
"""Initialize and sample from posterior of a continuous model. | ||
|
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.
tqdm progress bars need to be closed if sampling is interrupted. Some try...finally would do it.