You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
average_precision_score not working as expected #30147
When compute AP with average_precision_score, I get unexpected results. The y_scores (output from the models) are very low for positive samples, so my AP should be very low. Instead I get a perfect 1.0 AP score.
Precision is the ratio TP / (TP + FP). As all the true labels are positive, there will be no false positive (FP=0), and it seems reasonable that the precision is always 1.
If I plot the precision recall curve with this actual data I get:
The area under that curve (so the AP) is about 0.5
But if I plot the curve using the precision/recall used by average_precision_score I get:
Basically it adds an additional point with recall being one and precision as if all predictions were True.
Giving a tremendous AP of 0.97.
I don't think this is reasonable. For example, in object detection (where AP is the standard metric), a y_score of 0 means the object was not detected at all. It can never be a positive prediction so a "forced" recall of 1 does not make sense.
Hello! I'd like to work on this issue if it's available. Would it make sense to add a parameter to control the inclusion of the final recall=1 point in the AP calculation to better align with other standards?
On your other example, the last point that you have corresponds to the prevalence of the positive label estimated from the data.
This would be your chance level:
This would be the score of a DummyClassifier(strategy="constant", constant=1). It means that any predictor providing a score under this threshold do worse that a rule that does not learn any statistical association between the data and the target. So this is reasonable to me.
This would be the score of a DummyClassifier(strategy="constant", constant=1). It means that any predictor providing a score under this threshold do worse that a rule that does not learn any statistical association between the data and the target. So this is reasonable to me.
Not really because my application is Object Detection, where AP (or mAP) is the main metric used by most papers and benchmarks (e.g. COCO: https://cocodataset.org/#detection-eval).
In that case you can't predict all positives (or you would have an infinite number of false positives). That's what I meant by saying that when the model has 0 confidence in my example, it means it missed completely the detection, so it should never be counted as a positive no matter the threshold. Recall can't be above 0.55 in this case.
Not really because my application is Object Detection, where AP (or mAP) is the main metric used by most papers and benchmarks (e.g. COCO: https://cocodataset.org/#detection-eval). In that case you can't predict all positives (or you would have an infinite number of false positives). That's what I meant by saying that when the model has 0 confidence in my example, it means it missed completely the detection, so it should never be counted as a positive no matter the threshold. Recall can't be above 0.55 in this case.
AP and mAP are not interchangeable, they are different.
MS COCO calculates things like [email protected], [email protected] etc. These are completely different metrics compared to average_precision_score. And they define AP as AP and AR are averaged over multiple Intersection over Union (IoU) values. Specifically we use 10 IoU thresholds of .50:.05:.95.
MS COCO also use completely different interpolation method, while scikit-learn do not interpolate at all.
mAP is average across classes, but with only one class, mAP and AP should be equal.
[email protected] is Average Precision. @IOU0.5 simply means that IoU of 0.5 at least is needed to consider a prediction as matching an annotation. Once this matching is done, it should not change the way the AP is computed.
Interpolation is not what causes the major difference here.
The point was that in MS COCO AP is the average between 10 different IOUs, which is not average_precision_score;
Interpolation is a huge factor since it is basically the only difference between AUPRC, average_precision_score, MS COCO AP, PASCAL VOC AP and so on. Different interpolations yield very different results.
scikit-learn does not add point for recall==1, it actually only adds (0, 1) point (precision = 1 and recall = 0)
I draw it like in my code to compute AP. I tested different method with different interpolations. They all give about 0.5 AP on the example input from above, but the direct sklearn method that is giving 0.97 AP.
This is because in all methods the general idea is to compute the area under the PR curve. In my example, all methods stop at recall ~0.53, as my model never goes higher. But scikit-learn assumes a recall of 1 when the threshold is 0, this is not true in object detection.
defcompute_ap(precision, recall):
"""Compute AP given precision and recall values."""precision=np.concatenate(([0.0], precision, [0.0]))
recall=np.concatenate(([0.0], recall, [1.0]))
# Ensure precision is non-increasingforiinrange(len(precision) -1, 0, -1):
precision[i-1] =max(precision[i-1], precision[i])
# Find points where recall changesindices=np.where(recall[1:] !=recall[:-1])[0]
# Sum (recall_delta * precision)ap=np.sum((recall[indices+1] -recall[indices]) *precision[indices+1])
returnap# Compute AP using the COCO methoddefcompute_ap_coco(precision, recall):
"""Compute AP using the COCO method."""recall_thresholds=np.arange(0.0, 1.01, 0.01)
precisions=np.zeros_like(recall_thresholds)
fori, tinenumerate(recall_thresholds):
precisions[i] =np.max(precision[recall>=t]) if (recall>=t).any() else0.0returnnp.mean(precisions)
defcompute_ap_sum(precision, recall):
"""Compute AP using the sum method."""returnnp.sum((recall[1:] -recall[:-1]) *precision[1:])
# Compute AP scipy area under curvedefcompute_ap_scipy(precision, recall):
"""Compute AP using the scipy method."""returnauc(recall, precision)
defcompute_class_ap(preds, annots, iou_threshold, classes):
"""Compute AP per class and mAP. Args: preds: List (N_images, N_preds, 6) -> (class_idx, x1, y1, x2, y2, conf) annots: List (N_images, N_boxes, 5) -> (class_idx, x1, y1, x2, y2) iou_threshold: IOU threshold to match predictions and ground truths. Returns: class_ap: Dictionary of AP per class. mAP: Mean AP across all classes. """# Initialize lists to store true positives, false positives, and scores for each classall_true_positives=defaultdict(list)
all_false_positives=defaultdict(list)
all_scores=defaultdict(list)
n_gt_per_class=defaultdict(int)
y_true=defaultdict(list)
y_scores=defaultdict(list)
N_images=len(preds)
forimg_idxinrange(N_images):
pred_boxes=preds[img_idx]
annot_boxes=annots[img_idx]
forclass_idxinrange(len(classes)):
pred_class=pred_boxes[pred_boxes[:, 0] ==class_idx] iflen(pred_boxes) >0elsenp.array([])
annot_class=annot_boxes[annot_boxes[:, 0] ==class_idx] iflen(annot_boxes) >0elsenp.array([])
# Sort predictions by confidence scoreiflen(pred_class) >0:
pred_class=pred_class[np.argsort(-pred_class[:, 5])]
# Track matched ground truthsmatched_gt=np.zeros(len(annot_class), dtype=bool)
forpredinpred_class:
iflen(annot_class) >0:
ious=np.array([get_iou(pred[1:5], annot[1:5]) forannotinannot_class])
max_iou_idx=np.argmax(ious)
max_iou=ious[max_iou_idx]
ifmax_iou>=iou_thresholdandnotmatched_gt[max_iou_idx]:
# True positiveall_true_positives[class_idx].append(1)
all_false_positives[class_idx].append(0)
matched_gt[max_iou_idx] =Truey_true[class_idx].append(1)
else:
# False positiveall_true_positives[class_idx].append(0)
all_false_positives[class_idx].append(1)
y_true[class_idx].append(0)
else:
# False positive because there are no annotationsall_true_positives[class_idx].append(0)
all_false_positives[class_idx].append(1)
y_true[class_idx].append(0)
all_scores[class_idx].append(pred[5])
y_scores[class_idx].append(pred[5])
# Count number of ground truths for the classn_gt_per_class[class_idx] +=len(annot_class)
missed_gt=len(annot_class) -np.sum(matched_gt)
y_true[class_idx].extend([1] *missed_gt)
y_scores[class_idx].extend([0] *missed_gt)
# Compute AP per classclass_ap= {}
forclass_idxinall_scores:
# Sort by scoreindices=np.argsort(-np.array(all_scores[class_idx]))
true_positives=np.array(all_true_positives[class_idx])[indices]
false_positives=np.array(all_false_positives[class_idx])[indices]
# Compute cumulative sum of true positives and false positivescum_tp=np.cumsum(true_positives)
cum_fp=np.cumsum(false_positives)
# Compute precision and recallrecall=cum_tp/n_gt_per_class[class_idx]
precision=cum_tp/ (cum_tp+cum_fp)
#plot precision recall curveplt.figure(figsize=(10, 6))
plt.plot(recall, precision, marker='.')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('Precision-Recall Curve')
plt.show()
#compute precision and recall with sklearnfromsklearn.metricsimportprecision_recall_curveprecision, recall, thresholds=precision_recall_curve(y_true[class_idx], y_scores[class_idx])
plt.figure(figsize=(10, 6))
plt.plot(recall, precision, marker='.')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('Precision-Recall Curve')
plt.show()
# Compute AP#class_ap[class_idx] = compute_ap(precision, recall)#class_ap[class_idx] = compute_ap_voc(precision, recall)#class_ap[class_idx] = compute_ap_coco(precision, recall)#class_ap[class_idx] = compute_ap_scipy(precision, recall)#class_ap[class_idx] = compute_ap_sum(precision, recall)fromsklearn.metricsimportaverage_precision_scoreprint(f"Y_true: {y_true[class_idx]}")
print(f"Y_scores: {y_scores[class_idx]}")
class_ap[class_idx] =average_precision_score(y_true[class_idx], y_scores[class_idx])
# Compute mAPmAP=np.mean(list(class_ap.values())) ifclass_apelse0.0returnmAP, class_ap
I will get average_precision_score = 0.5055340559052119.
In terms of plots, we are basically will be doing this
instead of this
@glemaitre can someone please tell what is the meaning of adding the last value to the tps? The only thing I could find was commentary We also concatenate a value for the end of the curve. and that's it.
I ran several test cases, including OP's, and they all passed. Therefore, if we have some counterexamples along this direction, we will have a better chance of understanding the bug.
@glemaitre can someone please tell what is the meaning of adding the last value to the tps? The only thing I could find was commentary We also concatenate a value for the end of the curve. and that's it.
@glevv It corresponds to the prevalence. If you are in a medical setting, it would be the performance of a dummy classifier that always predict the positive outcome. Basically this is the chance level point. In this setting, you will never reach a precision of 0.0.
Consider OP's siutation: a binary classification problem with almost all samples labelled positive and low y_scores.
As @yuanx749 pointed out in the following comment:
Precision is the ratio TP / (TP + FP). As all the true labels are [all] positive, there will be no false positive (FP=0), and it seems reasonable that the precision is always 1.
the set of all $\left( \mathrm{Recall}, \mathrm{Precision} \right)$ pairs for this problem has the form $\left( \mathrm{Recall}, 1 \right)$. This means the precision-recall curve $P(\mathrm{Recall})$ is constant at 1 almost everywhere. (see the precision-recall displays provided by @glemaitre.) Hence, calculus tells us that:
$$\begin{array}{cl}
\mbox{Average Precision Score} &:=& \displaystyle\int_0^1 P(\mathrm{Recall}) \ d\left(\mathrm{Recall}\right) \\
&=& \displaystyle\int_0^1 1 \ d\left(\mathrm{Recall}\right) \\
&=& \mbox{length of the unit interval $[0,1]$} \\
&=& 1.
\end{array}$$
Thus, any valid numerical integration method should yield a result close to 1.
Regarding
But scikit-learn assumes a recall of 1 when the threshold is 0, this is not true in object detection.
This won't affect the calculation because a single point has zero area under curve.
Therefore, I agree with @yuanx749's recommendation to consider a different evaluation metric; or to adjust how the average precision score is interpreted in the context of object detection.
This won't affect the calculation because a single point has zero area under curve.
It does because because the line between the last actual observed recall and this assumed recall of 1.0 has an area (see @glevv plots above).
I think in the end it is really a question of context. In pure classification, the current implementation make sense, but in other context it might not.
TorchMetrics makes the difference by having an AP function specifically under its classification submodule and a mAP function under its detection submodule (with an option to get the result per class which is the AP).
TL;DR: I recommend closing this issue, as there is no need for code or documentation modifications.
I think in the end it is really a question of context. In pure classification, the current implementation make sense, but in other context it might not. TorchMetrics makes the difference by having an AP function specifically under its classification submodule and a mAP function under its detection submodule (with an option to get the result per class which is the AP).
Thank you again for sharing your perspective and use case. After comparing the scikit-learn implementation with PyTorch, and verifying the results mathematically, everything aligns as expected, including in the provided test cases. As you noted, the difference in interpretation seems derived from the context in which average precision is applied: classification vs. object detection.
Since the scikit-learn implementation aligns with standard classification metrics, this may simply reflect a difference in use case requirements rather than a need for code modification. As such, I'd recommend closing this issue.
If any additional considerations come to light, or if there's another angle we haven't covered, please don't hesitate to reopen the discussion. I'm happy to help explore any further questions or ideas you may have.
@pooja-singh702 probably you are doing it in good faith, but it feels like you are using ChatGPT or similar and pasting generic answer. I feel this is not particularly helpful in this case since the discussion has kind of reached a conclusion.
As such I am going to hide your previous two comments.
Please read our short section about our Automated contribution policy where we decided that we can block users if we feel they show repeated offenses of our guidelines. See also #29287 for more details about the context.
Activity
yuanx749 commentedon Oct 25, 2024
Precision is the ratio TP / (TP + FP). As all the true labels are positive, there will be no false positive (FP=0), and it seems reasonable that the precision is always 1.
Maybe try using other metrics to evaluate?
virgile-fsr commentedon Oct 25, 2024
AP (Average Precision) is a different metric than Precision.
It is the area under the Precision Recall curve: https://scikit-learn.org/1.5/modules/generated/sklearn.metrics.average_precision_score.html
Here is the issue with a less trivial example:
Y_true: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1]
Y_scores: [0.9997937083244324, 0.9848889112472534, 0, 0.9497167468070984, 0, 0, 0.9908866882324219, 0.9809730052947998, 0.9870287179946899, 0.9999470710754395, 0, 0, 0.9267389178276062, 0, 0.9746383428573608, 0.9993682503700256, 0.8148384094238281, 0, 0, 0, 0.6392842531204224, 0.9999898672103882, 1.0, 0, 0, 0, 0, 0.9375026822090149, 0.9581012725830078, 0.6106476783752441, 0.9974182844161987, 0, 0, 0, 1.0, 0.999996542930603, 0.8294159173965454, 0.7495031356811523, 0, 0, 0, 0.907082200050354]
If I plot the precision recall curve with this actual data I get:

The area under that curve (so the AP) is about 0.5
But if I plot the curve using the precision/recall used by average_precision_score I get:

Basically it adds an additional point with recall being one and precision as if all predictions were True.
Giving a tremendous AP of 0.97.
I don't think this is reasonable. For example, in object detection (where AP is the standard metric), a y_score of 0 means the object was not detected at all. It can never be a positive prediction so a "forced" recall of 1 does not make sense.
hugoboulenger commentedon Oct 27, 2024
Hello! I'd like to work on this issue if it's available. Would it make sense to add a parameter to control the inclusion of the final recall=1 point in the AP calculation to better align with other standards?
virgile-fsr commentedon Oct 28, 2024
I believe that would make a lot of sense yes!
glemaitre commentedon Oct 29, 2024
From you example, you will get the following PR curve:
So for this case, it looks like the average precision is correct.
glemaitre commentedon Oct 29, 2024
On your other example, the last point that you have corresponds to the prevalence of the positive label estimated from the data.
This would be your chance level:

This would be the score of a
DummyClassifier(strategy="constant", constant=1). It means that any predictor providing a score under this threshold do worse that a rule that does not learn any statistical association between the data and the target. So this is reasonable to me.glemaitre commentedon Oct 29, 2024
ping @ArturoAmorQ to have a second opinion here.
virgile-fsr commentedon Oct 29, 2024
Not really because my application is Object Detection, where AP (or mAP) is the main metric used by most papers and benchmarks (e.g. COCO: https://cocodataset.org/#detection-eval).
In that case you can't predict all positives (or you would have an infinite number of false positives). That's what I meant by saying that when the model has 0 confidence in my example, it means it missed completely the detection, so it should never be counted as a positive no matter the threshold. Recall can't be above 0.55 in this case.
glevv commentedon Oct 29, 2024
[email protected],[email protected]etc. These are completely different metrics compared toaverage_precision_score. And they define AP asAP and AR are averaged over multiple Intersection over Union (IoU) values. Specifically we use 10 IoU thresholds of .50:.05:.95.virgile-fsr commentedon Oct 29, 2024
mAP is average across classes, but with only one class, mAP and AP should be equal.
[email protected]is Average Precision. @IOU0.5 simply means that IoU of 0.5 at least is needed to consider a prediction as matching an annotation. Once this matching is done, it should not change the way the AP is computed.Interpolation is not what causes the major difference here.
Even if you look at the formula given in the scikit-learn documentation: https://scikit-learn.org/1.5/modules/generated/sklearn.metrics.average_precision_score.html
What the function is doing right now is adding an artificial value of R_n = 1.0 that doesn't exist in the data. All I am saying is that this is not clear in the function documentation and it's not the behavior that is always expected when computing AP. Always reaching 100% Recall is not guaranteed in all applications of ML but this is what is currently assumed by
average_precision_score.glevv commentedon Oct 29, 2024
average_precision_score;AUPRC,average_precision_score, MS COCO AP, PASCAL VOC AP and so on. Different interpolations yield very different results.scikit-learn does not add point for recall==1, it actually only adds (0, 1) point (precision = 1 and recall = 0)
scikit-learn/sklearn/metrics/_ranking.py
Line 1040 in 6e90391
If you remove this point you will get
average_precision_score=0.9110476661020139Can you please share the code that you used to draw the first graph, so that we can better understand the problem.
virgile-fsr commentedon Oct 30, 2024
I draw it like in my code to compute AP. I tested different method with different interpolations. They all give about 0.5 AP on the example input from above, but the direct sklearn method that is giving 0.97 AP.
This is because in all methods the general idea is to compute the area under the PR curve. In my example, all methods stop at recall ~0.53, as my model never goes higher. But scikit-learn assumes a recall of 1 when the threshold is 0, this is not true in object detection.
Another way to just have the plots would be:
glevv commentedon Oct 30, 2024
So if I replace this line
scikit-learn/sklearn/metrics/_ranking.py
Line 849 in 49c5948
with
threshold_idxs = distinct_value_indicesAnd this line
scikit-learn/sklearn/metrics/_ranking.py
Line 1033 in 49c5948
with
recall = tps / (y_true.size - 1)I will get
average_precision_score=0.5055340559052119.In terms of plots, we are basically will be doing this

instead of this

@glemaitre can someone please tell what is the meaning of adding the last value to the tps? The only thing I could find was commentary
We also concatenate a value for the end of the curve.and that's it.virchan commentedon Oct 30, 2024
We can compare
sklearn.metrics.average_precision_scorewith PyTorch's versiontorcheval.metrics.functional.binary_auprc.We can define a test function to compare numerical results between scikit-learn and PyTorch:
I ran several test cases, including OP's, and they all passed. Therefore, if we have some counterexamples along this direction, we will have a better chance of understanding the bug.
glemaitre commentedon Oct 30, 2024
@glevv It corresponds to the prevalence. If you are in a medical setting, it would be the performance of a dummy classifier that always predict the positive outcome. Basically this is the chance level point. In this setting, you will never reach a precision of 0.0.
glemaitre commentedon Oct 30, 2024
I have to put some thought if we should have a way to control this ending point depending on the application.
virchan commentedon Nov 1, 2024
TL;DR: I believe
sklearn.metrics.average_precision_scoreis working correctly.Consider OP's siutation: a binary classification problem with almost all samples labelled positive and low
y_scores.As @yuanx749 pointed out in the following comment:
the set of all$\left( \mathrm{Recall}, \mathrm{Precision} \right)$ pairs for this problem has the form $\left( \mathrm{Recall}, 1 \right)$ . This means the precision-recall curve $P(\mathrm{Recall})$ is constant at 1 almost everywhere. (see the precision-recall displays provided by @glemaitre.) Hence, calculus tells us that:
Thus, any valid numerical integration method should yield a result close to 1.
Regarding
This won't affect the calculation because a single point has zero area under curve.
Therefore, I agree with @yuanx749's recommendation to consider a different evaluation metric; or to adjust how the average precision score is interpreted in the context of object detection.
virgile-fsr commentedon Nov 1, 2024
It does because because the line between the last actual observed recall and this assumed recall of 1.0 has an area (see @glevv plots above).
I think in the end it is really a question of context. In pure classification, the current implementation make sense, but in other context it might not.
TorchMetrics makes the difference by having an AP function specifically under its classification submodule and a mAP function under its detection submodule (with an option to get the result per class which is the AP).
virchan commentedon Nov 7, 2024
TL;DR: I recommend closing this issue, as there is no need for code or documentation modifications.
Thank you again for sharing your perspective and use case. After comparing the scikit-learn implementation with PyTorch, and verifying the results mathematically, everything aligns as expected, including in the provided test cases. As you noted, the difference in interpretation seems derived from the context in which average precision is applied: classification vs. object detection.
Since the scikit-learn implementation aligns with standard classification metrics, this may simply reflect a difference in use case requirements rather than a need for code modification. As such, I'd recommend closing this issue.
If any additional considerations come to light, or if there's another angle we haven't covered, please don't hesitate to reopen the discussion. I'm happy to help explore any further questions or ideas you may have.
pooja-singh702 commentedon Nov 23, 2024
pooja-singh702 commentedon Nov 23, 2024
lesteve commentedon Nov 27, 2024
@pooja-singh702 probably you are doing it in good faith, but it feels like you are using ChatGPT or similar and pasting generic answer. I feel this is not particularly helpful in this case since the discussion has kind of reached a conclusion.
As such I am going to hide your previous two comments.
Please read our short section about our Automated contribution policy where we decided that we can block users if we feel they show repeated offenses of our guidelines. See also #29287 for more details about the context.
lesteve commentedon Nov 27, 2024
Skimming the discussion I kind of agree with @virchan in #30147 (comment) but if I miss something, feel free to reopen.