Skip to content

[WIP] Adding classes argument to Gaussian Naive Bayes - #9290

Open
thismlguy wants to merge 51 commits into
scikit-learn:mainfrom
thismlguy:naive_bayes
Open

thismlguy wants to merge 51 commits into
scikit-learn:mainfrom
thismlguy:naive_bayes

Conversation

@thismlguy

Copy link
Copy Markdown
Contributor

Fixing issue #8100

This PR involves adding a classes argument to the initialization of the gaussian naive bayes estimator. This would make the classes argument of partial_fit redundant as we'll no longer need to specify it every time.

Comment thread sklearn/naive_bayes.py Outdated

# initialize a flag which checks whether fit or partial fit was called
# once or not
self.fit_called = False

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.

using this to check first call to fit in place of _check_partial_fit_first_call. thoughts?

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.

classes_ set during initialization to set it once during the first call or when refit used and not again.

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 sure why you would need this. Also, init shouldn't set any attributes that are not __init__ parameters.

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.

modified

Comment thread sklearn/naive_bayes.py Outdated
initialization. It will be ignored in subsequent calls.

Note: Now this argument is redundant. We should remove this. But
this will affect backward compatibility

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.

is removing classes argument from partial_fit feasible? it will cause the previous code using this argument to give an error. thoughts?

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 we go the route of the PR and add classes to the constructor everywhere, we should deprecate it in partial_fit I think. We certainly wouldn't remove it, because that would break code, as you say. Check out the documentation on deprecation in the developer docs.

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.. my bad, should have checked it in the first place..

Comment thread sklearn/naive_bayes.py Outdated
Returns self.
"""
X, y = check_X_y(X, y)
check_y_classes(y, self.classes_)

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.

added this new function in utils as it'll be useful for all estimators.

Comment thread sklearn/naive_bayes.py Outdated
i = classes.searchsorted(y_i)
for y_i in np.unique(y):
# classes need not be sorted because user input
i = np.where(classes == y_i)[0][0]

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.

the classes need not be sorted anymore because they are user input. so using where in place of searchsorted

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.

huh... we could sort them. not having them sorted might lead to subtle bugs in some places...

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'll sort them but then i'll also make a note in the documentation of this parameter that this will be sorted internally and they should use the classes_ argument to get the final order. works?

Comment thread sklearn/tests/test_naive_bayes.py Outdated
y2 = np.array([1, 1, 2, 2, 3, 3])

# Test not needed if we remove the classes parameter in partial fit
# def test_gnb():

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.

this test is no more required because partial_fit will not have a classes argument. if this works, i'll remove this in next commit. just commented for now.

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.

this test should stay there until the end of the deprecation cycle.

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.

added back with 1 more test in it

assert_raises(ValueError, clf.partial_fit, np.hstack((X, X)), y)


def test_gnb_extra_classes():

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.

new test defined to check if adding new labels at end or started just adds zero-value columns and doesn't change the predictions made earlier.

@thismlguy

Copy link
Copy Markdown
Contributor Author

i've added some comments in the files changed section. please review those as well.

@amueller

amueller commented Jul 6, 2017

Copy link
Copy Markdown
Member

Thanks for posting this. I'll try to check it out tomorrow.

@thismlguy thismlguy changed the title Adding classes argument to Gaussian Naive Bayes [WIP] Adding classes argument to Gaussian Naive Bayes Jul 7, 2017
@amueller

amueller commented Jul 7, 2017

Copy link
Copy Markdown
Member

you need to fix the doctests.
I'm ambivalent about the fact that this is included in get_params and set_params.

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

some comments, rest in meeting ;)

Comment thread sklearn/naive_bayes.py Outdated
"""

