-
-
Notifications
You must be signed in to change notification settings - Fork 58
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added log_prob method to Model instances, allowing users to calculate the log probability of a list of unconstrained parameters. This feature is accompanied by a test: the log_prob method is validated by comparing the output against the log probability (lp__) extracted from a model fit. Closes #40
- Loading branch information
1 parent
2c530b8
commit 2426d63
Showing
2 changed files
with
87 additions
and
0 deletions.
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
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,54 @@ | ||
"""Test model with array parameter.""" | ||
import numpy as np | ||
import pytest | ||
|
||
import stan | ||
|
||
unrestricted_program = """ | ||
parameters { | ||
real y; | ||
} | ||
model { | ||
y ~ normal(0, 1); | ||
} | ||
""" | ||
|
||
restricted_program = """ | ||
parameters { | ||
real<lower=0> y; | ||
} | ||
model { | ||
y ~ normal(0, 1); | ||
} | ||
""" | ||
|
||
num_samples = 1000 | ||
num_chains = 4 | ||
|
||
|
||
@pytest.fixture | ||
def posterior(request): | ||
return stan.build(request.param, random_seed=1) | ||
|
||
|
||
@pytest.mark.parametrize("posterior", [unrestricted_program], indirect=True) | ||
def test_log_prob(posterior): | ||
"""Test log probability against sampled model with unrestriction.""" | ||
fit = posterior.sample(num_chains=num_chains, num_samples=num_samples) | ||
y = fit["y"][0][0] | ||
lp__ = fit["lp__"][0][0] | ||
lp = posterior.log_prob(unconstrained_parameters=[y]) | ||
assert np.allclose(lp__, lp) | ||
|
||
|
||
@pytest.mark.parametrize("posterior", [restricted_program], indirect=True) | ||
def test_log_prob_restricted(posterior): | ||
"""Test log probability against sampled model with restriction.""" | ||
fit = posterior.sample(num_chains=num_chains, num_samples=num_samples) | ||
y = fit["y"][0][0] | ||
y = posterior.unconstrain_pars({"y": y})[0] | ||
lp__ = fit["lp__"][0][0] | ||
lp = posterior.log_prob(unconstrained_parameters=[y], adjust_transform=False) | ||
assert np.allclose(lp__, lp + y) | ||
adjusted_lp = posterior.log_prob(unconstrained_parameters=[y], adjust_transform=True) | ||
assert np.allclose(lp__, adjusted_lp) |