Skip to content

[MRG+1] Pass sample_weight as kwargs in VotingClassifier #9493

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions sklearn/ensemble/tests/test_voting_classifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from sklearn.svm import SVC
from sklearn.multiclass import OneVsRestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.base import BaseEstimator, ClassifierMixin


# Load the iris dataset and randomly permute it
Expand Down Expand Up @@ -274,6 +275,20 @@ def test_sample_weight():
assert_raise_message(ValueError, msg, eclf3.fit, X, y, sample_weight)


def test_sample_weight_kwargs():
"""Check that VotingClassifier passes sample_weight as kwargs"""
class MockClassifier(BaseEstimator, ClassifierMixin):
"""Mock Classifier to check that sample_weight is received as kwargs"""
def fit(self, X, y, *args, **sample_weight):
assert_true('sample_weight' in sample_weight)

clf = MockClassifier()
eclf = VotingClassifier(estimators=[('mock', clf)], voting='soft')

# Should not raise an error.
eclf.fit(X, y, sample_weight=np.ones((len(y),)))


def test_set_params():
"""set_params should be able to set estimators"""
clf1 = LogisticRegression(random_state=123, C=1.0)
Expand Down
6 changes: 3 additions & 3 deletions sklearn/ensemble/voting_classifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@
from ..utils.metaestimators import _BaseComposition


def _parallel_fit_estimator(estimator, X, y, sample_weight):
def _parallel_fit_estimator(estimator, X, y, sample_weight=None):
"""Private function used to fit an estimator within a job."""
if sample_weight is not None:
estimator.fit(X, y, sample_weight)
estimator.fit(X, y, sample_weight=sample_weight)
else:
estimator.fit(X, y)
return estimator
Expand Down Expand Up @@ -185,7 +185,7 @@ def fit(self, X, y, sample_weight=None):

self.estimators_ = Parallel(n_jobs=self.n_jobs)(
delayed(_parallel_fit_estimator)(clone(clf), X, transformed_y,
sample_weight)
sample_weight=sample_weight)
for clf in clfs if clf is not None)

return self
Expand Down