Skip to content

[Proof of concept] Syntactic sugar for pipelines #2589

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

Closed
wants to merge 1 commit into from
Closed
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
12 changes: 11 additions & 1 deletion sklearn/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,13 +262,23 @@ def __repr__(self):
class_name = self.__class__.__name__
return '%s(%s)' % (class_name, _pprint(self.get_params(deep=False),
offset=len(class_name),),)

def __str__(self):
class_name = self.__class__.__name__
return '%s(%s)' % (class_name,
_pprint(self.get_params(deep=True),
offset=len(class_name), printer=str,),)

def __or__(self, estimator):
from sklearn.pipeline import Pipeline
if isinstance(self, Pipeline):
name = estimator.__class__.__name__
steps = self.steps + [(name, estimator)]
else:
name1 = self.__class__.__name__
name2 = estimator.__class__.__name__
steps = [(name1, self), (name2, estimator)]
return Pipeline(steps)


###############################################################################
class ClassifierMixin(object):
Expand Down
20 changes: 20 additions & 0 deletions sklearn/tests/test_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,26 @@ def test_pipeline_methods_preprocessing_svm():
pipe.score(X, y)


def test_pipeline_syntactic_sugar():
iris = load_iris()
X = iris.data
y = iris.target
pipeline = StandardScaler() | PCA(n_components=2) | SVC(random_state=0)
assert_true(isinstance(pipeline, Pipeline))

assert_equal(pipeline.steps[0][0], "StandardScaler")
assert_true(isinstance(pipeline.steps[0][1], StandardScaler))

assert_equal(pipeline.steps[1][0], "PCA")
assert_true(isinstance(pipeline.steps[1][1], PCA))

assert_equal(pipeline.steps[2][0], "SVC")
assert_true(isinstance(pipeline.steps[2][1], SVC))

y_pred = pipeline.fit(X, y).predict(X)
assert_equal(np.mean(y == y_pred), 0.92)


def test_feature_union():
# basic sanity check for feature union
iris = load_iris()
Expand Down