Skip to content

Commit 056d5cf

Browse files
authored
FIX np.divide undefined behaviour with where in gaussian processes (#24245)
1 parent c1330a2 commit 056d5cf

File tree

3 files changed

+14
-5
lines changed

3 files changed

+14
-5
lines changed

doc/whats_new/v1.2.rst

+7
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,13 @@ Changelog
208208
:mod:`sklearn.feature_selection`
209209
................................
210210

211+
:mod:`sklearn.gaussian_process`
212+
...............................
213+
214+
- |Fix| Fix :class:`gaussian_process.kernels.Matern` gradient computation with
215+
`nu=0.5` for PyPy (and possibly other non CPython interpreters). :pr:`24245`
216+
by :user:`Loïc Estève <lesteve>`.
217+
211218
:mod:`sklearn.linear_model`
212219
...........................
213220

sklearn/gaussian_process/kernels.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -1733,9 +1733,14 @@ def __call__(self, X, Y=None, eval_gradient=False):
17331733

17341734
if self.nu == 0.5:
17351735
denominator = np.sqrt(D.sum(axis=2))[:, :, np.newaxis]
1736-
K_gradient = K[..., np.newaxis] * np.divide(
1737-
D, denominator, where=denominator != 0
1736+
divide_result = np.zeros_like(D)
1737+
np.divide(
1738+
D,
1739+
denominator,
1740+
out=divide_result,
1741+
where=denominator != 0,
17381742
)
1743+
K_gradient = K[..., np.newaxis] * divide_result
17391744
elif self.nu == 1.5:
17401745
K_gradient = 3 * D * np.exp(-np.sqrt(3 * D.sum(-1)))[..., np.newaxis]
17411746
elif self.nu == 2.5:

sklearn/gaussian_process/tests/test_kernels.py

-3
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@
3434
assert_array_equal,
3535
assert_array_almost_equal,
3636
assert_allclose,
37-
fails_if_pypy,
3837
)
3938

4039

@@ -70,8 +69,6 @@
7069
kernels.append(PairwiseKernel(gamma=1.0, metric=metric))
7170

7271

73-
# Numerical precisions errors in PyPy
74-
@fails_if_pypy
7572
@pytest.mark.parametrize("kernel", kernels)
7673
def test_kernel_gradient(kernel):
7774
# Compare analytic and numeric gradient of kernels.

0 commit comments

Comments
 (0)