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
The method ndcg_score from sklearn.metrics fails when the true relevance scores are negative.
Steps/Code to Reproduce
import numpy as np
from sklearn.metrics import ndcg_score
y_true = np.array([-0.89, -0.53, -0.47, 0.39, 0.56]).reshape(1,-1)
y_score = np.array([0.07,0.31,0.75,0.33,0.27]).reshape(1,-1)
ndcg_score(y_true, y_score) # Should be between 0 and 1 as per the docstring
>>> 396.0329594603174
ndcg_score(y_true+1, y_score+1)
>>> 0.7996030755957273
Expected Results
The documentation doesn't explicitly state that y_true or y_score should be non-negative. The cited Wikipedia article for DCG doesn't seem to mention a non-negativity assumption either. So either the method should be able to deal with scores regardless of sign, or the documentation should explicitly say otherwise.
Disclosure/Question: I'm not an expert in ranking metrics, but it seems that there might be cases where one might want to compare lists of scores in (-∞,∞) based on their ordering alone (i.e., not MSE or related metrics). Is there any other metric in scikit-learn that is more appropriate for that use case?
Silently producing bogus results is certainly not acceptable behaviour.
Thanks for the report!
I don't see a reason to refuse negative scores in ranking.
What would be the fix for this? Even the Wikipedia page says how negative scores can change the ndcg from being in 0 to 1 range to negative value to 1 range.
Is it a warning if negative scores are given or shifting scores to all be positive.
This is what I think of this issue. Please let me know your comments.
NDCG is a metric that should be a value between 0 and 1. This is given by NDCG = actual DCG / Ideal DCG. Rephrasing it, NDCG is actually a measure of where our DCG is on a scale of 0 and Ideal DCG. This is because, min DCG is always assumed to be 0, which might be true in other cases, but not in a case where we have negative y_true values. So, correcting the above rephrased sentence, we can say, NDCG is actually a measure of where our DCG is located on a scale of min DCG and Ideal DCG
So, the actual NDCG formula should have been, NDCG = (actual DCG - min DCG) / (Ideal DCG - min DCG). When lower bound (i.e., minimum) is 0, we get back the formula that we always used.
Next, is how do we calculate Ideal DCG and min DCG given y_true and y_score.
# From the wiki, sorting all relevant documents in the corpus by their
# relative relevance, produces the maximum possible DCG through position,
# also called Ideal DCG (IDCG) through that position
Ideal DCG = dcg_score(sorted(y_true, reverse=True), sorted(y_true, reverse=True))
# Likewise to get min DCG, take the documents in the opposite direction.
# Notice that the 2nd argument is sorted in ascending order
# (least relevance to most relevance)
min DCG = dcg_score(sorted(y_true, reverse=True), sorted(y_true, reverse=False))
On a final note, y_score values just provide the relative ranks (or positions). y_score values are not involved in the calculation of dcg (or ndcg), only their positions are taken. So, shifting the y_score values by a constant amount shouldn't affect the ndcg score, right (because the positions wouldn't change)? And when you consider a formula with min DCG, I can see this to hold true.
# I have increased all y_score values by 1
y_true = np.array([-0.89, -0.53, -0.47, 0.39, 0.56]).reshape(1,-1)
y_score = np.array([1.07, 1.31, 1.75, 1.33, 1.27]).reshape(1,-1)
max_dcg = 2.9469641485546205
min_dcg: 1.8736677791864862
actual_dcg = 2.3564015968546186
ndcg_score = 0.4497674933460597
Reacted by Srimukh Sripada, Mahesh Ravariya and Pavel Perestoronin
So, the actual NDCG formula should have been, NDCG = (actual DCG - min DCG) / (Ideal DCG - min DCG). When lower bound (i.e., minimum) is 0, we get back the formula that we always used.
I think the metric you describe is meaningful, but I have not seen NDCG defined like this (for example not in Wikipedia nor in either of the three references cited in the docstring). Therefore it would be a useful metric, but it is not NDCG (and will almost never coincide with it; note that the min dcg will usually not be 0).
So far I could not find a reference addressing the problem of negative gains (ie relevance, y_true); I believe the least surprising behavior would be to refuse negative relevances.
For the scores, ie y_score, the predicted values, indeed only the ordering they produce matters, not their actual value
maybe roc_auc_score or label_ranking_loss for example?
Unfortunately both of those expect binary (or multi-class, discrete) y_true labels, but in my problem the true scores are real-valued. For now, I think I'll go with @dsandeep0138's approach, which indeed might not be formally NDCG, but seems quite sensible.
As for the issue, raising an exception for negative values of y_true seems like a good compromise solution.
@glemaitre and others what do you think? should I open a PR forbidding negative values in y_true ? and if so, should it raise a DeprecationWarning and keep returning the same results for now, or start raising a ValueError right away?
Seems to me that the original definition of NDCG just didn't account properly for negative values, as they were likely not expected in the foreseen use cases (e.g. ranking web page search results). As a result, there is no perfect way to handle those. Rejecting negative y_true values seems at odds with the absence of a specific provision forbidding negative values. Accepting negative values may sometimes give nonsensical results.
My opinion is that something is better than nothing. Right now, as of scikit-learn 1.0, ndcg_score still returns values not bounded within 0 and 1 when negative y_trues are provided. Any of the proposed fixes will be better than the current state of things. I personally am in favor of returning results (since the NDCG formula is being applied correctly) but warning that the output is not guaranteed to be bounded between 0 and 1 in the presence of negative y_trues. It may be useful to link this Github issue from the documentation or even from the warning message. This way, people will have the option to go with @dsandeep0138's approach, which looks indeed very sensible to me, even if it does not describe any published metric.
To that point, I wonder whether @dsandeep0138 would consider publishing that formula in a quick report - maybe even just an arXiv pre-print - which would provide a reference for implementing his formula as an additional metric in scikit-learn. The value of supporting negative values is that it would allow processing z-scores, which in turn are useful when comparing (pseudo-)NDCG scores across datasets.
To that point, I wonder whether @dsandeep0138 would consider publishing that formula in a quick report - maybe even just an arXiv pre-print - which would provide a reference for implementing his formula as an additional metric in scikit-learn. The value of supporting negative values is that it would allow processing z-scores, which in turn are useful when comparing (pseudo-)NDCG scores across datasets.
Sorry, I haven't been active on this thread. I can make a report. Can someone (maybe @jeromedockes / @rspreafico-absci) please help me with a report template, and I can share back with details filled in?
Hi there,
The implementation in the branch that mentioned this issue throws a "DeprecationWarning" as suggested by jeromesdockes. This sort of gives the best of both worlds, that it allows current functionality to still be used, but throws the warning about ndcg_score not always providing results between 0 and 1 for negative y_true values.
Feel free to suggest other changes too, if there's another change in mind. I'll be making a PR to this repo within a few days, once I get docs and tests done.
Activity
jnothman commentedon Jun 21, 2020
gan3sh500 commentedon Jun 21, 2020
What would be the fix for this? Even the Wikipedia page says how negative scores can change the ndcg from being in 0 to 1 range to negative value to 1 range.
Is it a warning if negative scores are given or shifting scores to all be positive.
jnothman commentedon Jun 21, 2020
glemaitre commentedon Jun 22, 2020
@jeromedockes You might be the only person that I know that used it. Do you have any advise on this issue.
dsandeep0138 commentedon Jun 22, 2020
This is what I think of this issue. Please let me know your comments.
NDCGis a metric that should be a value between 0 and 1. This is given byNDCG = actual DCG / Ideal DCG. Rephrasing it,NDCGis actually a measure of where our DCG is on a scale of 0 and Ideal DCG. This is because, min DCG is always assumed to be 0, which might be true in other cases, but not in a case where we have negative y_true values. So, correcting the above rephrased sentence, we can say,NDCGis actually a measure of where our DCG is located on a scale of min DCG and Ideal DCGSo, the actual NDCG formula should have been,
NDCG = (actual DCG - min DCG) / (Ideal DCG - min DCG). When lower bound (i.e., minimum) is 0, we get back the formula that we always used.Next, is how do we calculate Ideal DCG and min DCG given y_true and y_score.
NDCG score calculation:
On a final note, y_score values just provide the relative ranks (or positions). y_score values are not involved in the calculation of dcg (or ndcg), only their positions are taken. So, shifting the y_score values by a constant amount shouldn't affect the ndcg score, right (because the positions wouldn't change)? And when you consider a formula with min DCG, I can see this to hold true.
jeromedockes commentedon Jun 22, 2020
I think the metric you describe is meaningful, but I have not seen NDCG defined like this (for example not in Wikipedia nor in either of the three references cited in the docstring). Therefore it would be a useful metric, but it is not NDCG (and will almost never coincide with it; note that the min dcg will usually not be 0).
So far I could not find a reference addressing the problem of negative gains (ie relevance,
y_true); I believe the least surprising behavior would be to refuse negative relevances.For the scores, ie
y_score, the predicted values, indeed only the ordering they produce matters, not their actual valuejeromedockes commentedon Jun 22, 2020
maybe
roc_auc_scoreorlabel_ranking_lossfor example?jeromedockes commentedon Jun 22, 2020
If we choose that solution I can open a PR raising an exception when
y_truecontains negative valuesdmelis commentedon Jun 22, 2020
Unfortunately both of those expect binary (or multi-class, discrete)
y_truelabels, but in my problem the true scores are real-valued. For now, I think I'll go with @dsandeep0138's approach, which indeed might not be formally NDCG, but seems quite sensible.As for the issue, raising an exception for negative values of
y_trueseems like a good compromise solution.Thank you all for your help.
jeromedockes commentedon Jun 29, 2020
@glemaitre and others what do you think? should I open a PR forbidding negative values in
y_true? and if so, should it raise a DeprecationWarning and keep returning the same results for now, or start raising a ValueError right away?rspreafico-absci commentedon Nov 3, 2021
Seems to me that the original definition of NDCG just didn't account properly for negative values, as they were likely not expected in the foreseen use cases (e.g. ranking web page search results). As a result, there is no perfect way to handle those. Rejecting negative
y_truevalues seems at odds with the absence of a specific provision forbidding negative values. Accepting negative values may sometimes give nonsensical results.There are reports in the literature - from prominent scientists - suggesting to z-score
y_truebefore computing NDCG, in order to compare NDCGs produced from different datasets in a sensible way (https://www.biorxiv.org/content/10.1101/2021.03.28.437402v1). By definition, z-scoring will produce negativey_trues. So handling negative scores seem urgent.My opinion is that something is better than nothing. Right now, as of scikit-learn 1.0,
ndcg_scorestill returns values not bounded within 0 and 1 when negativey_trues are provided. Any of the proposed fixes will be better than the current state of things. I personally am in favor of returning results (since the NDCG formula is being applied correctly) but warning that the output is not guaranteed to be bounded between 0 and 1 in the presence of negativey_trues. It may be useful to link this Github issue from the documentation or even from the warning message. This way, people will have the option to go with @dsandeep0138's approach, which looks indeed very sensible to me, even if it does not describe any published metric.To that point, I wonder whether @dsandeep0138 would consider publishing that formula in a quick report - maybe even just an arXiv pre-print - which would provide a reference for implementing his formula as an additional metric in scikit-learn. The value of supporting negative values is that it would allow processing z-scores, which in turn are useful when comparing (pseudo-)NDCG scores across datasets.
trinhcon commentedon Feb 27, 2022
/take
dsandeep0138 commentedon Feb 28, 2022
Sorry, I haven't been active on this thread. I can make a report. Can someone (maybe @jeromedockes / @rspreafico-absci) please help me with a report template, and I can share back with details filled in?
trinhcon commentedon Mar 3, 2022
Hi there,
The implementation in the branch that mentioned this issue throws a "DeprecationWarning" as suggested by jeromesdockes. This sort of gives the best of both worlds, that it allows current functionality to still be used, but throws the warning about ndcg_score not always providing results between 0 and 1 for negative y_true values.
Feel free to suggest other changes too, if there's another change in mind. I'll be making a PR to this repo within a few days, once I get docs and tests done.
Merge pull request #6 from trinhcon/dev
thesofakillers commentedon Nov 30, 2023
Btw, @dsandeep0138 's suggestion appears in this paper https://dl.acm.org/doi/10.1145/3340531.3412123, also available here https://downloads.webis.de/publications/papers/gienapp_2020c.pdf (I have no affiliation with the authors)