Skip to content
Prev Previous commit
Next Next commit
Compare numpy scalar zero_division literals against cuml only
scikit-learn 1.9 maps numpy scalar literals such as np.int64(0) to
np.nan in _check_zero_division, whose fallback branch assumes the input
is nan without checking. cuml substitutes the given literal instead, so
comparing the two with assert_allclose fails on values cuml handles
correctly. Restrict the sklearn comparison to exact int and float
inputs, assert the literal substitution for numpy scalars, and document
the divergence in the docstring.
  • Loading branch information
VaggelisGian committed Aug 28, 2026
commit 5ba78742d9345b5929a46bf1c93ebbe11eed9d9a
2 changes: 2 additions & 0 deletions python/cuml/cuml/metrics/_classification.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,8 @@ def precision_score(
scikit-learn's label ordering. Null values are not supported. The
``'samples'`` averaging strategy, multilabel indicator input and
``zero_division=np.nan`` accepted by scikit-learn are not supported.
NumPy scalar literals such as ``np.int64(0)`` are accepted and
substituted as-is, where scikit-learn 1.9 substitutes ``np.nan``.
Unlike scikit-learn versions below 1.8, empty targets raise a
``ValueError`` instead of being scored.

Expand Down
31 changes: 23 additions & 8 deletions python/cuml/tests/test_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -450,27 +450,42 @@ def test_precision_score_zero_division_literal(zero_division):
# classes 1 and 2 are never predicted
y_true = np.array([0, 1, 2, 0, 1, 2])
y_pred = np.array([0, 0, 0, 0, 0, 0])
literal = float(zero_division)

# scikit-learn 1.9 routes numpy scalar literals through the nan branch
# of _check_zero_division, so the substitution is only compared against
# sklearn for exact int and float inputs
compare_sklearn = isinstance(zero_division, (int, float))

with warnings.catch_warnings():
warnings.simplefilter("error")
res = precision_score(
y_true, y_pred, average=None, zero_division=zero_division
)
sol = sk_precision(
y_true, y_pred, average=None, zero_division=zero_division
)
np.testing.assert_allclose(res, sol)
if compare_sklearn:
sol = sk_precision(
y_true, y_pred, average=None, zero_division=zero_division
)
if compare_sklearn:
np.testing.assert_allclose(res, sol)
else:
np.testing.assert_allclose(res, [1 / 3, literal, literal])

# binary case where pos_label is never predicted
with warnings.catch_warnings():
warnings.simplefilter("error")
res = precision_score(
np.array([0, 1]), np.array([0, 0]), zero_division=zero_division
)
sol = sk_precision(
np.array([0, 1]), np.array([0, 0]), zero_division=zero_division
)
assert res == sol == float(zero_division)
if compare_sklearn:
sol = sk_precision(
np.array([0, 1]),
np.array([0, 0]),
zero_division=zero_division,
)
assert res == literal
if compare_sklearn:
assert sol == literal


def test_precision_score_errors():
Expand Down
Loading