Skip to content
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

Allow for batched alpha in StickBreakingWeights #6042

Merged
merged 7 commits into from
Aug 31, 2022
Merged
Show file tree
Hide file tree
Changes from 6 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
21 changes: 6 additions & 15 deletions pymc/distributions/multivariate.py
Original file line number Diff line number Diff line change
Expand Up @@ -2192,32 +2192,23 @@ def make_node(self, rng, size, dtype, alpha, K):
alpha = at.as_tensor_variable(alpha)
K = at.as_tensor_variable(intX(K))

if alpha.ndim > 0:
raise ValueError("The concentration parameter needs to be a scalar.")

if K.ndim > 0:
raise ValueError("K must be a scalar.")

return super().make_node(rng, size, dtype, alpha, K)

def _infer_shape(self, size, dist_params, param_shapes=None):
alpha, K = dist_params

size = tuple(size)

return size + (K + 1,)
def _supp_shape_from_params(self, dist_params, **kwargs):
K = dist_params[1]
return (K + 1,)

@classmethod
def rng_fn(cls, rng, alpha, K, size):
if K < 0:
raise ValueError("K needs to be positive.")

if size is None:
size = (K,)
elif isinstance(size, int):
size = (size,) + (K,)
else:
size = tuple(size) + (K,)
size = to_tuple(size) if size is not None else alpha.shape
size = size + (K,)
purna135 marked this conversation as resolved.
Show resolved Hide resolved
alpha = alpha[..., np.newaxis]

betas = rng.beta(1, alpha, size=size)

Expand Down
38 changes: 38 additions & 0 deletions pymc/tests/test_distributions.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from aeppl.logprob import ParameterValueError
from aesara.tensor.random.utils import broadcast_params

from pymc.aesaraf import compile_pymc
from pymc.distributions.continuous import get_tau_sigma
from pymc.util import UNSET

Expand Down Expand Up @@ -952,6 +953,24 @@ def test_hierarchical_obs_logp():
assert not any(isinstance(o, RandomVariable) for o in ops)


@pytest.fixture(scope="module")
def _compile_stickbreakingweights_logpdf():
_value = at.vector()
_alpha = at.scalar()
_k = at.iscalar()
_logp = logp(StickBreakingWeights.dist(_alpha, _k), _value)
return compile_pymc([_value, _alpha, _k], _logp)


def _stickbreakingweights_logpdf(value, alpha, k, _compile_stickbreakingweights_logpdf):
return _compile_stickbreakingweights_logpdf(value, alpha, k)


stickbreakingweights_logpdf = np.vectorize(
_stickbreakingweights_logpdf, signature="(n),(),(),()->()"
)
ricardoV94 marked this conversation as resolved.
Show resolved Hide resolved


class TestMatchesScipy:
def test_uniform(self):
check_logp(
Expand Down Expand Up @@ -2312,6 +2331,25 @@ def test_stickbreakingweights_invalid(self):
assert pm.logp(sbw, np.array([0.4, 0.3, 0.2, -0.1])).eval() == -np.inf
assert pm.logp(sbw_wrong_K, np.array([0.4, 0.3, 0.2, 0.1])).eval() == -np.inf

@pytest.mark.parametrize(
"alpha,K",
[
(np.array([0.5, 1.0, 2.0]), 3),
(np.arange(1, 7, dtype="float64").reshape(2, 3), 5),
],
)
def test_stickbreakingweights_vectorized(self, alpha, K, _compile_stickbreakingweights_logpdf):
value = pm.StickBreakingWeights.dist(alpha, K).eval()
with Model():
sbw = StickBreakingWeights("sbw", alpha=alpha, K=K, transform=None)
pt = {"sbw": value}
assert_almost_equal(
pm.logp(sbw, value).eval(),
stickbreakingweights_logpdf(value, alpha, K, _compile_stickbreakingweights_logpdf),
decimal=select_by_precision(float64=6, float32=2),
err_msg=str(pt),
)

@aesara.config.change_flags(compute_test_value="raise")
def test_categorical_bounds(self):
with Model():
Expand Down
12 changes: 12 additions & 0 deletions pymc/tests/test_distributions_random.py
Original file line number Diff line number Diff line change
Expand Up @@ -1321,6 +1321,18 @@ def check_basic_properties(self):
assert np.all(draws <= 1)


class TestStickBreakingWeights_1D_alpha(BaseTestDistributionRandom):
pymc_dist = pm.StickBreakingWeights
pymc_dist_params = {"alpha": [1.0, 2.0, 3.0], "K": 19}
expected_rv_op_params = {"alpha": [1.0, 2.0, 3.0], "K": 19}
sizes_to_check = [None, (3,), (5, 3)]
sizes_expected = [(3, 20), (3, 20), (5, 3, 20)]
checks_to_run = [
"check_pymc_params_match_rv_op",
"check_rv_size",
]


class TestCategorical(BaseTestDistributionRandom):
pymc_dist = pm.Categorical
pymc_dist_params = {"p": np.array([0.28, 0.62, 0.10])}
Expand Down