Skip to content

average_precision_score produces unexpected output when scoring a single sample #30615

Open
Shyanil/scikit-learn
#1

Description

@Innixma

Describe the bug

When using average_precision_score and scoring a single sample, the metric ignores y_score and will always produce a score of 1.0 if y_true = [1] and otherwise will return a score of 0. I would have expected that it would instead raise an exception.

Potentially related to #30147, however I'm focusing on the minimal example with just a single sample.

Steps/Code to Reproduce

from sklearn.metrics import average_precision_score

y_score = [0]
y_true = [1]
score = average_precision_score(y_true=y_true, y_score=y_score)
print(score)  # 1.0

y_score = [1]
y_true = [1]
score = average_precision_score(y_true=y_true, y_score=y_score)
print(score)  # 1.0

y_score = [0.5]
y_true = [1]
score = average_precision_score(y_true=y_true, y_score=y_score)
print(score)  # 1.0

y_score = [0]
y_true = [0]
score = average_precision_score(y_true=y_true, y_score=y_score)
print(score)  # 0.0

y_score = [1]
y_true = [0]
score = average_precision_score(y_true=y_true, y_score=y_score)
print(score)  # 0.0

y_score = [0.5]
y_true = [0]
score = average_precision_score(y_true=y_true, y_score=y_score)
print(score)  # 0.0

Additionally, you can see that the average_precision_score returns a score opposite of what precision and recall return:

from sklearn.metrics import average_precision_score, precision_score, recall_score

y_score = [0]
y_true = [1]

score = average_precision_score(y_true=y_true, y_score=y_score)
print(score)  # 1.0
score = precision_score(y_true=y_true, y_pred=y_score)
print(score)  # 0.0
score = recall_score(y_true=y_true, y_pred=y_score)
print(score)  # 0.0

Expected Results

I would have expected the metric to raise an exception, similar to what happens when ROC_AUC is called with a single sample:

score = roc_auc_score(y_true=y_true, y_score=y_score)
print(score)
ValueError: Only one class present in y_true. ROC AUC score is not defined in that case.

Actual Results

Refer to code snippets above.

Versions

System:
    python: 3.11.10 | packaged by conda-forge | (main, Sep 30 2024, 18:08:57) [GCC 13.3.0]
executable: /opt/conda/envs/ag-311/bin/python
   machine: Linux-5.15.0-1056-aws-x86_64-with-glibc2.31

Python dependencies:
      sklearn: 1.5.1
          pip: 24.2
   setuptools: 60.2.0
        numpy: 1.26.4
        scipy: 1.12.0
       Cython: None
       pandas: 2.2.3
   matplotlib: 3.9.2
       joblib: 1.4.2
threadpoolctl: 3.5.0

Built with OpenMP: True

threadpoolctl info:
       user_api: blas
   internal_api: openblas
    num_threads: 128
         prefix: libopenblas
       filepath: /opt/conda/envs/ag-311/lib/libopenblasp-r0.3.28.so
        version: 0.3.28
threading_layer: pthreads
   architecture: SapphireRapids

       user_api: blas
   internal_api: openblas
    num_threads: 64
         prefix: libopenblas
       filepath: /opt/conda/envs/ag-311/lib/python3.11/site-packages/scipy.libs/libopenblasp-r0-23e5df77.3.21.dev.so
        version: 0.3.21.dev
threading_layer: pthreads
   architecture: Cooperlake

       user_api: openmp
   internal_api: openmp
    num_threads: 192
         prefix: libgomp
       filepath: /opt/conda/envs/ag-311/lib/python3.11/site-packages/scikit_learn.libs/libgomp-a34b3233.so.1.0.0
        version: None

