Repository navigation
Conversation
|
merge conflict ;) |
it was a small patch, resolved. |
amueller
left a comment
There was a problem hiding this comment.
Should we make labels mandatory as part of this PR? (i.e. warn if it's not passed and say it will required in a future version)
|
|
||
| if present_labels_ - labels_: | ||
| if not allow_labels_subset: | ||
| warnings.warn("The `allow_labels_subset` argument should be True " |
There was a problem hiding this comment.
I would say "The labels argument %s was a subset of the present classes %s. If you want to compute a metric on the subset of the classes, set allow_label_subset=True. This warning was introduced in 0.20 and will turn into an error in version 0.22."
|
|
||
| def confusion_matrix(y_true, y_pred, labels=None, sample_weight=None): | ||
| def confusion_matrix(y_true, y_pred, labels=None, sample_weight=None, | ||
| allow_labels_subset=False): |
There was a problem hiding this comment.
I would maybe say allow_label_subset?
There was a problem hiding this comment.
both sound good to me. i'll change it.
| allow_labels_subset : bool, optional default = False | ||
| This should be set to True if scoring on a subset of labels is | ||
| required. The subset of labels to score on should be passed in the | ||
| ``labels`` argument. |
There was a problem hiding this comment.
If not True and labels contains only a subset of the present classes, an error will be raised starting version 0.22.
| labels = unique_labels(y_true, y_pred) | ||
| labels = present_labels | ||
| else: | ||
| _check_labels_subset(present_labels, labels, allow_labels_subset) |
There was a problem hiding this comment.
Maybe I would put the if not allow_label_subset here and not pass as argument.
There was a problem hiding this comment.
i did that earlier but it was actually being repeated various times so i thought this might be better
| self._factory_args(), kwargs_string)) | ||
|
|
||
| def _get_labels_from_estimator(self, estimator, target_type): | ||
| """Check if estimator has a classes argument and if scorer has a |
There was a problem hiding this comment.
Even though it's private it would be good to document parameters.
There was a problem hiding this comment.
should be self._pass_classes instead of labels, and "as keyword argument to make_scorer".
| # labels should be a subset of classes | ||
| if not set(classes).issuperset( | ||
| set(self._kwargs[self._pass_classes])): | ||
| raise ValueError("`estimator classes=%s` is not the" |
There was a problem hiding this comment.
backticks indicate code, estimator classes=%s is not really code, so I wouldn't put it in backticks. maybe I'd use type(estimator).__name__ instead of "estimator" here.
| scorer = make_scorer(DummyScorerWithLabels, labels=[1, 2, 3]) | ||
| expected_msg = ("`estimator classes=[0 1]` is not the" | ||
| "superset of `scorer labels=[1, 2, 3]`") | ||
| assert_raise_message(ValueError, expected_msg, |
There was a problem hiding this comment.
Add a test for the subset warning, make a scorer with allow_label_subset and test that it doesn't warn and has the same result.
There was a problem hiding this comment.
won't that be covered in the test of metrics as that check happens in metrics?
| y_pred = np.vstack([p[:, -1] for p in y_pred]).T | ||
|
|
||
| if self._pass_classes is None: | ||
| kwargs = self._kwargs |
There was a problem hiding this comment.
maybe i should take this if inside the function. otherwise i'll have to write more tests for all 3 kind of scorers, which seem redundant.
| y_pred = clf.predict_proba(X) | ||
|
|
||
| if self._pass_classes is None: | ||
| kwargs = self._kwargs |
| (classes, | ||
| self._pass_classes, | ||
| self._kwargs['labels'])) | ||
| return self._kwargs |
There was a problem hiding this comment.
oh yea.. this will happen in case the estimator is something other than a classifier. but then the scorer_func will not have a labels parameter. should we remove this? or should we still check it just in case a user defined metrics for say regressor has a labels parameter?
|
My intial thoughts are not to make labels mandatory, but unless you have
other queries, I'll have a look here after your review is addressed...
…On 29 Aug 2017 5:08 am, "Andreas Mueller" ***@***.***> wrote:
***@***.**** commented on this pull request.
Should we make labels mandatory as part of this PR? (i.e. warn if it's
not passed and say it will required in a future version)
------------------------------
In sklearn/metrics/classification.py
<#9585 (comment)>
:
> @@ -112,6 +112,20 @@ def _weighted_sum(sample_score, sample_weight, normalize=False):
return sample_score.sum()
+def _check_labels_subset(present_labels, labels, allow_labels_subset):
+ present_labels_ = set(present_labels)
+ labels_ = set(labels)
+
+ if present_labels_ - labels_:
+ if not allow_labels_subset:
+ warnings.warn("The `allow_labels_subset` argument should be True "
I would say "The labels argument %s was a subset of the present classes
%s. If you want to compute a metric on the subset of the classes, set
allow_label_subset=True. This warning was introduced in 0.20 and will
turn into an error in version 0.22."
------------------------------
In sklearn/metrics/classification.py
<#9585 (comment)>
:
> @@ -183,7 +197,8 @@ def accuracy_score(y_true, y_pred, normalize=True, sample_weight=None):
return _weighted_sum(score, sample_weight, normalize)
-def confusion_matrix(y_true, y_pred, labels=None, sample_weight=None):
+def confusion_matrix(y_true, y_pred, labels=None, sample_weight=None,
+ allow_labels_subset=False):
I would maybe say allow_label_subset?
------------------------------
In sklearn/metrics/classification.py
<#9585 (comment)>
:
> @@ -213,6 +228,13 @@ def confusion_matrix(y_true, y_pred, labels=None, sample_weight=None):
sample_weight : array-like of shape = [n_samples], optional
Sample weights.
+ allow_labels_subset : bool, optional default = False
+ This should be set to True if scoring on a subset of labels is
+ required. The subset of labels to score on should be passed in the
+ ``labels`` argument.
If not True and labels contains only a subset of the present classes, an
error will be raised starting version 0.22.
------------------------------
In sklearn/metrics/classification.py
<#9585 (comment)>
:
> else:
+ _check_labels_subset(present_labels, labels, allow_labels_subset)
Maybe I would put the if not allow_label_subset here and not pass as
argument.
------------------------------
In sklearn/metrics/scorer.py
<#9585 (comment)>
:
> @@ -67,6 +69,43 @@ def __repr__(self):
"" if self._sign > 0 else ", greater_is_better=False",
self._factory_args(), kwargs_string))
+ def _get_labels_from_estimator(self, estimator, target_type):
+ """Check if estimator has a classes argument and if scorer has a
First line needs to be a short summary, see pep 257
<https://www.python.org/dev/peps/pep-0257/#multi-line-docstrings>
------------------------------
In sklearn/metrics/scorer.py
<#9585 (comment)>
:
> @@ -67,6 +69,43 @@ def __repr__(self):
"" if self._sign > 0 else ", greater_is_better=False",
self._factory_args(), kwargs_string))
+ def _get_labels_from_estimator(self, estimator, target_type):
+ """Check if estimator has a classes argument and if scorer has a
Even though it's private it would be good to document parameters.
------------------------------
In sklearn/metrics/scorer.py
<#9585 (comment)>
:
>
class _BaseScorer(six.with_metaclass(ABCMeta, object)):
- def __init__(self, score_func, sign, kwargs):
+ def __init__(self, score_func, sign, pass_classes, kwargs):
maybe we should have a proper docstring for the parameters?
------------------------------
In sklearn/metrics/scorer.py
<#9585 (comment)>
:
> + """Check if estimator has a classes argument and if scorer has a
+ labels argument and return new kwargs for scorer if label not already
+ set in make score initialization"""
+ classes = getattr(estimator, "classes_", None)
+
+ # if classes_ parameter doesn't exist
+ if classes is None:
+ return self._kwargs
+
+ if self._pass_classes in signature(self._score_func).parameters:
+ # if labels passed as kwargs, return kwargs as is
+ if self._pass_classes in self._kwargs:
+ if classes is not None:
+ # labels should be a subset of classes
+ if not set(classes).issuperset(
+ set(self._kwargs[self._pass_classes])):
do you need the set here?
------------------------------
In sklearn/metrics/scorer.py
<#9585 (comment)>
:
> @@ -67,6 +69,43 @@ def __repr__(self):
"" if self._sign > 0 else ", greater_is_better=False",
self._factory_args(), kwargs_string))
+ def _get_labels_from_estimator(self, estimator, target_type):
+ """Check if estimator has a classes argument and if scorer has a
should be self._pass_classes instead of labels, and "as keyword argument
to make_scorer".
------------------------------
In sklearn/metrics/scorer.py
<#9585 (comment)>
:
> + set(self._kwargs[self._pass_classes])):
+ raise ValueError("`estimator classes=%s` is not the"
+ "superset of `scorer %s=%s`" %
+ (classes,
+ self._pass_classes,
+ self._kwargs['labels']))
+ return self._kwargs
+ else:
+ kwargs = self._kwargs.copy()
+ if target_type == 'multilabel-indicator':
+ kwargs[self._pass_classes] = list(range(len(classes)))
+ else:
+ kwargs[self._pass_classes] = classes
+ return kwargs
+ else:
+ if self._pass_classes != 'labels':
I still think this is a bit strange, but I don't have a better idea right
now.
------------------------------
In sklearn/metrics/scorer.py
<#9585 (comment)>
:
> @@ -431,6 +489,14 @@ def make_scorer(score_func, greater_is_better=True, needs_proba=False,
For example ``average_precision`` or the area under the roc curve
can not be computed using discrete predictions alone.
+ pass_classes : string or None, default='labels'
+ The name of the scorer parameter into which the ``classes_`` attribute
+ of the estimator will be passed through. If None is passed, then the
+ ``classes_`` atribute will not be copied.
copied -> passed
------------------------------
In sklearn/metrics/scorer.py
<#9585 (comment)>
:
> @@ -431,6 +489,14 @@ def make_scorer(score_func, greater_is_better=True, needs_proba=False,
For example ``average_precision`` or the area under the roc curve
can not be computed using discrete predictions alone.
+ pass_classes : string or None, default='labels'
+ The name of the scorer parameter into which the ``classes_`` attribute
+ of the estimator will be passed through. If None is passed, then the
+ ``classes_`` atribute will not be copied.
+
+ It should be set only if a user-defined metric function is being used
+ and left as default in case of a scikit-learn API metric.
would remove "API"
------------------------------
In sklearn/metrics/tests/test_classification.py
<#9585 (comment)>
:
> +def test_check_labels_subset():
+ y = [1, 1, 2, 2, 3, 3]
+ labels1 = np.array([1, 2])
+ labels2 = np.array([1, 2, 4])
+ expected_msg1 = ("The `allow_labels_subset` argument should be True "
+ "if a subset of available classes=[1 2 3] was passed in "
+ " the labels=[1 2] argument. `allow_labels_subset` was "
+ " added in version 0.20 and this behavior will "
+ "result in error from version 0.22.")
+ expected_msg2 = ("The `allow_labels_subset` argument should be True "
+ "if a subset of available classes=[1 2 3] was passed in "
+ " the labels=[1 2 4] argument. `allow_labels_subset` was "
+ " added in version 0.20 and this behavior will "
+ "result in error from version 0.22.")
+
+ scorers_to_check = [confusion_matrix, cohen_kappa_score, recall_score,
I think this should be defined on file-level. Maybe this should rather
live in metrics/test_common.py?
------------------------------
In sklearn/metrics/tests/test_classification.py
<#9585 (comment)>
:
> + precision_score, precision_recall_fscore_support,
+ fbeta_score, f1_score, classification_report,
+ hamming_loss, log_loss]
+
+ for scorer in scorers_to_check:
+ kwargs = {}
+ params = signature(scorer).parameters
+ if 'average' in params:
+ kwargs['average'] = 'micro'
+ if 'beta' in params:
+ kwargs['beta'] = 2
+
+ assert_warns_message(DeprecationWarning,
+ expected_msg1,
+ scorer, y, y, labels=labels1, **kwargs)
+ if scorer != log_loss:
why?
------------------------------
In sklearn/metrics/tests/test_score_objects.py
<#9585 (comment)>
:
> @@ -526,3 +546,39 @@ def test_scoring_is_not_metric():
Ridge(), r2_score)
assert_raises_regexp(ValueError, 'make_scorer', check_scoring,
KMeans(), cluster_module.adjusted_rand_score)
+
+
+def test_pass_classes():
+ # Test the various properties of pass_classes parameter added
added only makes sense in this commit, and not afterwards, so I'd remove
it.
------------------------------
In sklearn/metrics/tests/test_score_objects.py
<#9585 (comment)>
:
> +def test_pass_classes():
+ # Test the various properties of pass_classes parameter added
+
+ X, y = make_blobs(random_state=0, centers=2)
+ clf = LogisticRegression(random_state=0)
+ clf.fit(X, y)
+
+ # copy_classes=None should not set labels
+ scorer = make_scorer(DummyScorerWithLabels, pass_classes=None)
+ assert_equal(scorer(clf, X, y), 0)
+
+ # by default, labels should be set
+ scorer = make_scorer(DummyScorerWithLabels)
+ assert_equal(scorer(clf, X, y), 1)
+
+ # by default, labels should be set
this comment seems odd
------------------------------
In sklearn/metrics/scorer.py
<#9585 (comment)>
:
> @@ -198,12 +250,18 @@ def __call__(self, clf, X, y, sample_weight=None):
elif isinstance(y_pred, list):
y_pred = np.vstack([p[:, -1] for p in y_pred]).T
+ if self._pass_classes is None:
When I suggested you put the if here, I think I didn't realize that it'll
be replicated three times. I'm not sure any more that was a good idea, but
I don't have a strong opinion.
------------------------------
In sklearn/metrics/scorer.py
<#9585 (comment)>
:
> + labels argument and return new kwargs for scorer if label not already
+ set in make score initialization"""
+ classes = getattr(estimator, "classes_", None)
+
+ # if classes_ parameter doesn't exist
+ if classes is None:
+ return self._kwargs
+
+ if self._pass_classes in signature(self._score_func).parameters:
+ # if labels passed as kwargs, return kwargs as is
+ if self._pass_classes in self._kwargs:
+ if classes is not None:
+ # labels should be a subset of classes
+ if not set(classes).issuperset(
+ set(self._kwargs[self._pass_classes])):
+ raise ValueError("`estimator classes=%s` is not the"
backticks indicate code, estimator classes=%s is not really code, so I
wouldn't put it in backticks. maybe I'd use type(estimator).__name__
instead of "estimator" here.
------------------------------
In sklearn/metrics/tests/test_score_objects.py
<#9585 (comment)>
:
> + clf = LogisticRegression(random_state=0)
+ clf.fit(X, y)
+
+ # copy_classes=None should not set labels
+ scorer = make_scorer(DummyScorerWithLabels, pass_classes=None)
+ assert_equal(scorer(clf, X, y), 0)
+
+ # by default, labels should be set
+ scorer = make_scorer(DummyScorerWithLabels)
+ assert_equal(scorer(clf, X, y), 1)
+
+ # by default, labels should be set
+ scorer = make_scorer(DummyScorerWithLabels, labels=[1, 2, 3])
+ expected_msg = ("`estimator classes=[0 1]` is not the"
+ "superset of `scorer labels=[1, 2, 3]`")
+ assert_raise_message(ValueError, expected_msg,
Add a test for the subset warning, make a scorer with allow_label_subset
and test that it doesn't warn and has the same result.
------------------------------
In sklearn/metrics/scorer.py
<#9585 (comment)>
:
> @@ -198,12 +250,18 @@ def __call__(self, clf, X, y, sample_weight=None):
elif isinstance(y_pred, list):
y_pred = np.vstack([p[:, -1] for p in y_pred]).T
+ if self._pass_classes is None:
+ kwargs = self._kwargs
not covered!
------------------------------
In sklearn/metrics/scorer.py
<#9585 (comment)>
:
> @@ -136,12 +181,19 @@ def __call__(self, clf, X, y, sample_weight=None):
super(_ProbaScorer, self).__call__(clf, X, y,
sample_weight=sample_weight)
y_pred = clf.predict_proba(X)
+
+ if self._pass_classes is None:
+ kwargs = self._kwargs
not covered!
------------------------------
In sklearn/metrics/scorer.py
<#9585 (comment)>
:
> + if classes is None:
+ return self._kwargs
+
+ if self._pass_classes in signature(self._score_func).parameters:
+ # if labels passed as kwargs, return kwargs as is
+ if self._pass_classes in self._kwargs:
+ if classes is not None:
+ # labels should be a subset of classes
+ if not set(classes).issuperset(
+ set(self._kwargs[self._pass_classes])):
+ raise ValueError("`estimator classes=%s` is not the"
+ "superset of `scorer %s=%s`" %
+ (classes,
+ self._pass_classes,
+ self._kwargs['labels']))
+ return self._kwargs
not covered!
------------------------------
In sklearn/metrics/tests/test_classification.py
<#9585 (comment)>
:
> + precision_score, precision_recall_fscore_support,
+ fbeta_score, f1_score, classification_report,
+ hamming_loss, log_loss]
+
+ for scorer in scorers_to_check:
+ kwargs = {}
+ params = signature(scorer).parameters
+ if 'average' in params:
+ kwargs['average'] = 'micro'
+ if 'beta' in params:
+ kwargs['beta'] = 2
+
+ assert_warns_message(DeprecationWarning,
+ expected_msg1,
+ scorer, y, y, labels=labels1, **kwargs)
+ if scorer != log_loss:
Add test that with allow_label_subset there is no warning.
—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
<#9585 (review)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AAEz61rqcLK9dEn2dWy2KHliambArEVPks5scxAkgaJpZM4O8Dqt>
.
|
| return 1 | ||
|
|
||
|
|
||
| def DummyScorerWithLabels(y_true, y_pred, labels=None): |
|
|
||
|
|
||
| def DummyScorerWithLabels(y_true, y_pred, labels=None): | ||
| """A dummy scorer function which returns 1 if labels argument was set |
| if classes is None: | ||
| return self._kwargs | ||
|
|
||
| if self._pass_classes in signature(self._score_func).parameters: |
There was a problem hiding this comment.
Hmm... I'm not sure I like this implicit magic. I'd rather have pass_classes=False (better than None) by default, and explicitly change our make_scorer invocations.
On the other hand, perhaps we are protecting users by making pass_classes='labels' by default as it makes make_scorer easier to use. Hmmm... I have to think.
There was a problem hiding this comment.
There is another advantage to have this as a string and not boolean. This will allow users who have different semantics for 'labels' in our API to use this functionality. eg, they might have 'present_classes' as an argument which works same as 'labels'. They can just pass 'present_classes' here and scorer will pass classes to that argument in metric call.
| if self._pass_classes in signature(self._score_func).parameters: | ||
| # if labels passed as kwargs, return kwargs as is | ||
| if self._pass_classes in self._kwargs: | ||
| if classes is not None: |
There was a problem hiding this comment.
the classes is None case returns above
| # labels should be a subset of classes | ||
| if not set(classes).issuperset( | ||
| set(self._kwargs[self._pass_classes])): | ||
| raise ValueError("%s classes=%s is not the " |
There was a problem hiding this comment.
I'm not convinced we should be stopping the user if their explicitly passed labels include more than the training data. That can be a valid, if unfortunate, case for macro-averaging.
We can warn, or we can be silent, but please no error.
There was a problem hiding this comment.
yeah agree. and this check should probably be in the specific metric and not here.
but maybe we can a similar check later when "classes" is added to the init of all estimators. Then if the user explicitly specifies classes, labels should be a subset.
| else: | ||
| kwargs = self._kwargs.copy() | ||
| if target_type == 'multilabel-indicator': | ||
| kwargs[self._pass_classes] = list(range(len(classes))) |
There was a problem hiding this comment.
Hmm. I guess this works for now, but I find it a bit awkward.
|
|
||
| if present_labels_ - labels_: | ||
| if not allow_label_subset: | ||
| warnings.warn("The labels argument %s was a subset of the present " |
There was a problem hiding this comment.
I still don't get why we really want this. In what case does raising an error here help the user? To tell them that they might have done something wrong when they manually entered a set of labels? I think that's a case where making a mistake should return the corresponding bad results. When a user explicitly sets something, they are responsible for it. When they do not, we are responsible for making decent default behaviour; which is what this PR is all about.
For P/R/F and cohen's kappa, we explicitly suggest using labels to limit the set of labels. In such a case why should cross validation reach the scoring phase and then blow up because the user failed to set some verbose "I followed the instructions correctly" flag?
|
So the reason a label subset is a problem is because the training data might have missed some test classes? I think this case should rather be handled by the scorer: if I just can't think how to get deeply nested grid searches to work without the user setting By far the best solution I can think of to this whole madness is to allow |
|
Is this PR stalled? |
|
It certainly doesn't look like it'll be merged soon, @turian! :\ It's possible that this same issue will be solved by SLEP006 which generally deals with how to get parameters to where they're sought. I also see #12385 as part of an alternative solution to the same problem: we should have APIs that construct metrics suitable for a given task, rather than users expecting to use metrics with their default parameters. |
|
This has been superseded by recent work. |
Scorers pass classes from estimators into the labels argument of the metrics.
allow_subset_labels added to all the metrics allowing scoring on a subset of labels.
Issues: #6231 #8100