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
---------------------------------------------------------------------------
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
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.
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:
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?
@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)
iflen(np.unique(y_true)) >y_score.shape[1]:
raiseValueError("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.
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.
@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.
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.
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.
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
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.
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
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?
I am not certain, but I think the original PR was merged by mistake
(without review and consensus) and I think removing it in 0.19.1 is the
sanest way to put out the fire.
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.
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.
I am not certain, but I think the original PR was merged by mistake
(without review and consensus) and I think removing it in 0.19.1 is the
sanest way to put out the fire.
mea culpa... no objection to revert and remove in 0.19.1. Sorry again.
I still think though that it is good to have a "validated" standard
implementation
in scikit-learn.
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.
I think a PR would be welcome, but it should focus on uses in the kinds of
machine learning tasks scikit-learn deals with: rectangular features,
rectangular targets.
Activity
[-]Using ndcg_score within RandomizedSearchCV throws an error[/-][+]metrics.ndcg_score is busted[/+]ianlcassidy commentedon Oct 13, 2017
So, I believe this is because the following code snippet
is adding a bunch of extra all 0 columns to
binarized_y_trueand can be fixed by then removing those columns usingjeromedockes commentedon Oct 14, 2017
I think this is the error:
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.
jnothman commentedon Oct 15, 2017
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.
ianlcassidy commentedon Oct 15, 2017
@jeromedockes, @jnothman i propose something like this as a fix:
there is an edge case here for
LabelBinarizerif you have two labels because the output of the transform will be a single column array; e.g.,but, we really want it to output this:
qinhanmin2014 commentedon Oct 15, 2017
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:
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?
Could anyone help me to see if I am wrong? Thanks :)
ianlcassidy commentedon Oct 15, 2017
@qinhanmin2014 I agree that using
OneHotEncorderis 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 iny_trueis less than or equal to the number of columns iny_scorebefore theOneHotEncoderfit/transform code is called. So, how about this: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 wanty_scoreto 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 apredict_probamethod (I think that's what the original author of this metric was intending). Here is a Kaggle thread that is related to this.jeromedockes commentedon Oct 16, 2017
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:
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.
qinhanmin2014 commentedon Oct 16, 2017
@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.
jeromedockes commentedon Oct 16, 2017
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.
Yes this is a very special use of NDCG, not the most common one.
jnothman commentedon Oct 16, 2017
jnothman commentedon Oct 16, 2017
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 iny_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_scoreandmetrics.dcg_scoredo not make an appearance inmetrics.tests.test_common, and as is clear from the present bug, the implementation only possibly works whenlen(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.
FIX ndcg to work for arbitrarily many samples
jnothman commentedon Oct 16, 2017
@ianlcassidy and @jeromedockes, please check that #9928 fixes your cases, at least where all classes are present in
y_true. Thanks.jeromedockes commentedon Oct 16, 2017
NDCG is not for classification; y_score and y_true should have the same shape
jnothman commentedon Oct 16, 2017
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.
jeromedockes commentedon Oct 16, 2017
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
jnothman commentedon Oct 16, 2017
jeromedockes commentedon Oct 16, 2017
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.
jeromedockes commentedon Oct 16, 2017
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.
agramfort commentedon Oct 16, 2017
jeromedockes commentedon Oct 16, 2017
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.
jnothman commentedon Oct 16, 2017