Activity

  1. added
    Needs Triage
    on Jan 9, 2025
  2. ogrisel commented on Jan 9, 2025

    @ogrisel
    Member

    Note that ValueError: Only one class present in y_true. ROC AUC score is not defined in that case. raised by ROC AUC is a more general case: there could be several data points but all with the same binary class labels.

    Currently, the following does not complain:

    >>> from sklearn.metrics import average_precision_score
    >>> average_precision_score([1, 1, 1], [0.1, 0.5, 0.9])
    np.float64(1.0)

    Note that the underlying precision_recall_fscore_support function would raise a warning on such degenerate cases where the predictions are thresholded:

    >>> from sklearn.metrics import precision_recall_fscore_support
    >>> precision_recall_fscore_support([1, 1, 1], [0, 1, 1])
    /Users/ogrisel/code/scikit-learn/sklearn/metrics/_classification.py:1566: UndefinedMetricWarning: Recall is ill-defined and being set to 0.0 in labels with no true samples. Use `zero_division` parameter to control this behavior.
      _warn_prf(average, modifier, f"{metric.capitalize()} is", result.shape[0])
    (array([0., 1.]), array([0.        , 0.66666667]), array([0. , 0.8]), array([0, 3]))
  3. added
    Needs Investigation
    and removed
    Needs Triage
    on Jan 9, 2025
  4. Innixma commented on Jan 9, 2025

    @Innixma
    Author

    If it turns out that 1 sample should be valid, it might be good for somewhere in the docstring to mention the behavior in this special case, since the current behavior is due to the additional synthetic sample appended to the input as detailed in #30147.

    The confusion on my end came from the concept of the average being an "area", but there is no area under the curve for a single sample, because there is no curve.

    For context, I'm trying to categorize most of scikit-learn's metrics by their behavior characteristics in AutoGluon so that I can programmatically check if a certain metric will raise an exception in a given situation (or become a degenerate score) and then implement safeguards (for example, dropping rare classes, stratified splits, warnings to the user, adding epsilons, etc.), as well as for optimization (is the mean of scores from two halves of the data the same as the score on the full data). I don't think there is anything like that in sklearn, but it would be a really awesome feature if it was added at some point.

  5. added 8 commits that reference this issue on Jan 12, 2025
    2f224d2
    f43553f
    e114d15
    e58a18f
    7b442ba
    0e8b7be
    0e4383a
    bfa3231
  6. Shyanil commented on Jan 13, 2025

    @Shyanil

    Hi, I apologize for creating multiple pull requests earlier. I’m still learning and getting familiar with the process. Please consider this current pull request as the main one, as it contains the correct changes. Feel free to ignore or close the previous ones if needed. Thank you for your understanding!

  7. Shyanil commented on Jan 13, 2025

    @Shyanil
  8. Innixma commented on Jan 15, 2025

    @Innixma
    Author

    Thanks @Shyanil, I added comments to the PR. This looks reasonable to me, assuming that the scikit-learn maintainers determine that this is indeed a bug instead of intended logic.

  9. Shyanil commented on Jan 15, 2025

    @Shyanil

    Thanks @Innixma for your review and feedback. I have updated the code based on the previous test case failures. Let me know if there’s anything else that needs improvement. Thank you!

  10. DresdenGman commented on Nov 20, 2026

    @DresdenGman

    Hi — I reproduced this on scikit-learn 1.9.1: with a single sample, average_precision_score returns 1.0 whenever y_true=[1] and 0.0 whenever y_true=[0], regardless of y_score (0, 0.5 and 1 all give the same result). The value comes entirely from the synthetic endpoints precision_recall_curve appends, since with one sample there are no real thresholds to integrate over.

    The four earlier PRs (#30627–#30631) were all closed because, as @jeremiedbb noted, no decision has been taken on this issue yet. Before anyone writes another fix, could a maintainer decide which behaviour is wanted: (a) raise a ValueError like roc_auc_score does when only one class is present in y_true, or (b) keep returning 1.0/0.0 and document the single-sample behaviour explicitly? Happy to implement whichever is chosen once the label is cleared.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugNeeds Investigation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions