Skip to content

metrics.ndcg_score is busted #9921

Closed

Description

@ianlcassidy

Description

metrics.ndcg_score is busted

Steps/Code to Reproduce

from sklearn import metrics

# test 1
y_true = [0, 1, 2, 1]
y_score = [[0.15, 0.55, 0.2], [0.7, 0.2, 0.1], [0.06, 0.04, 0.9], [0.1, 0.3, 0.6]]
metrics.ndcg_score(y_true, y_score)

# test 2
y_true = [0, 1, 0, 1]
y_score = [[0.15, 0.85], [0.7, 0.3], [0.06, 0.94], [0.7, 0.3]]
metrics.ndcg_score(y_true, y_score)

Expected Results

No error is thrown.

Actual Results

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-35bb0e2c9b0e> in <module>()
----> 1 metrics.ndcg_score(y_true, y_score)

/Users/iancassidy/virtualenvs/upside/lib/python2.7/site-packages/sklearn/metrics/ranking.py in ndcg_score(y_true, y_score, k)
    849 
    850     if binarized_y_true.shape != y_score.shape:
--> 851         raise ValueError("y_true and y_score have different value ranges")

ValueError: y_true and y_score have different value ranges

Versions

Darwin-16.7.0-x86_64-i386-64bit
('Python', '2.7.10 (default, Feb  7 2017, 00:08:15) \n[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)]')
('NumPy', '1.13.3')
('SciPy', '0.19.1')
('Scikit-Learn', '0.19.0')

