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
precision_recall_curve - assumed limits can be misleading #4223
I understand that recall goes to zero in the limit, but precision might not be so clear-cut. A really difficult problem where your top prediction is a false positive would have precision go to zero in the limit I believe. For plotting with this function, this case is probably not a big deal a vertical line from 0 to 1 would be hidden by the y-axis.
But for the drawn top-preds, as seen above, the plot becomes misleading and makes the viewer think that at least their top prediction was true positive. This may seem like a corner case, but I ran into it on a tough classification problem I was working on and was a little baffled by the output until I checked the code out.
A quick fix to preserve the intention of a clean P-R plot might be to draw a horizontal line from the highest threshold to the y-axis, this should not alter the output of most cases like here. Trying to actually calculate where it's going in the limit might be a bit overkill :-)
I would also think that adding a 1 to the end of the thresholds vector would be helpful when plotting both precision and recall against the probabilities.
I'm happy to open a PR if anyone thinks this is worth addressing.
Can you find literature that formally discusses the case of threshold higher than top score (which need not be bounded by 1, as it's not necessarily a probability in this function)?
Can you find literature that formally discusses the case of threshold higher than top score
Shall do a bit of a search over the coming days.
(which need not be bounded by 1, as it's not necessarily a probability in this function)?
And yes, forgot about predict_log_proba etc. Perhaps if this goes anywhere a function arg like threshold= {None, 'proba', 'log_proba'...} would be helpful to some people though to automagically add some limiting threshold at the end for ease of plotting?
decision_function is more the issue than predict_log_proba; it allows this
metric to be used with uncalibrated SVC, for instance.
There is averaging in the red plot in the IR book, but what's happening in
the left of the blue plot is less clear.
Thanks for looking into it.
On 10 February 2015 at 14:38, Trevor Stephens [email protected]
wrote:
Can you find literature that formally discusses the case of threshold
higher than top score
Shall do a bit of a search over the coming days.
(which need not be bounded by 1, as it's not necessarily a probability in
this function)?
And yes, forgot about predict_log_proba etc. Perhaps if this goes anywhere
a function arg like threshold= {None, 'proba', 'log_proba'...} would be
helpful to some people though to automagically add some limiting threshold
at the end for ease of plotting?
@jnothman , I've found a couple of references that are somewhat relevant, interested in your thoughts so far:
The Relationship between Recall and Precision @ 297 cites does not specifically address the question, but has several examples of P-R plots hitting the y-axis at values other than one. (This link may require manual saving as a pdf out of the browser)
The ROCR package in R does not appear to extrapolate beyond the thesholds relevant to the predictions.
This CrossValidated thread is the closest thing I have stumbled across, where quite a few different takes are presented.
Is it correct that, as true positives and false positives approach 0, the precision approaches 1? Same question for recall
Most interesting to me is Rob Hyndman's (somewhat brief) take:
If false positives and false negatives both approach zero at a faster rate than true positives, then yes to both questions. But otherwise, not necessarily.
He's a well respected statistician in the energy forecasting space, but no paper to refer to :-/
I've just recalled this. You seem chuffed to find Hyndman's opinion in agreement with you.
I'm still most curious to see what definitions of average precision say: for users of precision_recall_curve for visualisation it's fine to provide an option. For average_precision we need to have a more practically consistent answer.
You seem chuffed to find Hyndman's opinion in agreement with you.
It was more the fact I knew his name that caught my eye. He's very active in the area in which I work.
I'm still most curious to see what definitions of average precision say: for users of precision_recall_curve for visualisation it's fine to provide an option. For average_precision we need to have a more practically consistent answer.
As in a function parameter like y-intercept=True/False or something? I shall try to look into average precision too. Hopefully there's some more discussion on the corner cases there.
where is the change in the recall from i − 1 to i. ... It's not immediately clear from the example where the i's begin and end, ie. is there an item 11? But if we take the (oh dear, I hope I never meet you, evil classifier) example:
Which really doesn't jive with even simple intuition about the above (albeit quite crazy) example.
So I'd say @jnothman that your suspicion that average_precision_score is affected by this function as well is correct. Though, I'm yet to find any conclusive literature on the subject after a fair bit of search. :-/
Also reported in #5073. Let's get some resolution here. Ideally we'd like some confirmation from other implementations.
With or without confirmation, we could provide an option precision_at_0 (to precision_recall_curve and average_precision; maybe it should be precision_at_infinity, depending on whether we're talking recalls or thresholds). The current behaviour would be replicated by precision_at_0=1.0, but we could support precision_at_0=None meaning no point would intercept the axis unless there is a threshold for which recall=0, and precision_at_0='nextbest' or something that would just draw a horizontal line to the axis from the next point. Nomenclature suggestions welcome, as are alternative approaches.
We could change the default when we had a consensus of prior work.
FWIW, Weka introduces a "fake" point at (0, 0) in ThresholdCurve.getCurve, (although the fact that precision is 0 in this context may only be an artefact of code reuse). However in getPRCArea (comparable to average_precision), it comments "start from the first real p/r pair (not the artificial zero point)". The same data is used for their ROC calculation, although there the "artificial zero point" is treated differently rather than ignored.
I came to the same problem while working on a difficult classification problem and I would like to highlight that this situation is more problematic than a simple corner case. In fact when using CV or other methods to optimize classifier metaparameters for average_precision, it may be often the case that some parameter combinations produces (bad) classifiers with sharp decision boundaries; these will be however favoured in the current way that metric is computed. My current solution is to reset the value for precision at zero recall = 0 and seems to work well in combination with CV. I tend to favour @jnothman proposal of providing an additional parameter for the precision_at_0 for a more general solution.
With respect to precision_recall_curve() - since we are dealing with empirical data (not a theoretical distribution), there are 3 possibilities as to what the most extreme point of the curve should be (i.e. the point where recall is closest to 0)
The unique point with the highest score is "in-class". Then recall = 1/(number of in-class cases) and precision = 1 for that threshold.
The unique point with the highest score is "out-of-class". Then recall = 0 and precision = 0 for that threshold.
There are multiple points tied for the highest value. Then recall = (# in-class with that value)/(# total in-class cases) and precision = (# in-class with that value)/(total cases with that value)
In my opinion, it never makes sense to say precision = 1 and recall = 0. If you did not identify a single in-class (no in-class cases cleared the threshold) then how could you possibly claim to have any precision? I think it is a mistake to say that "precision at recall = 0" is always defined. It is either 0 (if the highest ranked case is out-of-class) or recall never reaches 0 (because one or more cases have the highest score in the set). It is not necessary to have a point for a threshold where no cases (in or out-of-class) are identified as positive. On the other hand, it does make sense to have a point where all points are identified as positive, since that gives a baseline performance.
Reacted by Tomas Petricek, aMKa, Dejia Xu and Gota Gando
@amueller I just saw this thread. Yes, this will be fixed in #7356 since the last (left-most) precision value isn't used: the first term in the sum is the p_1 (r_1 - r_0) where r_0 = 0 and I'm indexing from the smallest recall values.
The problem here is not so much with the first interpolating point (although I agree that it's confusing), but with using linear interpolation between operating points. There is no threshold that results in (recall=0.8, precision ~0.4) in the example above, and so linearly interpolating isn't valid. Consider the even more extreme case of a do-nothing predictor:
Your choices are to pick a threshold below 0.5 (recall=0, precision=undefined), or above 0.5 (recall=1, precision=0.5). The straight line between them is misleading because it suggests points along that line are possible operating points (perhaps in the limit of infinite data).
The correct interpretation is to plot a step-function:
plt.step(recall, precision, where='post');
This gives the correct intuition: if you want a recall of e.g. 0.2, you must choose a threshold above 0.5, which means precision = 0.5. For any recall > 0, the precision is 0.5; for recall = 0, precision is undefined (or whatever you decide the precision of an empty set is - it's totally arbitrary and doesn't affect your classifier because who wants recall=0?)
Since this is a common error, perhaps we could add an instruction in the precision_recall_curve docstring instructing people to plot it using plt.step(recall, precision, where='post') and then close this issue. @amueller what do you think?
The problem is not only plotting @ndingwall . Also, AUC value depends on precision-recall values.
Predictions and targets can be ranked then rank can be used as a score so it will break the tie. However, the order of the target important so should be sorted as well.
importfunctoolsfromsklearn.metricsimportprecision_recall_curvefromsklearn.metricsimportaucdeftie_breaker(func):
@functools.wraps(func)deftie_less_metric(y_true, probas_pred, pos_label=None,
sample_weight=None, **kwargs):
ifpos_label:
y_true= [i==pos_labelforiiny_true]
# Sort prediction and true pos_labely_true, probas_pred=zip(*sorted(
zip(y_true, probas_pred),
key=lambdax: (x[1], -x[0]), reverse=True))
# Convert probs into rank to break the tiesranks= [
(len(probas_pred) -i, prob)
fori, probinenumerate(probas_pred)
]
rank= [i[0] foriinranks]
precision, recall, thresholds=func(y_true, rank,
pos_label, sample_weight, **kwargs)
# Convert threshold into original scoresranks=dict(ranks)
thresholds= [ranks[i] foriinthresholds]
returnprecision, recall, thresholdsreturntie_less_metric
@ndingwall If you say the step function with where="post" gives the correct curve, shouldn't the AUC then be calculated from the step function as well?
EDIT:
As a demonstration, auc reports 0.2% higher for the step function:
defprc_step(precision, recall, sklearn_mode=True):
ifnotsklearn_mode:
# make sure that input is sorted by recallidx=np.argsort(recall)
else:
# by default, sklearn reports recall sorted descending# => just inverting in this case is fasteridx=slice(None, None, -1)
idxprec_step=np.zeros((len(precision) *2) -1)
rec_step=np.zeros((len(recall) *2) -1)
prec_step[np.arange(len(precision)) *2] =precision[idx]
rec_step[np.arange(len(recall)) *2] =recall[idx]
# resemble 'post' step plotprec_step[np.arange(len(recall) -1) *2+1] =precision[idx][1:]
rec_step[np.arange(len(recall) -1) *2+1] =recall[idx][:-1]
returnprec_step, rec_step
EDIT2:
This is actually very close to average precision score:
shouldn't the AUC then be calculated from the step function as well?
Yes, this is exactly what average_precision_score does since 0.19 (as you noticed). I wrote a whole blog post on this a few years ago if you're interested.
Is there still any issue with the current state? the plot_precision_recall_curve function actually does the step interpolation, which is the correct thing to do as @ndingwall states. average_precision now uses the formula from wikipedia so the point doesn't influence it any more.
For AUC, linear interpolation is valid and both the plotting and roc_auc use the linear interpolation.
[This whole thing has been a pet-peeve of mine for years, thanks for the blog post @ndingwall, though I guess it's out of date now since I think we fixed all of the issues?].
@amueller, yes, the blog-post should be updated, although I doubt it gets much traffic!
Is there still any issue with the current state?
I think precision/recall is a deceptively confusing topic, and there are a few things that compound common misconceptions:
the name precision_recall_curve isn't ideal, but I can't think of a better alternative and changing it would no doubt break a lot of code.
the auc documentation suggests that you "see also" precision_recall_curve, even though the existing auc function can't be used to compute anything meaningful with respect to precision-recall. It also says "For an alternative way to summarize a precision-recall curve, see average_precision_score" which suggests that auc itself is a valid way to summarize a precision-recall curve.
I can work on a PR that either (A) minimally corrects the documentation for auc (explaining that it cannot be used with precision_recall_score and pointing to average_precision_score as an alternative, or (B) add an interpolation argument to auc that can be either "linear" (default) or "step", document that precision_recall_curve uses the latter, and have average_precision_score use auc with the "step" argument.
I think (B) risks getting unwieldy since we'd probably end up wanting to offer "from-left" and "from-right" as options for "step" (for completeness), and before you know it the API is a confusing mess... On the other hand, it would emphasize that linear is just one of several ways to compute the area under a curve described by its coordinates.
That leaves the Precision Recall multiclass documentation. Since the precision_recall_curve docstring says "Note: this implementation is restricted to the binary classification task" and the multiclass example uses the trick of doing 1-vs-rest binary classification for each label, I'd advocate for dropping the multiclass section entirely. We could link to the OneVsRestClassifier if you really want multiclass covered.
Seems the original issue is actually solved / improved a lot since this issue was opened. Happy to have a fresh issue with concrete points on what can be improved in the docs or the API.
Activity
jnothman commentedon Feb 9, 2015
Can you find literature that formally discusses the case of threshold higher than top score (which need not be bounded by 1, as it's not necessarily a probability in this function)?
As I understand it, PR curves traditionally descend from P=1, R=0, although perhaps in http://nlp.stanford.edu/IR-book/html/htmledition/evaluation-of-ranked-retrieval-results-1.html the PR-curve does not actually meet the Y axis (but I'm not sure I'm reading it correctly)...?
More important, perhaps, is to check that average precision, as the area under this curve, agrees with definitions elsewhere.
trevorstephens commentedon Feb 10, 2015
Shall do a bit of a search over the coming days.
And yes, forgot about predict_log_proba etc. Perhaps if this goes anywhere a function arg like
threshold= {None, 'proba', 'log_proba'...}would be helpful to some people though to automagically add some limiting threshold at the end for ease of plotting?I'll check it out, looks like some averaging going on at a quick glance.
This is more involved than I thought :-) Will check it out.
jnothman commentedon Feb 10, 2015
decision_function is more the issue than predict_log_proba; it allows this
metric to be used with uncalibrated SVC, for instance.
There is averaging in the red plot in the IR book, but what's happening in
the left of the blue plot is less clear.
Thanks for looking into it.
On 10 February 2015 at 14:38, Trevor Stephens [email protected]
wrote:
trevorstephens commentedon Feb 11, 2015
@jnothman , I've found a couple of references that are somewhat relevant, interested in your thoughts so far:
The Relationship between Recall and Precision @ 297 cites does not specifically address the question, but has several examples of P-R plots hitting the y-axis at values other than one. (This link may require manual saving as a pdf out of the browser)
The
ROCRpackage in R does not appear to extrapolate beyond the thesholds relevant to the predictions.This CrossValidated thread is the closest thing I have stumbled across, where quite a few different takes are presented.
Most interesting to me is Rob Hyndman's (somewhat brief) take:
He's a well respected statistician in the energy forecasting space, but no paper to refer to :-/
jnothman commentedon Mar 19, 2015
I've just recalled this. You seem chuffed to find Hyndman's opinion in agreement with you.
I'm still most curious to see what definitions of average precision say: for users of
precision_recall_curvefor visualisation it's fine to provide an option. Foraverage_precisionwe need to have a more practically consistent answer.trevorstephens commentedon Mar 19, 2015
I see what you did there... :-)
It was more the fact I knew his name that caught my eye. He's very active in the area in which I work.
As in a function parameter like
y-intercept=True/Falseor something? I shall try to look into average precision too. Hopefully there's some more discussion on the corner cases there.trevorstephens commentedon Apr 4, 2015
Sorry for the delay, but I suppose it's not really a pressing issue as this is certainly a corner-case. Anyhow, I was unable to locate any specifics on unusual classifiers in the literature beyond what I've already posted, however http://ibrarian.net/navon/paper/Recall__Precision_and_Average_Precision_Mu_Zhu.pdf?paperid=8275510 defines AP as:
where
is the change in the recall from i − 1 to i. ... It's not immediately clear from the example where the i's begin and end, ie. is there an item 11? But if we take the (oh dear, I hope I never meet you, evil classifier) example:
Then I assume you would build this version of table 1 as:
Which would be:
In the
metricsthough:Which really doesn't jive with even simple intuition about the above (albeit quite crazy) example.
So I'd say @jnothman that your suspicion that
average_precision_scoreis affected by this function as well is correct. Though, I'm yet to find any conclusive literature on the subject after a fair bit of search. :-/jnothman commentedon Aug 17, 2015
Also reported in #5073. Let's get some resolution here. Ideally we'd like some confirmation from other implementations.
With or without confirmation, we could provide an option
precision_at_0(toprecision_recall_curveandaverage_precision; maybe it should beprecision_at_infinity, depending on whether we're talking recalls or thresholds). The current behaviour would be replicated byprecision_at_0=1.0, but we could supportprecision_at_0=Nonemeaning no point would intercept the axis unless there is a threshold for which recall=0, andprecision_at_0='nextbest'or something that would just draw a horizontal line to the axis from the next point. Nomenclature suggestions welcome, as are alternative approaches.We could change the default when we had a consensus of prior work.
jnothman commentedon Aug 17, 2015
FWIW, Weka introduces a "fake" point at (0, 0) in
ThresholdCurve.getCurve, (although the fact that precision is 0 in this context may only be an artefact of code reuse). However ingetPRCArea(comparable toaverage_precision), it comments "start from the first real p/r pair (not the artificial zero point)". The same data is used for their ROC calculation, although there the "artificial zero point" is treated differently rather than ignored.lfiaschi commentedon Feb 10, 2016
I came to the same problem while working on a difficult classification problem and I would like to highlight that this situation is more problematic than a simple corner case. In fact when using CV or other methods to optimize classifier metaparameters for
average_precision, it may be often the case that some parameter combinations produces (bad) classifiers with sharp decision boundaries; these will be however favoured in the current way that metric is computed. My current solution is to reset the value for precision at zero recall = 0 and seems to work well in combination with CV. I tend to favour @jnothman proposal of providing an additional parameter for theprecision_at_0for a more general solution.blucena commentedon Apr 28, 2016
With respect to precision_recall_curve() - since we are dealing with empirical data (not a theoretical distribution), there are 3 possibilities as to what the most extreme point of the curve should be (i.e. the point where recall is closest to 0)
In my opinion, it never makes sense to say precision = 1 and recall = 0. If you did not identify a single in-class (no in-class cases cleared the threshold) then how could you possibly claim to have any precision? I think it is a mistake to say that "precision at recall = 0" is always defined. It is either 0 (if the highest ranked case is out-of-class) or recall never reaches 0 (because one or more cases have the highest score in the set). It is not necessary to have a point for a threshold where no cases (in or out-of-class) are identified as positive. On the other hand, it does make sense to have a point where all points are identified as positive, since that gives a baseline performance.
amueller commentedon Oct 7, 2016
Is this fixed by #7356? Hm I guess not...
ndingwall commentedon Jun 7, 2017
@amueller I just saw this thread. Yes, this will be fixed in #7356 since the last (left-most) precision value isn't used: the first term in the sum is the
p_1 (r_1 - r_0)wherer_0 = 0and I'm indexing from the smallest recall values.7 remaining items
ndingwall commentedon Nov 11, 2020
The problem here is not so much with the first interpolating point (although I agree that it's confusing), but with using linear interpolation between operating points. There is no threshold that results in (recall=0.8, precision ~0.4) in the example above, and so linearly interpolating isn't valid. Consider the even more extreme case of a do-nothing predictor:
Your choices are to pick a threshold below 0.5 (recall=0, precision=undefined), or above 0.5 (recall=1, precision=0.5). The straight line between them is misleading because it suggests points along that line are possible operating points (perhaps in the limit of infinite data).
The correct interpretation is to plot a step-function:
This gives the correct intuition: if you want a recall of e.g. 0.2, you must choose a threshold above 0.5, which means precision = 0.5. For any recall > 0, the precision is 0.5; for recall = 0, precision is undefined (or whatever you decide the precision of an empty set is - it's totally arbitrary and doesn't affect your classifier because who wants recall=0?)
I wrote a whole blog post about this a few years ago if you need to be convinced any more!
ndingwall commentedon Nov 11, 2020
Since this is a common error, perhaps we could add an instruction in the
precision_recall_curvedocstring instructing people to plot it usingplt.step(recall, precision, where='post')and then close this issue. @amueller what do you think?MuhammedHasan commentedon Dec 9, 2020
The problem is not only plotting @ndingwall . Also, AUC value depends on precision-recall values.
Predictions and targets can be ranked then rank can be used as a score so it will break the tie. However, the order of the target important so should be sorted as well.
With tie:
Without tie:
ndingwall commentedon Dec 10, 2020
I'm not sure I follow this. The AUC is affected by your choice of interpolation. Here you've used linear interpolation which isn't valid for precision-recall curves: see https://www.biostat.wisc.edu/~page/rocpr.pdf for an explanation.
When you break ties, you're changing the classifier, so you should expect metrics (like
average_precision_scoreto change).Hoeze commentedon Dec 15, 2020
@ndingwall If you say the step function with
where="post"gives the correct curve, shouldn't the AUC then be calculated from the step function as well?EDIT:
As a demonstration, auc reports 0.2% higher for the step function:
EDIT2:
This is actually very close to average precision score:
0.03238006997915479ndingwall commentedon Dec 16, 2020
Yes, this is exactly what
average_precision_scoredoes since 0.19 (as you noticed). I wrote a whole blog post on this a few years ago if you're interested.amueller commentedon Dec 24, 2020
Is there still any issue with the current state? the
plot_precision_recall_curvefunction actually does the step interpolation, which is the correct thing to do as @ndingwall states.average_precisionnow uses the formula from wikipedia so the point doesn't influence it any more.For AUC, linear interpolation is valid and both the plotting and roc_auc use the linear interpolation.
[This whole thing has been a pet-peeve of mine for years, thanks for the blog post @ndingwall, though I guess it's out of date now since I think we fixed all of the issues?].
Maybe we could make the issue "explain what's up with interpolation", though there's now some references in the docs:
https://scikit-learn.org/dev/modules/model_evaluation.html#precision-recall-and-f-measures
ndingwall commentedon Jan 10, 2021
@amueller, yes, the blog-post should be updated, although I doubt it gets much traffic!
I think precision/recall is a deceptively confusing topic, and there are a few things that compound common misconceptions:
precision_recall_curveisn't ideal, but I can't think of a better alternative and changing it would no doubt break a lot of code.aucdocumentation suggests that you "see also"precision_recall_curve, even though the existingaucfunction can't be used to compute anything meaningful with respect to precision-recall. It also says "For an alternative way to summarize a precision-recall curve, see average_precision_score" which suggests thataucitself is a valid way to summarize a precision-recall curve.average_precision_scoredocumentation isn't explicit enough thataucis not valid for precision-recall curves.plt.plotinstead ofplt.step(the micro-averaged version usesplt.stepcorrectly).I can work on a PR that either (A) minimally corrects the documentation for
auc(explaining that it cannot be used withprecision_recall_scoreand pointing toaverage_precision_scoreas an alternative, or (B) add aninterpolationargument toaucthat can be either"linear"(default) or"step", document thatprecision_recall_curveuses the latter, and haveaverage_precision_scoreuseaucwith the"step"argument.I think (B) risks getting unwieldy since we'd probably end up wanting to offer "from-left" and "from-right" as options for
"step"(for completeness), and before you know it the API is a confusing mess... On the other hand, it would emphasize thatlinearis just one of several ways to compute the area under a curve described by its coordinates.That leaves the Precision Recall multiclass documentation. Since the
precision_recall_curvedocstring says "Note: this implementation is restricted to the binary classification task" and the multiclass example uses the trick of doing 1-vs-rest binary classification for each label, I'd advocate for dropping the multiclass section entirely. We could link to theOneVsRestClassifierif you really want multiclass covered.adrinjalali commentedon Apr 18, 2024
Seems the original issue is actually solved / improved a lot since this issue was opened. Happy to have a fresh issue with concrete points on what can be improved in the docs or the API.