Skip to content
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
3 changes: 1 addition & 2 deletions ngboost/distns/gamma.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def d_score(self, Y):
D = np.zeros((len(Y), 2))
# d(-log(PDF))/dalpha
D[:, 0] = self.alpha * (
sp.special.digamma(self.alpha) - np.log(self.eps + self.beta * Y)
sp.special.digamma(self.alpha) - np.log(self.beta) - np.log(Y)
)
# d(-log(PDF))/dbeta
D[:, 1] = (self.beta * Y) - self.alpha
Expand All @@ -42,7 +42,6 @@ def __init__(self, params):
self.dist = dist(
a=self.alpha, loc=np.zeros_like(self.alpha), scale=1 / self.beta
)
self.eps = 1e-10

def fit(Y):
a, _, scale = dist.fit(Y, floc=0)
Expand Down
34 changes: 34 additions & 0 deletions tests/test_gamma_logscore.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""The Gamma score gradient must remain exact on its positive support."""

import numpy as np
import pytest
from scipy.stats import gamma

from ngboost.distns import Gamma
from ngboost.manifold import manifold
from ngboost.scores import LogScore


@pytest.mark.parametrize("alpha", [0.5, 2.0])
def test_gamma_logscore_positive_tail_gradient(alpha):
beta = np.array([1.0, 1.0, 1e-100, 1e100, 0.5, 2.0])
y = np.array([1e-20, 1e-200, 1e-100, 1e-100, 0.8, 3.0])
params = np.array([np.full(len(y), np.log(alpha)), np.log(beta)])
score_dist = manifold(LogScore, Gamma)
obj = score_dist(params)
# Closed-form digamma values avoid using the implementation's special function.
psi = 1 - np.euler_gamma if alpha == 2 else -np.euler_gamma - 2 * np.log(2)
expected = np.column_stack(
(alpha * (psi - np.log(beta) - np.log(y)), beta * y - alpha)
)
np.testing.assert_allclose(obj.score(y), -gamma.logpdf(y, alpha, scale=1 / beta))
np.testing.assert_allclose(obj.d_score(y), expected, rtol=1e-12, atol=1e-12)
for i in range(2):
step = np.zeros_like(params)
step[i] = 1e-5
numerical = (
score_dist(params + step).score(y) - score_dist(params - step).score(y)
) / 2e-5
np.testing.assert_allclose(
obj.d_score(y)[:, i], numerical, rtol=1e-7, atol=1e-7
)
Loading