def __init__(self, priors=None):
def __init__(self, classes=None, priors=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.

it should go last in case people passed priors as positional 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.

done

Comment thread sklearn/naive_bayes.py Outdated
self.priors = priors

# initialize additional parameter:
self.classes_ = 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.

It's illegal to set trailing underscore attributes in __init__ (and should result in some test failure)

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.

modified

Comment thread sklearn/naive_bayes.py Outdated

# initialize a flag which checks whether fit or partial fit was called
# once or not
self.fit_called = 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'm not sure why you would need this. Also, init shouldn't set any attributes that are not __init__ parameters.

Comment thread sklearn/naive_bayes.py Outdated
"""
# check if classes were defined, set the classes_ attribute every time
if self.classes is not None:
self.classes_ = np.asarray(self.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.

we should check that they are unique, right?

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.

done

Comment thread sklearn/naive_bayes.py Outdated
initialization. It will be ignored in subsequent calls.

Note: Now this argument is redundant. We should remove this. But
this will affect backward compatibility

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 we go the route of the PR and add classes to the constructor everywhere, we should deprecate it in partial_fit I think. We certainly wouldn't remove it, because that would break code, as you say. Check out the documentation on deprecation in the developer docs.

Comment thread sklearn/naive_bayes.py Outdated
i = classes.searchsorted(y_i)
for y_i in np.unique(y):
# classes need not be sorted because user input
i = np.where(classes == y_i)[0][0]

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.

huh... we could sort them. not having them sorted might lead to subtle bugs in some places...

Comment thread sklearn/tests/test_naive_bayes.py Outdated
y2 = np.array([1, 1, 2, 2, 3, 3])

# Test not needed if we remove the classes parameter in partial fit
# def test_gnb():

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.

this test should stay there until the end of the deprecation cycle.

"""Test whether adding extra classes doesn't change the prediction of the
existing classes just adds 0 value columns for new classes"""
clf1 = GaussianNB(classes=[1, 2]).fit(X, y)
pred1 = clf1.predict_proba(X)

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.

check the shapes first on all of these

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.

done

Comment thread sklearn/tests/test_naive_bayes.py Outdated
assert_array_almost_equal(pred1[:, 0], pred3[:, 1])
assert_array_almost_equal(pred1[:, 1], pred2[:, 1])
assert_array_almost_equal(pred1[:, 1], pred3[:, 2])
assert_array_almost_equal(pred2[:, 2], zero_array)

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.

just do 0 for second one.

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.

done

assert_array_almost_equal(pred2[:, 3], zero_array)
assert_array_almost_equal(pred3[:, 0], zero_array)
assert_array_almost_equal(pred3[:, 3], zero_array)

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 test that passing y that's not contained in classes raises 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.

added

Comment thread sklearn/utils/validation.py Outdated
raise ValueError("Negative values in data passed to %s" % whom)


def check_y_classes(y, 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.

add a test for this

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.

make it private

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.

done

Comment thread sklearn/utils/validation.py Outdated

def check_y_classes(y, classes):
"""
Chech if y has a subset of classes as set in the classes 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.

*check

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.

done

@amueller

amueller commented Aug 1, 2017

Copy link
Copy Markdown
Member

cross_val_scorer pick scorers using a function and not a dictionary

That is always an option - though not a function, a scoring callable. And I'm only talking as a workaround until we have the classes in estimators. So if someone really wants to specify labels in cross_val_score because they get an error, then can use make_scorer to get around that.

@thismlguy

thismlguy commented Aug 1, 2017 •

Copy link
Copy Markdown
Contributor Author

That is always an option - though not a function, a scoring callable. And I'm only talking as a workaround until we have the classes in estimators. So if someone really wants to specify labels in cross_val_score because they get an error, then can use make_scorer to get around that.

we could ask the user to do it at their end then. maybe make the error more explicit with link to the documentation on how to resolve it.

@amueller

amueller commented Aug 1, 2017

Copy link
Copy Markdown
Member

That's what I meant

@thismlguy

Copy link
Copy Markdown
Contributor Author

I'm not sure how we can use make_scorer to solve the error in the code cross_val_score(GaussianNB(), iris.data, iris.target, cv=KFold(3)).
This is because we need all the classes while fitting the estimator and labels will be available only while scoring.
For same reason, we require labels to be a subset of classes and not the other way around.

@jnothman

jnothman commented Aug 2, 2017

Copy link
Copy Markdown
Member

I think we're heading the right direction regardless, in that we're annotating the scorer with how the underlying metric should take classes. I think we should take a step back and list the cases that are working poorly ATM and try to think about solving it as a whole:

  • partial_fit (has a current solution, but one that has been a maintenance pitfall)
  • Classes from training missing in test. Would be solved by passing classes_ where metric supports it (as long as there are no classes in test missing from training, which may be less likely since train is usually larger)
  • Classes from cross validation dataset missing from some split's training or both training and test data
  • Classes from outer cross validation missing from some inner cross validation training set

Are there cases I have missed? We need to make sure that our solution fixes all of these, perhaps with the exception of partial_fit, and is the simplest solution to do so

@thismlguy

thismlguy commented Aug 3, 2017 •

Copy link
Copy Markdown
Contributor Author

partial_fit (has a current solution, but one that has been a maintenance pitfall)

I guess we'll be deprecating the classes parameter of partial_fit and force the user to pass same input as that passed while initialization (if passed). what do u mean by it being a maintenance pitfall?

Classes from training missing in test. Would be solved by passing classes_ where metric supports it (as long as there are no classes in test missing from training, which may be less likely since train is usually larger)

yea its less likely but a user might have bad train-test split strategy and if there are many classes, it might be an issue. we can still cater to it with classes parameter and smarter scorers.

Classes from cross validation dataset missing from some split's training or both training and test data
Classes from outer cross validation missing from some inner cross validation training set

i think we can solve both by adding an extra step. before doing cv, we can check if the estimator has classes parameter set, if not, we'll can just copy the estimator into a new one, keeping all parameters same just passing an additional classes argument taking unique from y (not sure if such an estimator clone is currently possible in sklearn).

but again we need the classes parameter added to estimators for all these. i'm not sure how we can do it by just fixing the scorers.

one way I can think of, without having the classes parameter added to all estimators, is if we can somehow create a helper to explicitly set the classes_ attribute of an estimator, which is illegal right now afaik.

@amueller

amueller commented Aug 4, 2017 •

Copy link
Copy Markdown
Member

@jnothman I think you have all cases. We might want to also think about bagging, which do work, but would be easier with this implementation.

@aarshayj whenever we do cross-validation we clone the estimator for each separate fold, so in theory we could inject classes there into the construction. We could also set classes_ or classes without making it a constructor parameter everywhere (though that would be a bit silly, because we would still need to implement all the infrastructure around handling it, and so adding the parameter is the least of our worries).

@amueller

amueller commented Aug 4, 2017

Copy link
Copy Markdown
Member

Btw, also see #1304 for an earlier attempt that we then abandoned but now following through on (maybe).

@amueller

amueller commented Aug 4, 2017

Copy link
Copy Markdown
Member

I think we should not only consider our cross-validation, but also users building their own cross-validation or other ensembling. It would be good to be able to ensure consistent shape of decision_function and predict_proba.

@amueller

amueller commented Aug 4, 2017

Copy link
Copy Markdown
Member

I think I actually like @aarshayj's idea of setting classes in cloning inside the cross-validation loop if it's not set already.

@amueller

amueller commented Aug 4, 2017

Copy link
Copy Markdown
Member

Ok, so in this branch:

cross_val_score(GaussianNB(), iris.data, iris.target, cv=KFold(2), scoring="f1_macro")

array([ 0.21875, 0.25 ])

Here there are two classes in the averaging because len(est.classes_) == 2

cross_val_score(GaussianNB(classes=[0, 1, 2]), iris.data, iris.target, cv=KFold(2), scoring="f1_macro")

array([ 0.14583333, 0.16666667])

The second result is probably the intended one. Without having classes, the careful user could do

f1_classes = make_scorer(f1_score, average="macro", labels=[0, 1, 2])
cross_val_score(GaussianNB(), iris.data, iris.target, cv=KFold(2), scoring=f1_classes)

That give the correct result. It doesn't work in this branch, though (in this branch you should use classes)

@amueller

amueller commented Aug 4, 2017

Copy link
Copy Markdown
Member

I'm a bit confused because master yields

cross_val_score(GaussianNB(), iris.data, iris.target, cv=KFold(2), scoring="f1_macro")

array([ 0.14583333, 0.25 ])

@thismlguy

thismlguy commented Aug 4, 2017 •

Copy link
Copy Markdown
Contributor Author

I'm a bit confused because master yields

cross_val_score(GaussianNB(), iris.data, iris.target, cv=KFold(2), scoring="f1_macro")
array([ 0.14583333, 0.25 ])

This is because f1_score considers labels as the combination of unique values of y_true and y_pred. So in first fold, classes [1,2] went into training and a few 2s were predicted so f1_score had 3 classes. But in second case, [0,1] went into training but all 1s were predicted. so f1_score divided by 2 as it didn't know that 0 existed as a class.

This PR is more consistent. it passes labels from estimator and the average is taken only for the classes present in train. So the result:

cross_val_score(GaussianNB(), iris.data, iris.target, cv=KFold(2), scoring="f1_macro")
array([ 0.21875, 0.25 ])

@amueller

amueller commented Aug 4, 2017

Copy link
Copy Markdown
Member

I propose to add a allow_label_subset=False parameter to all the metrics that have labels and if the labels are a subset, we error (warn during deprecation cycle) unless allow_label_subset=True.

I think computing a metric for a subset of the labels is a relatively rare special case, and we should be strict in validating the input to the metric, unless the user explicitly asks for a subset.

@amueller

amueller commented Aug 4, 2017

Copy link
Copy Markdown
Member

So my plan:

  1. do the proposed fix of passing classes_ as labels in the scorer
  2. error / warn if there's a label that's not in labels unless allow_label_subset=True
  3. Add classes to all Estimators
  4. set classes during cloning in cross-validation unless it was set by the user
  5. possibly make labels required in the metrics.

I think that will cover all use-cases and will make it hard for users to get wrong results. Also it will be relatively automatic.
I think the first PR should be 1 & 2, then 3 & 4 for a second pr.
I'm uncertain about making labels required (5), but I think it will minimize surprise.

@jnothman

jnothman commented Aug 6, 2017

Copy link
Copy Markdown
Member

what do u mean by it being a maintenance pitfall?

I mean that we've had problems with buggy implementations. In part because we've not merged some common tests for partial_fit, but in part just because the design is hard to get right because of its interaction with batch fit.

@amueller

amueller commented Aug 9, 2017

Copy link
Copy Markdown
Member

@jnothman any comments on my plan?

@jnothman

jnothman commented Aug 9, 2017

Copy link
Copy Markdown
Member

Yes, a comment: please make us release 0.19 so that I can feel comfortable thinking about these things!

I'll comment more specifically when I can soon focus on this...

@jnothman

Copy link
Copy Markdown
Member

Some days I wonder who I should blame for this idea of keeping the learning algorithm, its model and the data semantics on the same object... Similarly, I know Gaël wanted to not decorate metrics with the properties that transform them into scorers, but I'm a little worried that annotations like allow_label_subset=True on the scorer but not the metric will be inconvenient to maintain.

At a glance your plan seems reasonable. The need for labels in metrics is exclusive to multiclass (not multilabel-only) metrics; and then there are some where it has no effect, such as accuracy (although it could be used to raise an error perhaps). Other than that, yes, labels should be supported.

Your plan doesn't mention partial_fit.

Your plan also doesn't mention how we do this in terms of estimator checks in a way that doesn't break contrib code!

@thismlguy

Copy link
Copy Markdown
Contributor Author

one way to do it without a new argument like allow_label_subset could be presence of classes parameter in the classifier. If the user passes a subset of classes_ in labels and classes was set at the time of init, we know they want a subset. otherwise, we can enforce that they set the classes parameter as well at the time of init, so that we're sure that they want a subset.

Also, I'm not sure how many people actually use labels in scorer to get scores for only a subset of classes. If I can assume, the people who do really know what they're doing, this might work.

Of course, this would mean we fix both classifiers and scorers in the same version.

@amueller

Copy link
Copy Markdown
Member

I think we should just deprecate classes in partial_fit.
I think we already have labels in (nearly?) all metrics that require them. I would not add them to accuracy or other metrics that are not impacted.

I'm a little worried that annotations like allow_label_subset=True on the scorer but not the metric will be inconvenient to maintain.

I'm not sure I understand your point. The idea was to have allow_label_subsets be an argument to the metric, not the scorer, and the scorers always pass False. That way, if a user really wants to do this, they need to create a scorer with make_scorer an set allow_label_subsets=True.

@aarshayj the problem I saw with your approach was that we might pass classes automagically in cross-validation when we know the true classes, so it's a fragile way to determine it was explicitly set by the user.

@thismlguy

thismlguy commented Aug 14, 2017 •

Copy link
Copy Markdown
Contributor Author

@aarshayj the problem I saw with your approach was that we might pass classes automagically in cross-validation when we know the true classes, so it's a fragile way to determine it was explicitly set by the user.

I think we can overcome this. What I meant was that we should have this check before we clone the estimator and pass classes in cross_val_score. When a call to cross_val_score is made, we have the estimator, scorer and y. so we can check the following:

  • if classes is set in estimator, we're good irrespective of labels.
  • if not, if labels is a subset of whats present in y, then we flag an error (after deprecation) or warning (now) saying that a subset of classes was passed as labels but classes was not set at init.
  • if not, labels has same classes as y and we're good to set them as classes in cloned estimator.

i think the idea is also based on an assumption that people who are using a subset of labels really know what they are doing and we might get away without a hard confirmation from them. sounds fair?

@jnothman

jnothman commented Aug 15, 2017 via email

Copy link
Copy Markdown
Member

@thismlguy

Copy link
Copy Markdown
Contributor Author

I think the above strategy allows both of these scenarios. The classes being fit on are dependent on the labels only though the fact that they have to be a superset. We can fit on as many classes and score on a subset. And we can also have as many scorers as we want, the classes argument will be a union of all the labels and classes in y, if not passed during init.

@amueller

Copy link
Copy Markdown
Member

@aarshayj I don't think I understand your proposal, let's discuss in person.

This branch has not been deployed

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

Labels

API Needs Decision Requires decision

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants