Skip to content

Commit 984c743

Browse files
Allow zero rate for Poisson distribution. (#2176)
* Allow zero rate for Poisson distribution. * Add zero-rate test for sparse Poisson log likelihood evaluation. * fix: allowing rate to be zero --------- Co-authored-by: Meesum Qazalbash <meesumqazalbash@gmail.com>
1 parent df76b46 commit 984c743

2 files changed

Lines changed: 12 additions & 2 deletions

File tree

numpyro/distributions/discrete.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -762,7 +762,7 @@ class Poisson(Distribution):
762762
:meth:`log_prob`, which can speed up computation when data is sparse.
763763
"""
764764

765-
arg_constraints = {"rate": constraints.positive}
765+
arg_constraints = {"rate": constraints.greater_than_eq(0.0)}
766766
support = constraints.nonnegative_integer
767767
pytree_aux_fields = ("is_sparse",)
768768

@@ -804,7 +804,11 @@ def log_prob(self, value: ArrayLike) -> ArrayLike:
804804
)
805805
.reshape(shape)
806806
)
807-
return (jnp.log(self.rate) * value) - gammaln(value + 1) - self.rate
807+
return (
808+
xlogy(jnp.astype(value, jnp.result_type(self.rate)), self.rate)
809+
- gammaln(value + 1)
810+
- self.rate
811+
)
808812

809813
@property
810814
def mean(self) -> ArrayLike:

test/test_distributions.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1278,9 +1278,11 @@ def get_sp_dist(jax_dist):
12781278
T(dist.DiscreteUniform, np.array([-4, 3, 4, 5]), np.array([6])),
12791279
T(dist.Poisson, 2.0),
12801280
T(dist.Poisson, np.array([2.0, 3.0, 5.0])),
1281+
T(dist.Poisson, np.array([0.0, 1.0])),
12811282
T(SparsePoisson, 2.0),
12821283
T(SparsePoisson, np.array([2.0, 3.0, 5.0])),
12831284
T(SparsePoisson, 2),
1285+
T(SparsePoisson, np.array([0.0, 1.0])),
12841286
T(dist.ZeroInflatedPoisson, 0.6, 2.0),
12851287
T(dist.ZeroInflatedPoisson, np.array([0.2, 0.7, 0.3]), np.array([2.0, 3.0, 5.0])),
12861288
T(ZeroInflatedPoissonLogits, 2.0, 3.0),
@@ -2138,6 +2140,10 @@ def test_log_prob_gradient(jax_dist, sp_dist, params):
21382140
and jnp.result_type(float) == jnp.float32
21392141
):
21402142
pytest.skip(f"{jax_dist.__name__} is tested with x64 only.")
2143+
if jax_dist is dist.Poisson and jnp.any(params[0] == 0):
2144+
pytest.skip(
2145+
"finite difference gradients for Poisson with zero rate not defined"
2146+
)
21412147

21422148
rng_key = random.key(0)
21432149
value = jax_dist(*params).sample(rng_key)

0 commit comments

Comments
 (0)