Skip to content

FIX: Fix average_precision_score for single sample case - #30627

Closed
Shyanil wants to merge 4 commits into
scikit-learn:mainfrom
Shyanil:fix/average-precision-score-single-sample-30615
Closed

Shyanil wants to merge 4 commits into
scikit-learn:mainfrom
Shyanil:fix/average-precision-score-single-sample-30615

Conversation

@Shyanil

@Shyanil Shyanil commented Jan 12, 2025

Copy link
Copy Markdown

Fixes #30615

Fix for Issue #30615 - average_precision_score with single sample

Solution

I solved this by adding a validation check in the _binary_uninterpolated_average_precision function to ensure there are at least two samples before attempting to calculate the average precision score.

Implementation

def _binary_uninterpolated_average_precision(
    y_true, y_score, pos_label=1, sample_weight=None
):
    # Add validation for minimum samples
    if len(y_true) < 2:
        raise ValueError(
            "Average precision requires at least 2 samples to compute a meaningful "
            "score. A single sample cannot form a precision-recall curve. "
            f"Got array with shape ({len(y_true)},)"
        )
    
    precision, recall, _ = precision_recall_curve(
        y_true, y_score, pos_label=pos_label, sample_weight=sample_weight
    )
    # Return the step function integral
    return max(0.0, -np.sum(np.diff(recall) * np.array(precision)[:-1]))

Changes

  • Added input validation to check for minimum number of samples
  • Improved error message that explains why single sample computation is not possible
  • Follows scikit-learn's error messaging conventions

BEFORE (Original Code):

def _binary_uninterpolated_average_precision(
    y_true, y_score, pos_label=1, sample_weight=None
):
    precision, recall, _ = precision_recall_curve(
        y_true, y_score, pos_label=pos_label, sample_weight=sample_weight
    )
    # Return the step function integral
    return max(0.0, -np.sum(np.diff(recall) * np.array(precision)[:-1]))

AFTER (Fixed Code):

def _binary_uninterpolated_average_precision(
    y_true, y_score, pos_label=1, sample_weight=None
):
    # Add validation for minimum samples
    if len(y_true) < 2:
        raise ValueError(
            "Average precision requires at least 2 samples to compute a meaningful "
            "score. A single sample cannot form a precision-recall curve. "
            f"Got array with shape ({len(y_true)},)"
        )
    
    precision, recall, _ = precision_recall_curve(
        y_true, y_score, pos_label=pos_label, sample_weight=sample_weight
    )
    # Return the step function integral
    return max(0.0, -np.sum(np.diff(recall) * np.array(precision)[:-1]))

The average_precision_score function was returning misleading results
(1.0 or 0.0) when given a single sample. Added validation to require
at least 2 samples and provide a clear error message.

Fixes scikit-learn#30615
@github-actions

github-actions Bot commented Jan 12, 2025 •

Copy link
Copy Markdown

❌ Linting issues

This PR is introducing linting issues. Here's a summary of the issues. Note that you can avoid having linting issues by enabling pre-commit hooks. Instructions to enable them can be found here.

You can see the details of the linting issues under the lint job here


black

black detected issues. Please run black . locally and push the changes. Here you can see the detected issues. Note that running black might also fix some of the issues which might be detected by ruff. Note that the installed black version is black=24.3.0.

Details

--- /home/runner/work/scikit-learn/scikit-learn/sklearn/metrics/_ranking.py	2025-01-12 18:46:41.654853+00:00
+++ /home/runner/work/scikit-learn/scikit-learn/sklearn/metrics/_ranking.py	2025-01-12 18:46:59.292202+00:00
@@ -218,11 +218,10 @@
     np.float64(0.77...)
     """
 
     def _binary_uninterpolated_average_precision(
         y_true, y_score, pos_label=1, sample_weight=None
-
     ):
         if len(y_true) < 2:
             raise ValueError(
                 f"Average precision requires at least 2 samples. Got {len(y_true)}."
                 " A single sample cannot form a precision-recall curve."
would reformat /home/runner/work/scikit-learn/scikit-learn/sklearn/metrics/_ranking.py

Oh no! 💥 💔 💥
1 file would be reformatted, 920 files would be left unchanged.

Generated for commit: e58a18f. Link to the linter CI: here

@Shyanil Shyanil closed this Jan 12, 2025
The average_precision_score function was returning misleading results
(1.0 or 0.0) when given a single sample. Added validation to require
at least 2 samples and provide a clear error message.

Fixes scikit-learn#30615
The average_precision_score function was returning misleading results
(1.0 or 0.0) when given a single sample. Added validation to require
at least 2 samples and provide a clear error message.

Fixes scikit-learn#30615
The average_precision_score function was returning misleading results
(1.0 or 0.0) when given a single sample. Added validation to require
at least 2 samples and provide a clear error message.

Fixes scikit-learn#30615
@Shyanil Shyanil reopened this Jan 12, 2025
@Shyanil Shyanil closed this Jan 12, 2025
@Shyanil
Shyanil deleted the fix/average-precision-score-single-sample-30615 branch January 12, 2025 18:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

average_precision_score produces unexpected output when scoring a single sample

1 participant