|
3 | 3 |
|
4 | 4 | from .checks import close_to
|
5 | 5 | from .models import simple_categorical, mv_simple, mv_simple_discrete, simple_2model
|
| 6 | +from .helpers import SeededTest |
| 7 | +from pymc3 import df_summary, traceplot |
6 | 8 | from pymc3.sampling import assign_step_methods, sample
|
7 | 9 | from pymc3.model import Model
|
8 | 10 | from pymc3.step_methods import (NUTS, BinaryGibbsMetropolis, CategoricalGibbsMetropolis,
|
9 | 11 | Metropolis, Slice, CompoundStep,
|
10 | 12 | MultivariateNormalProposal, HamiltonianMC)
|
11 |
| -from pymc3.distributions import Binomial, Normal, Bernoulli, Categorical |
| 13 | +from pymc3.distributions import Binomial, Normal, Bernoulli, Categorical, InverseGamma |
12 | 14 |
|
13 | 15 | from numpy.testing import assert_array_almost_equal
|
14 | 16 | import numpy as np
|
15 | 17 | from tqdm import tqdm
|
| 18 | +from scipy import stats |
16 | 19 |
|
17 | 20 |
|
18 | 21 | class TestStepMethods(object): # yield test doesn't work subclassing unittest.TestCase
|
@@ -238,3 +241,42 @@ def test_binomial(self):
|
238 | 241 | Binomial('x', 10, 0.5)
|
239 | 242 | steps = assign_step_methods(model, [])
|
240 | 243 | self.assertIsInstance(steps, Metropolis)
|
| 244 | + |
| 245 | + |
| 246 | +class TestSampleEstimates(SeededTest): |
| 247 | + def test_posterior_estimate(self): |
| 248 | + alpha_true, sigma_true = 1., 0.5 |
| 249 | + beta_true = 1. |
| 250 | + |
| 251 | + size = 1000 |
| 252 | + |
| 253 | + X = np.random.randn(size) |
| 254 | + Y = alpha_true + beta_true * X + np.random.randn(size) * sigma_true |
| 255 | + |
| 256 | + decimal = 1 |
| 257 | + with Model() as model: |
| 258 | + alpha = Normal('alpha', mu=0, sd=100, testval=alpha_true) |
| 259 | + beta = Normal('beta', mu=0, sd=100, testval=beta_true) |
| 260 | + sigma = InverseGamma('sigma', 10., testval=sigma_true) |
| 261 | + mu = alpha + beta * X |
| 262 | + Y_obs = Normal('Y_obs', mu=mu, sd=sigma, observed=Y) |
| 263 | + |
| 264 | + for step_method in (NUTS, Slice, Metropolis): |
| 265 | + trace = sample(100000, step=step_method(), progressbar=False) |
| 266 | + trace_ = trace[-300::5] |
| 267 | + |
| 268 | + # We do the same for beta - using more burnin. |
| 269 | + np.testing.assert_almost_equal(np.mean(trace_.alpha), |
| 270 | + alpha_true, decimal=decimal) |
| 271 | + np.testing.assert_almost_equal(np.mean(trace_.beta), |
| 272 | + beta_true, |
| 273 | + decimal=decimal) |
| 274 | + np.testing.assert_almost_equal(np.mean(trace_.sigma), |
| 275 | + sigma_true, decimal=decimal) |
| 276 | + |
| 277 | + # Make sure posteriors are normal |
| 278 | + _, p_alpha = stats.normaltest(trace_.alpha) |
| 279 | + _, p_beta = stats.normaltest(trace_.beta) |
| 280 | + # p-values should be > .05 to indiciate |
| 281 | + np.testing.assert_array_less(0.05, p_alpha, verbose=True) |
| 282 | + np.testing.assert_array_less(0.05, p_beta, verbose=True) |
0 commit comments