Skip to content

Wrong chance_level plot in PrecisionRecallDisplay when using Pytorch data #33342

Closed

Description

@lucolivi

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) # Correct

Expected Results

Correct chance classifier line at y 0.4 with y_true as a numpy array.

Image

Actual Results

Wrong chance classifier line at y 0.0 with y_true as a pytorch tensor.

Image

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: Haswell

Interest 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_predictions relies on Counter class to compare y_true entries with pos_label values in order to generate prevalence_pos_label (chance level).
    class_count = Counter(y_true)
    prevalence_pos_label = class_count[pos_label] / sum(class_count.values())
  • Counter is 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

  1. added
    Needs Triage
    on Feb 21, 2026
  2. NandiniDhanrale commented on Feb 22, 2026

    @NandiniDhanrale

    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.

  3. lucolivi commented on Feb 22, 2026

    @lucolivi
    ContributorAuthor

    Hi @NandiniDhanrale, I am already working on this. Just waiting the issue confirmation to submit a PR.

  4. devendrakushwah80 commented on Feb 23, 2026

    @devendrakushwah80

    Hi @lucolivi , are you still working on this? If not, I’d be happy to help with the fix and tests

  5. AnneBeyer commented on Feb 23, 2026

    @AnneBeyer
    Member

    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.

  6. AnneBeyer commented on Feb 23, 2026

    @AnneBeyer
    Member

    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?)

  7. lesteve commented on Feb 23, 2026

    @lesteve
    Member

    Slightly suprising PyTorch behaviour but fair enough.

    I guess this would make sense to use

    prevalence_pos_label = (y_true == pos_label).sum() / len(y_true)

    I can't think of a super-strong reason to use Counter here 1, but I would double-check git blame and the associated PRs to see if there was a good reason to use Counter.

    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_array on y_true at the top of this function so that y_true is converted into a numpy array early on.

    Footnotes

    1. using Counter avoids creating a temporary array but since y_true is 1d I don't think this is very important in practice. ↩

  8. lucolivi commented on Feb 23, 2026

    @lucolivi
    ContributorAuthor

    As per line R481, its the first implementation from 3 years ago. Most likely the author used Counter for convenience only.

    I think prevalence_pos_label = (y_true == pos_label).sum() / len(y_true) will break in case y_true and pos_label are neither complied with ArrayAPI, like native list and integers.

    Despite the problem simplicity, I like the check_array solution to keep things more high level.

    About testings, since .from_predictions returns the display object containing prevalence_pos_label property, 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?

  9. lesteve commented on Feb 24, 2026

    @lesteve
    Member

    Good point that y_true is array-like so it can be a list. In this case using something like y_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 current Counter code.

    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_predictions documents y_true as 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_array that does something like np.asarray at 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

    1. also other libraries like CuPy and others that conform to the Array API spec ↩

  10. lucyleeow commented on Feb 24, 2026

    @lucyleeow
    Member

    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.

  11. lucolivi commented on Feb 24, 2026

    @lucolivi
    ContributorAuthor

    For tests, should we use torch itself or just replicate the hash behavior with some existing data type like np.float32?

  12. lesteve commented on Feb 24, 2026

    @lesteve
    Member

    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.

    def test_something_with_pytorch():
        torch = pytest.importorskip("torch")
        # rest of the test code using PyTorch
  13. lucolivi commented on Feb 24, 2026

    @lucolivi
    ContributorAuthor

    Test fails for the current code

    Image

    and passes with the discussed solutions

    Image

    Correct plot this time

    Image
  14. removed
    Needs Triage
    on Feb 25, 2026
  15. lesteve commented on Feb 25, 2026

    @lesteve
    Member

    Looks good, please submit a PR with your changes!

  16. betatim commented on Mar 2, 2026

    @betatim
    Member

    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.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions