Skip to content

FEA Add array API support for average_precision_score - #32909

Merged
lucyleeow merged 23 commits into
scikit-learn:mainfrom
StefanieSenger:array_api_average_precision_score
Jan 23, 2026
Merged

lucyleeow merged 23 commits into
scikit-learn:mainfrom
StefanieSenger:array_api_average_precision_score

Conversation

@StefanieSenger

@StefanieSenger StefanieSenger commented Dec 16, 2025 •

Copy link
Copy Markdown
Member

Reference Issues/PRs

towards #26024

What does this implement/fix? Explain your changes.

Adds array API support to average_precision_score

AI usage disclosure

I used AI assistance for:

  • Code generation (e.g., when writing an implementation or fixing a bug)
  • Test/benchmark generation
  • Documentation (including examples)
  • Research and understanding

Any other comments?

WIP

TODO:

  • add array API in average_precision_score
  • add common metrics test
  • add average_precision_score to the array API docs
  • removed old fix for numpy<= 1.24.1 from average_precision_score as well as from _check_set_wise_labels which allows to have present_labels as an array instead of a list
  • use LabelBinarizer instead of label_binarize # TODO: check if in fact necessary
  • add array API in _average_binary_score
  • fix remaining test failures
  • add changelog
  • make it accept mixed namespace inputs
  • (only necessary if TST Add common test for mixed array API inputs for metrics #32755 is merged first) add new test case for average_precision_score in METRICS_SUPPORTING_MIXED_NAMESPACE in sklearn/metrics/tests/test_common.py

Comment thread sklearn/metrics/_base.py Resolved
Comment thread sklearn/metrics/_classification.py Resolved
@StefanieSenger StefanieSenger moved this to In progress - High Priority in Labs Dec 16, 2025
@StefanieSenger StefanieSenger changed the title Add array API support for average_precision_score Add array API support for average_precision_score Dec 16, 2025
Comment on lines +2100 to +2111
if metric.__name__ == "average_precision_score":
# we need y_pred_nd to be of shape (n_samples, n_classes
y_pred_np = np.array(
[
[0.7, 0.2, 0.05, 0.05],
[0.1, 0.8, 0.05, 0.05],
[0.1, 0.1, 0.7, 0.1],
[0.05, 0.05, 0.1, 0.8],
],
dtype=dtype_name,
)

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.

This case handling needs to be added, because average_precision_score handels multiclass inputs by binarising it. As a consequence, y_score needs to be of shape (n_samples, n_classes). I have made a PR with a fix here: #32912.

Comment thread sklearn/metrics/_ranking.py Resolved
Comment thread sklearn/metrics/_base.py
if average_weight is not None:
# Scores with 0 weights are forced to be 0, preventing the average
# score from being affected by 0-weighted NaN elements.
average_weight = np.asarray(average_weight)

@StefanieSenger StefanieSenger Dec 16, 2025 •

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.

This is not needed anymore, since average_weight is converted to an array earlier.

Comment thread sklearn/metrics/_ranking.py Outdated
Comment on lines +232 to +236
if not get_config().get("array_api_dispatch", False):
y_true = _convert_to_numpy(y_true, xp=xp)
y_score = _convert_to_numpy(y_score, xp=xp)
if sample_weight is not None:
sample_weight = _convert_to_numpy(sample_weight, xp=xp)

@StefanieSenger StefanieSenger Dec 17, 2025 •

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.

This (hopefully) fixes an error occurring on the CI (link to output):

E TypeError: sum() received an invalid combination of arguments - got (out=NoneType, axis=int, ), but expected one of:
E * (*, torch.dtype dtype = None)
E  didn't match because some of the keywords were incorrect: out, axis
E  * (tuple of ints dim, bool keepdim = False, *, torch.dtype dtype = None)
E  * (tuple of names dim, bool keepdim = False, *, torch.dtype dtype = None)

@lesteve and I investigated this together. It seems that numpy.sum() when passed a torch tensor, internally tries to dispatch to torch, but that fails because torch.sum() doesn't have the out argument. The same happens with np.repeat() which has an axis argument, but torch.repeat() hasn't (which had raised in my setup locally).

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.

Yes, I ran into the same issue when I was working on roc_auc_score.

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.

Instead of converting everything to NumPy ahead of time, we should inspect the namespace and device of y_score only. Indeed, we want to allow y_true to have an object dtype for string class labels (hence a NumPy array) even when the predictions are a non-NumPy namespace with a non-CPU device.

See: https://scikit-learn.org/dev/modules/array_api.html#scoring-functions

y_true should thereafter convert to binary indicators (using pos_label when available, and moved to the same device, dtype and namespace as y_score just before doing the arithmetic computation.

sample_weight should similarly follow the namespace, dtype and device of y_score using move_to.

See the discussion and implementation of the common test being worked on in #32755 for mixed input metrics.

@StefanieSenger StefanieSenger Dec 26, 2025 •

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 will keep your comment in mind for later, but this here addresses a different problem. It fixes a test failure if array api is not enabled and all inputs (specifically y_true and y_score) are torch tensors on cpu.

In check_array_api_metric() we have defined a numpy_as_array_works boolean that is True if array api is not enabled, but we get input from a non-numpy namespace that can be converted to numpy (see here):

    # When array API dispatch is disabled, and np.asarray works (for example PyTorch
    # with CPU device), calling the metric function with such numpy compatible inputs
    # should work (albeit by implicitly converting to numpy arrays instead of
    # dispatching to the array library).
    try:
        np.asarray(a_xp)
        np.asarray(b_xp)
        numpy_as_array_works = True

In this case, we feed two torch arrays into the metric, but the test fails (see here):

    if numpy_as_array_works:
        metric_xp = metric(a_xp, b_xp, **metric_kwargs)

If I have understood correctly, then we would always try to convert to numpy, if get_config().get("array_api_dispatch", False) but the input would be convertible to numpy, and making sure that we do is the purpose of this test (added in #30454).

(In this WIP PR I haven't taken care of mixed inputs at all yet, also #32755 is not merged yet.
See:
image
)

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.

Maybe we could add a comment about why we are doing this?

Just to clarify, what was previously doing the asarray for torch inputs? type_of_target does do check_array, but does that not fix the error?

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.

Then, the next question is whether this is a good way to fix this, and what are the alternatives.

What I like about this is that it is very explicit. check_array would be almost as explicit, but a conversion to numpy happening by array operations (somewhere in the code) would be very implicit and dependent on the current implementation. Since we see that we get hard to debug errors, I would not be in favour if this solution.

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.

precision_recall_curve indeed does that, but average_precision_score does not.

But doesn't average_precision_score call precision_recall_curve ?

It fixes a test failure if array api is not enabled and all inputs (specifically y_true and y_score) are torch tensors on cpu.

My understanding of this is that the following code is meant to an error (when dispatch is disabled - explicitly set here):

    import torch
    from sklearn.metrics import average_precision_score

    y_scores = torch.tensor([0.1, 0.4, 0.35, 0.8], device='cpu')
    y_true = torch.tensor([0, 0, 1, 1], device='cpu')
    with config_context(array_api_dispatch=False):
        average_precision_score(y_true, y_scores)

Thus to make testing easier, I checked the above on main (works fine) and on this branch with the above lines commented out (works as well).

From what I can follow, the inputs are converted to numpy arrays?
average_precision_score calls precision_recall_curve calls confusion_matrix_at_thresholds which calls column_or_1d on y_true and y_score ?

@StefanieSenger StefanieSenger Jan 9, 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.

But doesn't average_precision_score call precision_recall_curve ?

I think the changes made to y_true and y_score made in precision_recall_curve stay local.

Thus to make testing easier, I checked the above on main (works fine) and on this branch with the above lines commented out (works as well).

Interesting. It fails on the mps CI (but fails on a different test case for a similar reason (at np.repeat) locally for me on linux).

From what I can follow, the inputs are converted to numpy arrays?
average_precision_score calls precision_recall_curve calls confusion_matrix_at_thresholds which calls column_or_1d on y_true and y_score ?

Let me actually comment out this patch and push, so you can inspect on CI.

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.

Here it is: #33028

I have opened a new PR for this to have the CI run and also to explore alternative solutions there.

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 changed this code according to my suggestion in #33028 (comment).

Please let me know if that's not a good solution in your opinion. Happy to change it.

Comment thread sklearn/metrics/_ranking.py Resolved
Comment thread sklearn/metrics/_base.py Resolved
Comment thread sklearn/metrics/_base.py Outdated

import sklearn.externals.array_api_extra as xpx
from sklearn.utils import check_array, check_consistent_length
from sklearn.utils._array_api import _ravel, get_namespace_and_device

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.

Suggested change
from sklearn.utils._array_api import _ravel, get_namespace_and_device
from sklearn.utils._array_api import _ravel, get_namespace_and_device, xpx

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 wasn't aware of that, and maybe that had been discussed somewhere I missed. So I did a bit of searching and I have found xpx imported via _array_api.py in sklearn/model_selection/_search.py and in sklearn/tree/tests/test_tree.py.
And I have found from sklearn.externals import array_api_extra as xpx imports in three other files.

I prefer the more explicit import from sklearn.externals, since it is easier to see what is going on the first glance even if you are unfamiliar with array api, and it will have to be obvious for people unfamilar with array api, as it will be in every function in the future and we also want to make it easy for future contributors.

Comment thread sklearn/metrics/_ranking.py Outdated
Comment on lines +232 to +236
if not get_config().get("array_api_dispatch", False):
y_true = _convert_to_numpy(y_true, xp=xp)
y_score = _convert_to_numpy(y_score, xp=xp)
if sample_weight is not None:
sample_weight = _convert_to_numpy(sample_weight, xp=xp)

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.

Yes, I ran into the same issue when I was working on roc_auc_score.

@github-actions github-actions Bot removed the CUDA CI label Dec 19, 2025
@StefanieSenger StefanieSenger changed the title Add array API support for average_precision_score FEA Add array API support for average_precision_score Dec 19, 2025
@StefanieSenger

Copy link
Copy Markdown
Member Author

Commit 3a9b788 had caused AttributeError: 'list' object has no attribute 'dtype' for weighted_ovr_roc_auc and weighted_roc_auc. (CI output: https://github.com/scikit-learn/scikit-learn/actions/runs/21099327740/job/60681250707?pr=32909)

The reason is that also in there we hadn't converted sample_weight into an array early.

In 299fda1 I have added

    if sample_weight is not None:
        sample_weight = column_or_1d(sample_weight)

in roc_auc_score as well to fix this. We will need it there anyways when we introduce array api support.

@adrinjalali adrinjalali 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.

As far as I can tell, LGTM.

@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.

LGTM as well! Thanks, @StefanieSenger!

Just one minor nitpick.

Also, perhaps @lucyleeow or @ogrisel could take a look before merging.

Comment thread sklearn/metrics/_base.py Resolved

@lucyleeow lucyleeow 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.

Nits and a question, otherwise looks good!

Comment thread sklearn/metrics/tests/test_common.py Resolved
Comment thread sklearn/metrics/_base.py Resolved
Comment thread sklearn/metrics/_base.py Resolved
Comment on lines +701 to +702
if sample_weight is not None:
sample_weight = column_or_1d(sample_weight)

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 probably missed something by why the changes to roc_auc_score ?

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.

roc_auc_score shares _average_binary_score as a common helper function with average_binary_score. With the changes in there, we now get an error there (AttributeError: 'list' object has no attribute 'dtype') because roc_auc_score had previously not handled sample_weight correctly either.

@StefanieSenger

Copy link
Copy Markdown
Member Author
image Seems the CI cannot checkout the scikit-learn repo. This error is unrelated to this PR and (as of now) did not occur in any other PR (Actions tab looks fine, except for this PR).

Hopefully this is just a temporary issue. I will re-trigger the CI later to see if it will work then.

@lucyleeow

Copy link
Copy Markdown
Member

Thanks for your patience and perseverance @StefanieSenger ! Let's get this in!

@lucyleeow
lucyleeow merged commit 492ad11 into scikit-learn:main Jan 23, 2026
@github-project-automation github-project-automation Bot moved this from In progress - High Priority to Done in Labs Jan 23, 2026
@github-project-automation github-project-automation Bot moved this from In Progress to Done in Array API Jan 23, 2026
@StefanieSenger
StefanieSenger deleted the array_api_average_precision_score branch January 23, 2026 07:42
@StefanieSenger

Copy link
Copy Markdown
Member Author

Thanks to everybody who has reviewed. 💟

dschult pushed a commit to dschult/scikit-learn that referenced this pull request Jan 25, 2026
dschult pushed a commit to dschult/scikit-learn that referenced this pull request Jan 25, 2026
TejasAnalyst pushed a commit to TejasAnalyst/scikit-learn that referenced this pull request Feb 10, 2026
@adrinjalali adrinjalali removed this from Labs Mar 9, 2026
tonybaloney pushed a commit to tonybaloney/swe-complex-scikit-learn that referenced this pull request Mar 19, 2026
tonybaloney pushed a commit to tonybaloney/swe-complex-scikit-learn that referenced this pull request Mar 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

6 participants