Skip to content

Adds moments for inverse gamma distribution #5199

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 2 commits into from
Nov 18, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
20 changes: 8 additions & 12 deletions pymc/distributions/continuous.py
Original file line number Diff line number Diff line change
Expand Up @@ -2334,23 +2334,19 @@ def dist(cls, alpha=None, beta=None, mu=None, sigma=None, sd=None, *args, **kwar
alpha = at.as_tensor_variable(floatX(alpha))
beta = at.as_tensor_variable(floatX(beta))

# m = beta / (alpha - 1.0)
# try:
# mean = (alpha > 1) * m or np.inf
# except ValueError: # alpha is an array
# m[alpha <= 1] = np.inf
# mean = m

# mode = beta / (alpha + 1.0)
# variance = at.switch(
# at.gt(alpha, 2), (beta ** 2) / ((alpha - 2) * (alpha - 1.0) ** 2), np.inf
# )

assert_negative_support(alpha, "alpha", "InverseGamma")
assert_negative_support(beta, "beta", "InverseGamma")

return super().dist([alpha, beta], **kwargs)

def get_moment(rv, size, alpha, beta):
mean = beta / (alpha - 1.0)
mode = beta / (alpha + 1.0)
moment = at.switch(alpha > 1, mean, mode)
if not rv_size_is_none(size):
moment = at.full(size, moment)
return moment

@classmethod
def _get_alpha_beta(cls, alpha, beta, mu, sigma):
if alpha is not None:
Expand Down
17 changes: 17 additions & 0 deletions pymc/tests/test_distributions_moments.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
HalfNormal,
HalfStudentT,
HyperGeometric,
InverseGamma,
Kumaraswamy,
Laplace,
Logistic,
Expand Down Expand Up @@ -396,6 +397,22 @@ def test_gamma_moment(alpha, beta, size, expected):
assert_moment_is_expected(model, expected)


@pytest.mark.parametrize(
"alpha, beta, size, expected",
[
(5, 1, None, 1 / 4),
(0.5, 1, None, 1 / 1.5),
(5, 1, 5, np.full(5, 1 / (5 - 1))),
(np.arange(2, 7), 1, None, 1 / np.arange(1, 6)),
(np.arange(1, 6), 1, None, np.array([0.5, 1, 1 / 2, 1 / 3, 1 / 4])),
],
)
def test_inverse_gamma_moment(alpha, beta, size, expected):
with Model() as model:
InverseGamma("x", alpha=alpha, beta=beta, size=size)
assert_moment_is_expected(model, expected)


@pytest.mark.parametrize(
"alpha, m, size, expected",
[
Expand Down