Skip to content

ENH Array API support for confusion_matrix - #30562

Merged
OmarManzoor merged 50 commits into
scikit-learn:mainfrom
StefanieSenger:array_api_confusion_matrix_numpy
Aug 4, 2025
Merged

OmarManzoor merged 50 commits into
scikit-learn:mainfrom
StefanieSenger:array_api_confusion_matrix_numpy

Conversation

@StefanieSenger

@StefanieSenger StefanieSenger commented Dec 30, 2024 •

Copy link
Copy Markdown
Member

Reference Issues/PRs

towards #26024
closes #30440 (supercedes)

This PR is an alternative, discussed in #30440. It accepts array inputs from all namespaces, converts the input arrays to numpy arrays right away to do the calculations in numpy (which is necessary for the coo_matrix at least) and returns the confusion_matrix in the same namespace as the input and on a cpu device.

That's what we had discussed. For more details see the discussions on both PRs.

@github-actions

github-actions Bot commented Dec 30, 2024 •

Copy link
Copy Markdown

✔️ Linting Passed

All linting checks passed. Your pull request is in excellent shape! ☀️

Generated for commit: 5b103e7. Link to the linter CI: here

Comment thread sklearn/utils/_array_api.py Resolved
Comment on lines +3120 to +3127
result = confusion_matrix(y_true, y_pred)
xp_result, _ = get_namespace(result)
assert _is_numpy_namespace(xp_result)

# Since the computation always happens with NumPy / SciPy on the CPU, this
# function is expected to return an array allocated on the CPU even when it does
# not match the input array's device.
assert result.device == "cpu"

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have adjusted this test to your suggestions from this comment, @ogrisel. But here, the test is narrower because we made the return value of confusion_matrix to always be a numpy array on cpu.

@StefanieSenger

Copy link
Copy Markdown
Member Author

Regarding the question how to document the return type of confusion_matrix() as a numpy array, I think that keeping
C : ndarray of shape (n_classes, n_classes) in the docstring should be enough, assumed that all the other functions and methods where we have added array api support document the return value type correctly, which is currently not the case.

Comment thread sklearn/utils/_array_api.py Resolved

@virchan virchan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suspect the CI failure (about the Test Library) is a false positive, as I couldn't reproduce the same error after running the tests multiple times on my local machine. Instead, I encountered a different set of errors related to CUDA. I believe the issue might be linked to how we convert sample_weight into a NumPy array.

Comment thread sklearn/metrics/_classification.py Resolved

@StefanieSenger StefanieSenger left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your reviews, @OmarManzoor and @lesteve!
I have applied your suggestions and commented regarding the documentation.

Now, this PR looks very straightforward. :)

Comment thread doc/modules/array_api.rst Resolved
Comment thread sklearn/metrics/_classification.py Resolved

@lesteve lesteve left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks!

@ogrisel ogrisel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM beside the point below.

I am not sure how to best document which scikit-learn functions and classes intentionally rely on internal array API namespace conversions (https://github.com/scikit-learn/scikit-learn/pull/30562/files#r2207423623). I think it's interesting to do it but I agree we can discuss that in a follow-up issue or PR.

Comment thread sklearn/metrics/_classification.py Resolved

@OmarManzoor OmarManzoor left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thanks @StefanieSenger

@OmarManzoor

Copy link
Copy Markdown
Contributor

There are some tests failing which may need to be checked

@lesteve

lesteve commented Aug 1, 2025

Copy link
Copy Markdown
Member

Hmm probably some weird interaction with #31701?

@lesteve

lesteve commented Aug 1, 2025 •

Copy link
Copy Markdown
Member

In d1b3439 we fixed the latest failures in the most straightforward (but maybe a bit hacky) way. We also added a test that would have failed in #31701 and would have surfaced the issue.

The tension comes from:

A maybe more clean approach would be to pass an additional argument ensure_min_samples in _check_targets that gets passed to _check_sample_weight and eventually to ensure that ensure_min_samples=ensure_min_samples is passed to the check_array(sample_weight) call. This seems a bit too much since it seems like confusion_matrix is a bit special in being able to handle empty inputs?

@OmarManzoor

Copy link
Copy Markdown
Contributor

@lesteve Thanks for the fixes. I think the current changes look fine. However the approach that you have mentioned about adding in ensure_min_samples also sounds good. Wouldn't that approach be better considering that such a parameter is actually available in the check_array function?

@ogrisel

ogrisel commented Aug 4, 2025

Copy link
Copy Markdown
Member

I am also fine the current workaround implemented in this PR as it is well explained by the inline comment.

+1 for exploring the refactoring suggested by @lesteve in a follow-up PR.

@OmarManzoor

OmarManzoor commented Aug 4, 2025 •

Copy link
Copy Markdown
Contributor

Let's merge this then!

@OmarManzoor
OmarManzoor enabled auto-merge (squash) August 4, 2025 08:22
@OmarManzoor
OmarManzoor merged commit 1ff785e into scikit-learn:main Aug 4, 2025
@StefanieSenger
StefanieSenger deleted the array_api_confusion_matrix_numpy branch August 4, 2025 11:15
lucyleeow pushed a commit to lucyleeow/scikit-learn that referenced this pull request Aug 22, 2025
Co-authored-by: Virgil Chan <[email protected]>
Co-authored-by: Olivier Grisel <[email protected]>
Co-authored-by: Loïc Estève <[email protected]>
Co-authored-by: Omar Salman <[email protected]>
@jeremiedbb jeremiedbb mentioned this pull request Sep 3, 2025
13 tasks done
Comment on lines +511 to +516
# This is needed to handle the special case where y_true, y_pred and
# sample_weight are all empty.
# In this case we don't pass sample_weight to _check_targets that would
# check that sample_weight is not empty and we don't reuse the returned
# sample_weight
y_type, y_true, y_pred, _ = _check_targets(y_true, y_pred)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@StefanieSenger could you expand on why this branch is needed?
In the case where "y_true, y_pred and sample_weight are all empty" (as per your comment), it would error here:

for array in [y_true, y_pred]:
if _num_samples(array) < 1:
raise ValueError(
"Found empty input array (e.g., `y_true` or `y_pred`) while a minimum "
"of 1 sample is required."

When just y_true, y_pred are empty, not sample_weight provided, it would also error at the same place.

If only sample_weight was empty, this then raises an error:

cm = coo_array(
(sample_weight, (y_true, y_pred)),
shape=(n_labels, n_labels),
dtype=dtype,
).toarray()

But I am not sure why this would be better than passing sample_weight to _check_targets and letting it raise the error?

Maybe you could provide an example/test for the case that this branch is for? Thanks!

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

gentle ping @StefanieSenger

xref: #34221

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm afraid I cannot answer that question as I didn't commit this: d1b3439
I would agree that erroring in _check_targets if no sample_weight is provided is fine.

@StefanieSenger StefanieSenger Jun 18, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, it seems this test were @lesteve had added the condition (test_confusion_matrix_on_zero_length_input) is now gone.
I am not sure where and why it was removed. I will check with git grap (later)

@StefanieSenger StefanieSenger Jun 18, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have removed it in #32549 when we removed support for empty inputs. 😆
So the if-else is indeed not needed anymore.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you! 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants