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

Add ICDF and CDF to BernoulliProbs #1652

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
7 changes: 7 additions & 0 deletions numpyro/distributions/discrete.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,13 @@ def mean(self):
def variance(self):
return self.probs * (1 - self.probs)

def cdf(self, value):
return ((1 - self.probs) * jnp.heaviside(value, 1)
+ self.probs * jnp.heaviside(value - 1, 1))

def icdf(self, q):
return jnp.heaviside(q - (1 - self.probs), 1)

def enumerate_support(self, expand=True):
values = jnp.arange(2).reshape((-1,) + (1,) * len(self.batch_shape))
if expand:
Expand Down
13 changes: 10 additions & 3 deletions test/test_distributions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1387,7 +1387,7 @@ def test_mixture_log_prob():
@pytest.mark.parametrize(
"jax_dist, sp_dist, params",
# TODO: add more complete pattern for Discrete.cdf
CONTINUOUS + [T(dist.Poisson, 2.0), T(dist.Poisson, np.array([2.0, 3.0, 5.0]))],
CONTINUOUS + [T(dist.Poisson, 2.0), T(dist.Poisson, np.array([2.0, 3.0, 5.0])), T(dist.BernoulliProbs, 0.2)],
)
@pytest.mark.filterwarnings("ignore:overflow encountered:RuntimeWarning")
def test_cdf_and_icdf(jax_dist, sp_dist, params):
Expand All @@ -1411,8 +1411,15 @@ def test_cdf_and_icdf(jax_dist, sp_dist, params):
atol=1e-5,
rtol=rtol,
)
assert_allclose(d.cdf(d.icdf(quantiles)), quantiles, atol=1e-5, rtol=1e-5)
assert_allclose(d.icdf(d.cdf(samples)), samples, atol=1e-5, rtol=rtol)
if jax_dist is dist.BernoulliProbs:
assert pytest.approx(d.icdf(quantiles).mean(), abs=0.1) == d.probs
prop_of_ones = (d.cdf(d.icdf(quantiles)) == 1).mean()
prop_of_zeros = (d.cdf(d.icdf(quantiles)) == (1 - d.probs)).mean()
assert pytest.approx(prop_of_ones, abs=0.1) == d.probs
assert pytest.approx(prop_of_zeros, abs=0.1) == (1 - d.probs)
else:
assert_allclose(d.cdf(d.icdf(quantiles)), quantiles, atol=1e-5, rtol=1e-5)
assert_allclose(d.icdf(d.cdf(samples)), samples, atol=1e-5, rtol=rtol)
except NotImplementedError:
pass

Expand Down
Loading