Activity

  1. changed the title [-]Using ndcg_score within RandomizedSearchCV throws an error[/-] [+]metrics.ndcg_score is busted[/+] on Oct 13, 2017
  2. ianlcassidy commented on Oct 13, 2017

    @ianlcassidy
    Author

    So, I believe this is because the following code snippet

    lb = LabelBinarizer()
    lb.fit(np.arange(max(np.max(y_true) + 1, len(y_true))))
    binarized_y_true = lb.transform(y_true)
    

    is adding a bunch of extra all 0 columns to binarized_y_true and can be fixed by then removing those columns using

    binarized_y_true = binarized_y_true[:, ~np.all(binarized_y_true == 0, axis=0)]
    
  3. jeromedockes commented on Oct 14, 2017

    @jeromedockes
    Contributor

    I think this is the error:

        lb.fit(np.arange(max(np.max(y_true) + 1, len(y_true))))
    

    the number of features for the binarizer should be bigger than the biggest label in y_true, and bigger than the number of outputs in y_score. so above len(y_true) should read y_score.shape[1], len(y_true is irrelevant). But actually the number of labels should be equal to the number of columns in y_score, and we should check that the highest label in y_true is smaller than that.

  4. jnothman commented on Oct 15, 2017

    @jnothman
    Member

    Hmm... Thanks for reporting. I agree, @jeromedockes, it looks like len(y_true) should be irrelevant there.

    Whatever the cause, a patch including a test is very welcome.

  5. added this to the 0.19.1 milestone on Oct 15, 2017
  6. ianlcassidy commented on Oct 15, 2017

    @ianlcassidy
    Author

    @jeromedockes, @jnothman i propose something like this as a fix:

    lb = LabelBinarizer()
    lb.fit(np.arange(max(np.max(y_true) + 1, 3)))
    binarized_y_true = lb.transform(y_true)
    if binarized_y_true.shape[1] == 3 and sum(binarized_y_true[:, 2]) == 0:
        binarized_y_true = binarized_y_true[:, :2]
    

    there is an edge case here for LabelBinarizer if you have two labels because the output of the transform will be a single column array; e.g.,

    In []:
    y_true = [0, 1, 0, 1]
    lb = LabelBinarizer()
    lb.fit([0, 1])
    lb.transform(y_true)
    
    Out []:
    array([[0],
           [1],
           [0],
           [1]])
    

    but, we really want it to output this:

    array([[1, 0],
           [0, 1],
           [1, 0],
           [0, 1]])
    
  7. qinhanmin2014 commented on Oct 15, 2017

    @qinhanmin2014
    Member

    Personally, I might not agree with @ianlcassidy's code. It seems really difficult to understand.
    So there seems two problem:
    (1)The shape of binarized_y_true is not correct. It seems that this can be solved by using y_score.shape[1]
    (2)For LabeBinarizer, Binary targets transform to a column vector (because it is designed for labels). An alternative solution might be using OneHotEncoder?
    So I might write something like this:

    enc = OneHotEncoder(sparse = False)
    enc.fit(np.arange(y_score.shape[1]).reshape(-1, 1))
    binarized_y_true = enc.transform(y_true.reshape(-1, 1))

    Also, I strongly doubt whether the implementation is right. It's not consistent with the wiki page, nor with all the materials I can find. And the reference link in the code seems dead. Personally, I might think ogrisel's implementation here is correct. At least in general case, ndcg should accept two 1d array instead of a 1d array and a 2d array. What's the meaning of the score calculated by the following script?

    y_true = [0, 1, 2, 1]
    y_score = [[0.15, 0.55, 0.2], [0.7, 0.2, 0.1], [0.06, 0.04, 0.9], [0.1, 0.3, 0.6]]
    metrics.ndcg_score(y_true, y_score)

    Could anyone help me to see if I am wrong? Thanks :)

  8. ianlcassidy commented on Oct 15, 2017

    @ianlcassidy
    Author

    @qinhanmin2014 I agree that using OneHotEncorder is much less hacky than what I suggested 😄. If we go with that approach, we'll probably also want a check to make sure the number of unique labels in y_true is less than or equal to the number of columns in y_score before the OneHotEncoder fit/transform code is called. So, how about this:

    if ~isinstance(y_true, np.ndarray):
        y_true = np.array(y_true)
        
    if ~isinstance(y_score, np.ndarray):
        y_score = np.array(y_score)
        
    if len(np.unique(y_true)) > y_score.shape[1]:
        raise ValueError("y_true cannot have more labels than the number of columns in y_score")
        
    enc = OneHotEncoder(sparse=False)
    enc.fit(np.arange(y_score.shape[1]).reshape(-1, 1))
    binarized_y_true = enc.transform(y_true.reshape(-1, 1))

    In terms of the implementation, it seems correct to me. If you look at metrics.dcg_score, that follows the logic in the wiki article and it accepts two 1d arrays as inputs. For NDCG, we want y_score to be a 2d array where each row corresponds to the prediction probability of each label. This way it can be used to score the predictions of classifiers that have a predict_proba method (I think that's what the original author of this metric was intending). Here is a Kaggle thread that is related to this.

  9. jeromedockes commented on Oct 16, 2017

    @jeromedockes
    Contributor

    Also, I strongly doubt whether the implementation is right. It's not consistent with the wiki page, nor with all the materials I can find. And the reference link in the code seems dead. Personally, I might think ogrisel's implementation here is correct.

    I completey agree. NDCG is meant to evaluate a ranking with respect to the true scores of the scored entities.

    (see the wikipedia page,
    Järvelin, K., & Kekäläinen, J. (2002). Cumulated gain-based evaluation of IR techniques. ACM Transactions on Information Systems (TOIS), 20(4), 422-446.,
    or Wang, Y., Wang, L., Li, Y., He, D., Chen, W., & Liu, T. Y. (2013, May). A theoretical analysis of NDCG ranking measures. In Proceedings of the 26th Annual Conference on Learning Theory (COLT 2013).)

    For example, evaluate a ranking of answers to a query with respect to the actual relevance of the answers. Ogrisel's code for which @qinhanmin2014 provided a link is a typical use case of NDCG, and the implementation is correct. So ndcg_score should accept two 2-d arrays of the same shape, y_score contains the scores inducing the predicted ranking and y_true containing a floating-point value (e.g. relevance, term frequency, ...) for each output dimension.
    for example something like this should be ok:

    import numpy as np
    
    
    def _cumulative_gain(relevance, ranking, k=None):
        relevance = np.atleast_2d(relevance)
        ranking = np.atleast_2d(ranking)
        ranked = relevance[np.arange(ranking.shape[0])[:, np.newaxis], ranking]
        if k is not None:
            ranked = ranked[:, :k]
        log_indices = np.log(np.arange(ranked.shape[1]) + 2)
        gain = (ranked / log_indices).sum(axis=1)
        return gain
    
    
    def normalized_discounted_cumulative_gain(y_true, y_score, k=None):
        prediction_ranking = np.argsort(y_score)[:, ::-1]
        true_ranking = np.argsort(y_true)[:, ::-1]
        gain = _cumulative_gain(y_true, prediction_ranking, k)
        normalizing_gain = _cumulative_gain(y_true, true_ranking, k)
        all_irrelevant = normalizing_gain == 0
        gain[all_irrelevant] = 0
        gain[~all_irrelevant] /= normalizing_gain[~all_irrelevant]
        return gain
    

    we can check wether y_true is a vector of labels instead of a matrix of true scores and perform one-hot encoding, but since this is not the most common use case it may be better to keep the interface simple and let the user one-hot encode it they want to do this.

  10. qinhanmin2014 commented on Oct 16, 2017

    @qinhanmin2014
    Member

    @ianlcassidy @jeromedockes Thanks a lot for the detailed reply :)
    So seems that current ndcg is just a copy-past from kaggle by the original author.
    I agree with @jeromedockes (though I might make ndcg simpler to accept two 1d array instead of two 2d array). It seems not suitable to take a kaggle kernel as our reference, especially considering that the kernel is actually designed for certain competition. @ianlcassidy you actually don't answer my question. What's the meaning of supporting different categories and then calculating the mean value in ndcg? After quickly scanning the competition, I would rather believe the competition require some wrapper around ndcg to calculate the competition score. This kernel in the same competition seems much reasonable to me. It provides functions to calculate dcg and ndcg along with a function to calculate the competition score based on ndcg.

  11. jeromedockes commented on Oct 16, 2017

    @jeromedockes
    Contributor

    I might make ndcg simpler to accept two 1d array instead of two 2d array).

    This is true. However, I imagine in most cases the user will want to score a
    bunch of predictions rather than just one, hence the 2d arrays. I'd be happy to
    open a PR either way (1d / one sample or 2d / several samples).

    detail: to avoid the division by zero, [Järvelin, K., & Kekäläinen, J. (2002)]
    (the original paper) don't apply the discount to i=1. They also don't apply the
    discount for indices up to b, where b is the basis of the log, when computing
    DCG. [Wang, Y., Wang, L., Li, Y., He, D., Chen, W., & Liu, T. Y. (2013, May)]
    uses log(i+1) for the discount and apply it everywhere (I think this is the most
    commonly used discount). With this definition, the basis of the logarithm
    doesn't matter for NDCG.

    This is a separate issue, but it might also be useful to include weighted recall
    @ k, as it is another popular metric for evaluating a ranking against a vector
    of scores.

    It seems not suitable to take a kaggle kernel
    as our reference, especially considering that the kernel is actually designed
    for certain competition.

    Yes this is a very special use of NDCG, not the most common one.

  12. jnothman commented on Oct 16, 2017

    @jnothman
    Member
  13. jnothman commented on Oct 16, 2017

    @jnothman
    Member

    So without reading too deeply into the above discussion, the problem stems from the fact that ndcg is apparently the first metric we have implemented which supports multiclass (not multilabel or binary) classification with a score, and we've just not implemented it right.

    I think using binarized_y_true = label_binarize(y_true, np.unique(y_true)) will work in the case that all classes used to trained the estimator are present in y_true.

    Using binarized_y_true = label_binarize(y_true, np.arange(y_score.shape[1])) will work when this condition is violated, but the original training data had classes represented by all numbers in range 0..max(y).

    I think we should take the former approach, but should provide a parameter where the user can specify the mapping defined by a classifier's classes_ attribute.

    Disappointingly, metrics.ndcg_score and metrics.dcg_score do not make an appearance in metrics.tests.test_common, and as is clear from the present bug, the implementation only possibly works when len(y_true) == y_score.shape[1] which is weird.

    I do not understand why #7739 was essentially merged without review. This should be properly fixed within the 0.19 series, but I think we should release 0.19.1 with only the barest fix.

  14. added a commit that references this issue on Oct 16, 2017
    b331527
  15. jnothman commented on Oct 16, 2017

    @jnothman
    Member

    @ianlcassidy and @jeromedockes, please check that #9928 fixes your cases, at least where all classes are present in y_true. Thanks.

  16. jeromedockes commented on Oct 16, 2017

    @jeromedockes
    Contributor

    So without reading too deeply into the above discussion, the problem stems from the fact that ndcg is apparently the first metric we have implemented which supports multiclass (not multilabel or binary) classification with a score, and we've just not implemented it right.

    NDCG is not for classification; y_score and y_true should have the same shape

  17. jnothman commented on Oct 16, 2017

    @jnothman
    Member

    I think you're misunderstanding what ndcg_score is trying to achieve in our implementation, though I agree that it is somewhat obscure and it is vastly under-documented (hence #9931). It is interpreting multiclass classification as "each class is to receive a score ranking it, and only one class is relevant". I think this should be extended to multilabel binary relevance evaluation.

    I don't think that dealing with true ranking (i.e. each output is understood to be a continuous measure comparable in rank against other outputs) is really within scope for scikit-learn.

    It also disturbs me a little that the merged implementation differs from #2805 which it claimed to extend substantially.

  18. jeromedockes commented on Oct 16, 2017

    @jeromedockes
    Contributor

    I think you're misunderstanding what ndcg_score is trying to achieve in our implementation, though I agree that it is somewhat obscure and it is vastly under-documented (hence #9931). It is interpreting multiclass classification as "each class is to receive a score ranking it, and only one class is relevant". I think this should be extended to multilabel binary relevance evaluation.

    I see, sorry about that. both the name and the implementation are a bit confusing then, nothing is being cumulated and the normalizing constant is always 1

  19. jnothman commented on Oct 16, 2017

    @jnothman
    Member
  20. jeromedockes commented on Oct 16, 2017

    @jeromedockes
    Contributor

    yes, I was also surprised to see it's not multilabel. Do you agree that having a ndcg implementation for multilabel ground truth would at least be useful?

    NDCG for a multilabel would be useful. In this case, the interface and
    implementation would be identical as for the general case (multilabel would
    simply correspond to the special case where relevance scores are binary), and
    since some of the motivation for NDCG was to start using non-binary relevance
    scores ("highly relevant documents are more valuable than marginally relevant
    documents"), it would do no harm to allow a floating-point ground truth to be
    passed.
    But if as you said, ranking and IR metrics are outside of the scope of
    scikit-learn, maybe NDCG isn't essential.

  21. jeromedockes commented on Oct 16, 2017

    @jeromedockes
    Contributor

    I think removing it in 0.19.1 is the sanest way to put out the fire.

    This sounds perfectly reasonable; a discussion about wether it should be
    included and what scikit-learn users would use it for can always be reopened. It
    is very easy to implement and takes only a few lines of code, and the current
    version is clearly flawed.

  22. agramfort commented on Oct 16, 2017

    @agramfort
    Member
  23. jeromedockes commented on Oct 16, 2017

    @jeromedockes
    Contributor

    I still think though that it is good to have a "validated" standard implementation in scikit-learn.

    I can open a PR if you think it is useful. I think the snippet I posted above is
    a correct implementation of the standard definition of NDCG. Again, I think that
    any implementation suiting the sklearn API should accept 2d arrays of the same
    shape; NDCG is a ranking metric and the user should provide the true scores and
    predicted scores for all candidates. In the kaggle airbnb competition the
    previous implementation referred to, it just happened to be the case that only
    one answer was relevant for each query. But the competition description
    uses the general definition of NDCG: a discounted sum of the relevance scores of
    all candidates, sorted in the predicted order. It would probably be better not
    to have it than present it as a metric for multiclass classification.

    If we also provide DCG, it may be useful to expose the discount function (or at
    least the basis of the log) as a parameter. For NDCG, the basis of the log
    doesn't matter and [Wang, Y., Wang, L., Li, Y., He, D., Chen, W., & Liu, T. Y.
    (2013, May). A theoretical analysis of NDCG ranking measures. In Proceedings of
    the 26th Annual Conference on Learning Theory (COLT 2013).)] gives a formal
    justification for the standard (logarithmic) discount.

    Finally, people use different gain functions (for example 2^rel_i to put
    emphasis on highly relevant documents). Since the user provides the true scores,
    I think it is safe to assume that the user provides the output of the gain
    function, i.e. true_y are the scores, to be used without any transformation.

  24. jnothman commented on Oct 16, 2017

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions