Skip to content

Fix categorical random shape #3060

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 3 commits into from
Jul 20, 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
1 change: 1 addition & 0 deletions pymc3/distributions/discrete.py
Original file line number Diff line number Diff line change
Expand Up @@ -712,6 +712,7 @@ def __init__(self, p, *args, **kwargs):

def random(self, point=None, size=None):
p, k = draw_values([self.p, self.k], point=point, size=size)

return generate_samples(random_choice,
p=p,
broadcast_shape=p.shape[:-1] or (1,),
Expand Down
3 changes: 2 additions & 1 deletion pymc3/distributions/dist_math.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,8 @@ def random_choice(*args, **kwargs):
k = p.shape[-1]

if p.ndim > 1:
samples = np.row_stack([np.random.choice(k, p=p_) for p_ in p])
# If a 2d vector of probabilities is passed return a sample for each row of categorical probability
samples = np.array([np.random.choice(k, p=p_) for p_ in p])
else:
samples = np.random.choice(k, p=p, size=size)
return samples
Expand Down
8 changes: 6 additions & 2 deletions pymc3/tests/test_distributions_random.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,7 @@ def test_broadcast_shape(self, size):
@pytest.mark.parametrize('shape', [(), (1,), (1, 1), (1, 2), (10, 10, 1), (10, 10, 2)], ids=str)
def test_different_shapes_and_sample_sizes(self, shape):
prefix = self.distribution.__name__
expected = []
actual = []

rv = self.get_random_variable(shape, name='%s_%s' % (prefix, shape))
for size in (None, 1, 5, (4, 5)):
if size is None:
Expand Down Expand Up @@ -402,6 +401,11 @@ class TestCategorical(BaseTestCases.BaseTestCase):
def get_random_variable(self, shape, with_vector_params=False, **kwargs): # don't transform categories
return super(TestCategorical, self).get_random_variable(shape, with_vector_params=False, **kwargs)

def test_probability_vector_shape(self):
"""Check that if a 2d array of probabilities are passed to categorical correct shape is returned"""
p = np.ones((10, 5))
assert pm.Categorical.dist(p=p).random().shape == (10,)


class TestScalarParameterSamples(SeededTest):
def test_bounded(self):
Expand Down