Skip to content

ndcg_score fails for negative scores #17639

Closed
trinhcon/scikit-learn
#6

Description

@dmelis

Description

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?

Versions

numpy: 1.18.1
scipy: 1.4.1
sklearn: 0.22.1

Activity

  1. jnothman commented on Jun 21, 2020

    @jnothman
    Member
  2. gan3sh500 commented on Jun 21, 2020

    @gan3sh500

    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.

  3. jnothman commented on Jun 21, 2020

    @jnothman
    Member
  4. glemaitre commented on Jun 22, 2020

    @glemaitre
    Member

    @jeromedockes You might be the only person that I know that used it. Do you have any advise on this issue.

  5. dsandeep0138 commented on Jun 22, 2020

    @dsandeep0138

    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))
    

    NDCG score calculation:

    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)
    max_dcg  = -0.001494970324771916
    min_dcg =  -1.0747913396929056
    actual_dcg =  -0.5920575220247735
    ndcg_score = 0.44976749334605975
    

    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
    
  6. jeromedockes commented on Jun 22, 2020

    @jeromedockes
    Contributor

    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

  7. jeromedockes commented on Jun 22, 2020

    @jeromedockes
    Contributor

    Is there any other metric in scikit-learn that is more appropriate for that use case?

    maybe roc_auc_score or label_ranking_loss for example?

  8. jeromedockes commented on Jun 22, 2020

    @jeromedockes
    Contributor

    @jeromedockes You might be the only person that I know that used it. Do you have any advise on this issue.

    If we choose that solution I can open a PR raising an exception when y_true contains negative values

  9. dmelis commented on Jun 22, 2020

    @dmelis
    Author

    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.

    Thank you all for your help.

  10. jeromedockes commented on Jun 29, 2020

    @jeromedockes
    Contributor

    @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?

  11. rspreafico-absci commented on Nov 3, 2021

    @rspreafico-absci

    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.

    There are reports in the literature - from prominent scientists - suggesting to z-score y_true before 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 negative y_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_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.

  12. trinhcon commented on Feb 27, 2022

    @trinhcon
    Contributor

    /take

  13. dsandeep0138 commented on Feb 28, 2022

    @dsandeep0138

    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?

  14. trinhcon commented on Mar 3, 2022

    @trinhcon
    Contributor

    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.

  15. added a commit that references this issue on Mar 6, 2022
    30d1f36
  16. thesofakillers commented on Nov 30, 2023

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

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions