-
-
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.
feat: Add grad_log_prob method to Model
Added grad_log_prob method to Model instances, allowing users to calculate the gradient of the log posterior evaluated at the unconstrained parameters. This feature is accompanied by a test: the grad_log_prob method is validated by comparing the output against an analytical calculation of the gradient.
- Loading branch information
1 parent
399ec6c
commit 66ce87c
Showing
2 changed files
with
75 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
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,39 @@ | ||
"""Test model with array parameter.""" | ||
import random | ||
|
||
import numpy as np | ||
import pytest | ||
|
||
import stan | ||
|
||
program = """ | ||
parameters { | ||
real y; | ||
} | ||
model { | ||
y ~ normal(0, 1); | ||
} | ||
""" | ||
|
||
num_samples = 1000 | ||
num_chains = 4 | ||
|
||
|
||
def gaussian_gradient(x: float, mean: float, var: float) -> float: | ||
"""Analytically evaluate Gaussian gradient.""" | ||
gradient = (mean - x) / (var ** 2) | ||
return gradient | ||
|
||
|
||
@pytest.fixture | ||
def posterior(request): | ||
return stan.build(request.param, random_seed=1) | ||
|
||
|
||
@pytest.mark.parametrize("posterior", [program], indirect=True) | ||
def test_grad_log_prob(posterior): | ||
"""Test log probability against sampled model with no restriction.""" | ||
y = random.uniform(0, 10) | ||
lp__ = gaussian_gradient(y, 0, 1) | ||
lp = posterior.grad_log_prob(unconstrained_parameters=[y]) | ||
assert np.allclose(lp__, lp) |