Repository navigation
Conversation
average_precision_score
| 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, | ||
| ) | ||
|
|
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
This is not needed anymore, since average_weight is converted to an array earlier.
| 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) |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
Yes, I ran into the same issue when I was working on roc_auc_score.
There was a problem hiding this comment.
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.
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.
There was a problem hiding this comment.
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 = TrueIn 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:

)
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 ?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Here it is: #33028
I have opened a new PR for this to have the CI run and also to explore alternative solutions there.
There was a problem hiding this comment.
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.
|
|
||
| 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 |
There was a problem hiding this comment.
| from sklearn.utils._array_api import _ravel, get_namespace_and_device | |
| from sklearn.utils._array_api import _ravel, get_namespace_and_device, xpx |
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
Yes, I ran into the same issue when I was working on roc_auc_score.
average_precision_scoreaverage_precision_score
|
Commit 3a9b788 had caused The reason is that also in there we hadn't converted In 299fda1 I have added if sample_weight is not None:
sample_weight = column_or_1d(sample_weight)in |
adrinjalali
left a comment
There was a problem hiding this comment.
As far as I can tell, LGTM.
virchan
left a comment
There was a problem hiding this comment.
LGTM as well! Thanks, @StefanieSenger!
Just one minor nitpick.
Also, perhaps @lucyleeow or @ogrisel could take a look before merging.
lucyleeow
left a comment
There was a problem hiding this comment.
Nits and a question, otherwise looks good!
| if sample_weight is not None: | ||
| sample_weight = column_or_1d(sample_weight) |
There was a problem hiding this comment.
I probably missed something by why the changes to roc_auc_score ?
There was a problem hiding this comment.
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.
Co-authored-by: Lucy Liu <[email protected]>
|
Thanks for your patience and perseverance @StefanieSenger ! Let's get this in! |
|
Thanks to everybody who has reviewed. 💟 |
…#32909) Co-authored-by: Lucy Liu <[email protected]>
…#32909) Co-authored-by: Lucy Liu <[email protected]>
…#32909) Co-authored-by: Lucy Liu <[email protected]>
PR: scikit-learn#32909 Issue: scikit-learn#26024 Base commit: c9656a5 Changed lines: 96
PR: scikit-learn#32912 Issue: scikit-learn#32909 Base commit: 4ac1079 Changed lines: 41

Reference Issues/PRs
towards #26024
What does this implement/fix? Explain your changes.
Adds array API support to
average_precision_scoreAI usage disclosure
I used AI assistance for:
Any other comments?
WIP
TODO:
average_precision_scoreaverage_precision_scoreas well as from_check_set_wise_labelswhich allows to havepresent_labelsas an array instead of a listLabelBinarizerinstead oflabel_binarize# TODO: check if in fact necessary_average_binary_scoreaverage_precision_scoreinMETRICS_SUPPORTING_MIXED_NAMESPACEinsklearn/metrics/tests/test_common.py