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 3 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
19 changes: 6 additions & 13 deletions pymc/distributions/multivariate.py
Original file line number Diff line number Diff line change
Expand Up @@ -2192,32 +2192,25 @@ 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,)
size = alpha.shape + (K,)
alpha = alpha[..., np.newaxis]
purna135 marked this conversation as resolved.
Show resolved Hide resolved
else:
size = tuple(size) + (K,)
size = size + (K,)

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

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

from pymc.distributions.continuous import get_tau_sigma
from pymc.distributions.dist_math import betaln
from pymc.util import UNSET

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


def _stickbreakingweights_logpdf(value, alpha, K):
purna135 marked this conversation as resolved.
Show resolved Hide resolved
purna135 marked this conversation as resolved.
Show resolved Hide resolved
logp = -at.sum(
at.log(
at.cumsum(
value[..., ::-1],
axis=-1,
)
),
axis=-1,
)
logp += -K * betaln(1, alpha)
logp += alpha * at.log(value[..., -1])
logp = at.switch(
at.or_(
at.any(
at.and_(at.le(value, 0), at.ge(value, 1)),
axis=-1,
),
at.or_(
at.bitwise_not(at.allclose(value.sum(-1), 1)),
at.neq(value.shape[-1], K + 1),
),
),
-np.inf,
logp,
)
return logp.eval()


stickbreakingweights_logpdf = np.vectorize(_stickbreakingweights_logpdf, signature="(n),(),()->()")


class TestMatchesScipy:
def test_uniform(self):
check_logp(
Expand Down Expand Up @@ -2312,6 +2345,28 @@ 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(
"value, alpha, K",
[
(np.array([5, 4, 3, 2, 1]) / 15, [0.5, 1.0, 2.0], 19),
(
np.append(0.5 ** np.arange(1, 20), 0.5**20),
np.arange(1, 7, dtype="float64").reshape(2, 3),
4,
),
],
)
def test_stickbreakingweights_vectorized(self, value, alpha, K):
purna135 marked this conversation as resolved.
Show resolved Hide resolved
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),
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]
purna135 marked this conversation as resolved.
Show resolved Hide resolved
sizes_expected = [(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