Skip to content

Add pass classes argument to scorers and allow_subset_labels in metrics - #9585

Closed
thismlguy wants to merge 17 commits into
scikit-learn:mainfrom
thismlguy:metrics_pass_classes
Closed

thismlguy wants to merge 17 commits into
scikit-learn:mainfrom
thismlguy:metrics_pass_classes

Conversation

@thismlguy

@thismlguy thismlguy commented Aug 18, 2017 •

Copy link
Copy Markdown
Contributor

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

@amueller

Copy link
Copy Markdown
Member

merge conflict ;)

@thismlguy

thismlguy commented Aug 28, 2017 •

Copy link
Copy Markdown
Contributor Author

merge conflict ;)

it was a small patch, resolved.

@amueller amueller left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Comment thread sklearn/metrics/classification.py Outdated

if present_labels_ - labels_:
if not allow_labels_subset:
warnings.warn("The `allow_labels_subset` argument should be True "

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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."

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

got it!

Comment thread sklearn/metrics/classification.py Outdated

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would maybe say allow_label_subset?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

both sound good to me. i'll change it.

Comment thread sklearn/metrics/classification.py Outdated
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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If not True and labels contains only a subset of the present classes, an error will be raised starting version 0.22.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

got it

Comment thread sklearn/metrics/classification.py Outdated
labels = unique_labels(y_true, y_pred)
labels = present_labels
else:
_check_labels_subset(present_labels, labels, allow_labels_subset)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe I would put the if not allow_label_subset here and not pass as argument.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i did that earlier but it was actually being repeated various times so i thought this might be better

Comment thread sklearn/metrics/scorer.py Outdated
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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

First line needs to be a short summary, see pep 257

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even though it's private it would be good to document parameters.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should be self._pass_classes instead of labels, and "as keyword argument to make_scorer".

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

got it!

Comment thread sklearn/metrics/scorer.py Outdated
# 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"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

got it!

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,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

won't that be covered in the test of metrics as that check happens in metrics?

Comment thread sklearn/metrics/scorer.py Outdated
y_pred = np.vstack([p[:, -1] for p in y_pred]).T

if self._pass_classes is None:
kwargs = self._kwargs

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not covered!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread sklearn/metrics/scorer.py Outdated
y_pred = clf.predict_proba(X)

if self._pass_classes is None:
kwargs = self._kwargs

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not covered!

Comment thread sklearn/metrics/scorer.py
(classes,
self._pass_classes,
self._kwargs['labels']))
return self._kwargs

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not covered!

@thismlguy thismlguy Aug 30, 2017 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

@jnothman

jnothman commented Aug 28, 2017 via email

Copy link
Copy Markdown
Member

return 1


def DummyScorerWithLabels(y_true, y_pred, labels=None):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

def dummy_metric_with_labels



def DummyScorerWithLabels(y_true, y_pred, labels=None):
"""A dummy scorer function which returns 1 if labels argument was set

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

scorer -> metric

Comment thread sklearn/metrics/scorer.py
if classes is None:
return self._kwargs

if self._pass_classes in signature(self._score_func).parameters:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread sklearn/metrics/scorer.py Outdated
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:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the classes is None case returns above

Comment thread sklearn/metrics/scorer.py Outdated
# 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 "

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread sklearn/metrics/scorer.py
else:
kwargs = self._kwargs.copy()
if target_type == 'multilabel-indicator':
kwargs[self._pass_classes] = list(range(len(classes)))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 "

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

@jnothman

jnothman commented Nov 6, 2017 •

Copy link
Copy Markdown
Member

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 pass_classes is active then identifying additional classes in the test data should raise a warning and later an error, telling the user to explicitly set labels. Unfortunately this comes at extra computational cost :(

I just can't think how to get deeply nested grid searches to work without the user setting labels explicitly somewhere, unless we can implement that classes parameter, which we have discovered is very tricky. But telling the user when there is a mismatch between training and test data, in the pass_classes case, would be helpful. But when the user explicitly sets labels, we should just do as they say, not force them to say "yes I meant it" which this PR currently does.

By far the best solution I can think of to this whole madness is to allow y to be a pandas.Categorical series and then strongly recommend that users use this for categorical data. It includes a record of what classes are available, which can be used when labels=None (and may also be used to make a number of things more efficient, such as LabelEncoder and LabelBinarizer). If numpy implements a similar dtype, we can use that too... We could even have a global config on scikit-learn that casts y as a pandas.Series when appropriate to ensure that the full set of classes is known, but this could lead to subtle changes in behaviour and I expect it will face opposition.

Base automatically changed from master to main January 22, 2021 10:49
@turian

turian commented Jul 28, 2021

Copy link
Copy Markdown

Is this PR stalled?

@jnothman

Copy link
Copy Markdown
Member

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.

@adrinjalali

Copy link
Copy Markdown
Member

This has been superseded by recent work.

@adrinjalali adrinjalali closed this Mar 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants