Repository navigation
Closed
Closed
Copy link
Description
Describe the bug and give evidence about its user-facing impact
The chance_level line drawn by PrecisionRecallDisplay.from_predictions when plot_chance_level=True is not correct when y_true is an instance of pytorch.Tensor.
Steps/Code to Reproduce
# pytorch==2.8.0
from sklearn.metrics import PrecisionRecallDisplay
import torch
torch.manual_seed(42)
y_true = torch.cat([torch.ones(40), torch.zeros(60)]) # Chance level equal 0.4
y_score = torch.rand_like(y_true)
PrecisionRecallDisplay.from_predictions(y_true, y_score, plot_chance_level=True) # Wrong
PrecisionRecallDisplay.from_predictions(y_true.numpy(), y_score, plot_chance_level=True) # CorrectExpected Results
Correct chance classifier line at y 0.4 with y_true as a numpy array.
Actual Results
Wrong chance classifier line at y 0.0 with y_true as a pytorch tensor.
Versions
System:
python: 3.13.5 | packaged by Anaconda, Inc. | (main, Jun 12 2025, 16:37:03) [MSC v.1929 64 bit (AMD64)]
executable: C:\Users\lucas\miniconda\envs\pytorch28\python.exe
machine: Windows-11-10.0.26200-SP0
Python dependencies:
sklearn: 1.7.1
pip: 25.1
setuptools: 78.1.1
numpy: 2.1.2
scipy: 1.16.1
Cython: None
pandas: 2.3.3
matplotlib: 3.10.5
joblib: 1.5.1
threadpoolctl: 3.6.0
Built with OpenMP: True
threadpoolctl info:
user_api: openmp
internal_api: openmp
num_threads: 6
prefix: libiomp
filepath: C:\Users\lucas\miniconda\envs\pytorch28\Lib\site-packages\torch\lib\libiomp5md.dll
version: None
user_api: openmp
internal_api: openmp
num_threads: 1
prefix: libiomp
filepath: C:\Users\lucas\miniconda\envs\pytorch28\Lib\site-packages\torch\lib\libiompstubs5md.dll
version: None
user_api: blas
internal_api: openblas
num_threads: 12
prefix: libscipy_openblas
filepath: C:\Users\lucas\miniconda\envs\pytorch28\Lib\site-packages\numpy.libs\libscipy_openblas64_-c16e4918366c6bc1f1cd71e28ca36fc0.dll
version: 0.3.27
threading_layer: pthreads
architecture: Haswell
user_api: openmp
internal_api: openmp
num_threads: 12
prefix: vcomp
filepath: C:\Users\lucas\miniconda\envs\pytorch28\Lib\site-packages\sklearn\.libs\vcomp140.dll
version: None
user_api: blas
internal_api: openblas
num_threads: 12
prefix: libscipy_openblas
filepath: C:\Users\lucas\miniconda\envs\pytorch28\Lib\site-packages\scipy.libs\libscipy_openblas-6b2103f2ae4d8547998b5d188e9801fb.dll
version: 0.3.28
threading_layer: pthreads
architecture: HaswellInterest in fixing the bug
Working on this, the root cause is due to these reasons:
- pytorch (and potentially other array libraries) defines scalars in such a way that their hash is different from their value and same values may have different hashes;
PrecisionRecallDisplay.from_predictionsrelies onCounterclass to comparey_trueentries withpos_labelvalues in order to generateprevalence_pos_label(chance level).scikit-learn/sklearn/metrics/_plot/precision_recall_curve.py
Lines 563 to 565 in 646da0f
class_count = Counter(y_true) prevalence_pos_label = class_count[pos_label] / sum(class_count.values()) Counteris not able to group objects with same values since they have different hash values.
Comparing the values from y_true directly to pos_label to calculate prevalence_pos_label should be enough to fix this.
Activity
NandiniDhanrale commentedon Feb 22, 2026
Hi, I’d like to work on this issue. I’ll update the prevalence_pos_label computation to support PyTorch tensors and add a test for this case.
lucolivi commentedon Feb 22, 2026
Hi @NandiniDhanrale, I am already working on this. Just waiting the issue confirmation to submit a PR.
devendrakushwah80 commentedon Feb 23, 2026
Hi @lucolivi , are you still working on this? If not, I’d be happy to help with the fix and tests
AnneBeyer commentedon Feb 23, 2026
Hi @devendrakushwah80 (and @NandiniDhanrale). Thank you for your interest in contributing to scikit-learn, but please check our guidelines for contributing and in particular the section New contributors, as you are commenting on an issue that still has the label "Needs Triage". As @lucolivi correctly noted, this issue still needs to be confirmed, and he also already said that he will work on it, once it is, so please stop spamming the discussion here.
AnneBeyer commentedon Feb 23, 2026
I can reproduce the issue with the given code example (also with the newest dev version of scikit-learn).
@ogrisel: This looks related to the ArrayAPI, could you check if the suggested approach sounds reasonable (or if there already exist helpers for such cases?)
lesteve commentedon Feb 23, 2026
Slightly suprising PyTorch behaviour but fair enough.
I guess this would make sense to use
I can't think of a super-strong reason to use
Counterhere 1, but I would double-checkgit blameand the associated PRs to see if there was a good reason to useCounter.Adding a test for this would be nice but I am not sure how doable this is.
An alternative would be to make sure we call
check_arrayony_trueat the top of this function so thaty_trueis converted into a numpy array early on.Footnotes
using
Counteravoids creating a temporary array but sincey_trueis 1d I don't think this is very important in practice. ↩lucolivi commentedon Feb 23, 2026
As per line R481, its the first implementation from 3 years ago. Most likely the author used
Counterfor convenience only.I think
prevalence_pos_label = (y_true == pos_label).sum() / len(y_true)will break in casey_trueandpos_labelare neither complied with ArrayAPI, like native list and integers.Despite the problem simplicity, I like the
check_arraysolution to keep things more high level.About testings, since
.from_predictionsreturns the display object containingprevalence_pos_labelproperty, we could check if its value is correct.In a broader scenario, should this pytorch behavior be a big concern? Perhaps adding some monkey-patched warnings in the test suite in case array libraries are used to index dict like objects?
lesteve commentedon Feb 24, 2026
Good point that
y_trueis array-like so it can be a list. In this case using something likey_true = check_array(y_true, ensure_2d=False)at the top of the function seems to make sense.I would also use something like
prevalence_pos_label = (y_true == pos_label).sum() / len(y_true)for simplicity rather than the currentCountercode.Inspecting the label for the AP value seems OK (even if a bit brittle) as a test if you can make it work.
The topic here is that a PyTorch CPU tensor is array-like and that
.from_predictionsdocumentsy_trueas array-like. In other words, providing a PyTorch CPU tensor is supposed to work for array-like inputs because the PyTorch CPU tensor will be converted to a numpy array by scikit-learn code (check_arraythat does something likenp.asarrayat one point).Array API support is something slightly different, it's the ability (ongoing experimental effort, see doc) to keep the PyTorch 1 tensor (CPU or GPU) and do the computation with PyTorch throughout the scikit-learn code.
Footnotes
also other libraries like CuPy and others that conform to the Array API spec ↩
lucyleeow commentedon Feb 24, 2026
I added the array API label just because if we add a torch test, it may be array API adjacent, as requires env that has torch - but please remove if you wish.
lucolivi commentedon Feb 24, 2026
For tests, should we use torch itself or just replicate the hash behavior with some existing data type like
np.float32?lesteve commentedon Feb 24, 2026
I feel the simplest here is to test the real issue that you discovered, rather than to come up with a alternative test that doesn't use PyTorch.
You can use
pytest.importorskip('torch')in your test so that the test gets run if PyTorch is installed and skipped otherwise.lucolivi commentedon Feb 24, 2026
Test fails for the current code
and passes with the discussed solutions
Correct plot this time
lesteve commentedon Feb 25, 2026
Looks good, please submit a PR with your changes!
betatim commentedon Mar 2, 2026
Stopping by to raise awareness of the last few comments in #32676 (comment) - my tl;dr from that is that the answer to "Is a PyTorch CPU tensor array-like?" is not as simple as you might think. The question is mostly around "do we want to officially state that we support this?" - while it might look like a simple question, there is potential for quite a bit of extra maintenance work if we officially support it.
I think for this issue and PR contributors can continue on as they were. However, we maintainers need to scratch our heads a bit and discuss this topic.