Skip to content

Improve random for ObservedRV #3036

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 1 commit into from
Jun 18, 2018
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
12 changes: 11 additions & 1 deletion pymc3/distributions/distribution.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,17 @@ def _draw_value(param, point=None, givens=None, size=None):
elif (hasattr(param, 'distribution') and
hasattr(param.distribution, 'random') and
param.distribution.random is not None):
return param.distribution.random(point=point, size=size)
# reset the dist shape for ObservedRV
if hasattr(param, 'observations'):
dist_tmp = param.distribution
try:
distshape = param.observations.shape.eval()
except AttributeError:
distshape = param.observations.shape
dist_tmp.shape = distshape
return dist_tmp.random(point=point, size=size)
else:
return param.distribution.random(point=point, size=size)
else:
if givens:
variables, values = list(zip(*givens))
Expand Down
24 changes: 22 additions & 2 deletions pymc3/tests/test_sampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@ def test_ignores_observed(self):
assert (prior['mu'] < 90).all()
assert (prior['positive_mu'] > 90).all()
assert (prior['x_obs'] < 90).all()
assert prior['x_obs'].shape == (500, 200)
npt.assert_array_almost_equal(prior['positive_mu'], np.abs(prior['mu']), decimal=4)

def test_respects_shape(self):
Expand Down Expand Up @@ -395,9 +396,28 @@ def test_transformed(self):

thetas = pm.Beta('thetas', alpha=phi*kappa, beta=(1.0-phi)*kappa, shape=n)

y = pm.Binomial('y', n=at_bats, p=thetas, shape=n, observed=hits)
y = pm.Binomial('y', n=at_bats, p=thetas, observed=hits)
gen = pm.sample_prior_predictive(draws)

assert gen['phi'].shape == (draws,)
assert gen['y'].shape == (draws, n)
assert 'thetas_logodds__' in gen
assert 'thetas_logodds__' in gen

def test_shared(self):
n1 = 10
obs = shared(np.random.rand(n1) < .5)
draws = 50

with pm.Model() as m:
p = pm.Beta('p', 1., 1.)
y = pm.Bernoulli('y', p, observed=obs)
gen1 = pm.sample_prior_predictive(draws)

assert gen1['y'].shape == (draws, n1)

n2 = 20
obs.set_value(np.random.rand(n2) < .5)
with m:
gen2 = pm.sample_prior_predictive(draws)

assert gen2['y'].shape == (draws, n2)