Skip to content
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
31 changes: 25 additions & 6 deletions openml/flows/sklearn_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,10 @@ def flow_to_sklearn(o, components=None, initialize_with_defaults=False):
del components[key]
if step_name is None:
rval = component
else:
elif 'argument_1' not in value:
rval = (step_name, component)
else:
rval = (step_name, component, value['argument_1'])
elif serialized_type == 'cv_object':
rval = _deserialize_cross_validator(value)
else:
Expand Down Expand Up @@ -305,21 +307,36 @@ def _extract_information_from_model(model):

if (isinstance(rval, (list, tuple)) and len(rval) > 0 and
isinstance(rval[0], (list, tuple)) and
[type(rval[0]) == type(rval[i]) for i in range(len(rval))]):
all([isinstance(rval[i], type(rval[0]))
for i in range(len(rval))])):

# Steps in a pipeline or feature union, or base classifiers in voting classifier
# Steps in a pipeline or feature union, or base classifiers in
# voting classifier
parameter_value = list()
reserved_keywords = set(model.get_params(deep=False).keys())

for sub_component_tuple in rval:
identifier, sub_component = sub_component_tuple
identifier = sub_component_tuple[0]
sub_component = sub_component_tuple[1]
sub_component_type = type(sub_component_tuple)
if not 2 <= len(sub_component_tuple) <= 3:
# length 2 is for {VotingClassifier.estimators,
# Pipeline.steps, FeatureUnion.transformer_list}
# length 3 is for ColumnTransformer
msg = 'Length of tuple does not match assumptions'
raise ValueError(msg)
if not isinstance(sub_component, (OpenMLFlow, type(None))):
msg = 'Second item of tuple does not match assumptions. '\
'Expected OpenMLFlow, got %s' % type(sub_component)
raise TypeError(msg)

if identifier in reserved_keywords:
parent_model_name = model.__module__ + "." + \
model.__class__.__name__
raise PyOpenMLError('Found element shadowing official ' + \
'parameter for %s: %s' % (parent_model_name, identifier))
msg = 'Found element shadowing official '\
'parameter for %s: %s' % (parent_model_name,
identifier)
raise PyOpenMLError(msg)

if sub_component is None:
# In a FeatureUnion it is legal to have a None step
Expand All @@ -342,6 +359,8 @@ def _extract_information_from_model(model):
cr_value = OrderedDict()
cr_value['key'] = identifier
cr_value['step_name'] = identifier
if len(sub_component_tuple) == 3:
cr_value['argument_1'] = sub_component_tuple[2]
component_reference['value'] = cr_value
parameter_value.append(component_reference)

Expand Down
11 changes: 8 additions & 3 deletions openml/runs/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -442,11 +442,16 @@ def extract_parameters(_flow, _flow_dict, component_model,
# inside a feature union or pipeline
if not isinstance(_tmp, (list, tuple)):
raise e
for step_name, step in _tmp:
if isinstance(step_name, openml.flows.OpenMLFlow):
for _temp_step in _tmp:

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 we should also add some checks/safeguards that the third argument is not an instance of OpenMLFlow? Meybe this piece of code can be generalized to check all elements in that list?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I added checks for all 3 parts of the tuple

step_name = _temp_step[0]
step = _temp_step[1]
if not isinstance(step_name, str):
raise e
elif not isinstance(step, openml.flows.OpenMLFlow):
if not isinstance(step, openml.flows.OpenMLFlow):
raise e
if len(_temp_step) > 2:
if not isinstance(_temp_step[2], list):
raise e
continue
else:
raise e
Expand Down
89 changes: 73 additions & 16 deletions tests/test_flows/test_sklearn.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,6 @@ def test_serialize_model(self, check_dependencies_mock):

self.assertEqual(check_dependencies_mock.call_count, 1)


@mock.patch('openml.flows.sklearn_converter._check_dependencies')
def test_serialize_model_clustering(self, check_dependencies_mock):
model = sklearn.cluster.KMeans()
Expand Down Expand Up @@ -180,7 +179,6 @@ def test_serialize_model_clustering(self, check_dependencies_mock):

self.assertEqual(check_dependencies_mock.call_count, 1)


def test_serialize_model_with_subcomponent(self):
model = sklearn.ensemble.AdaBoostClassifier(
n_estimators=100, base_estimator=sklearn.tree.DecisionTreeClassifier())
Expand Down Expand Up @@ -228,8 +226,8 @@ def test_serialize_model_with_subcomponent(self):
def test_serialize_pipeline(self):
scaler = sklearn.preprocessing.StandardScaler(with_mean=False)
dummy = sklearn.dummy.DummyClassifier(strategy='prior')
model = sklearn.pipeline.Pipeline(steps=(
('scaler', scaler), ('dummy', dummy)))
model = sklearn.pipeline.Pipeline(steps=[
('scaler', scaler), ('dummy', dummy)])

fixture_name = 'sklearn.pipeline.Pipeline(' \
'scaler=sklearn.preprocessing.data.StandardScaler,' \
Expand Down Expand Up @@ -290,8 +288,8 @@ def test_serialize_pipeline(self):
def test_serialize_pipeline_clustering(self):
scaler = sklearn.preprocessing.StandardScaler(with_mean=False)
km = sklearn.cluster.KMeans()
model = sklearn.pipeline.Pipeline(steps=(
('scaler', scaler), ('clusterer', km)))
model = sklearn.pipeline.Pipeline(steps=[
('scaler', scaler), ('clusterer', km)])

fixture_name = 'sklearn.pipeline.Pipeline(' \
'scaler=sklearn.preprocessing.data.StandardScaler,' \
Expand Down Expand Up @@ -349,12 +347,71 @@ def test_serialize_pipeline_clustering(self):
self.assertEqual(new_model_params, fu_params)
new_model.fit(self.X, self.y)

@unittest.skipIf(LooseVersion(sklearn.__version__) < "0.20",
reason="columntransformer introduction in 0.20.0")
def test_serialize_column_transformer(self):
# temporary local import, dependend on version 0.20
import sklearn.compose
model = sklearn.compose.ColumnTransformer(
transformers=[
('numeric', sklearn.preprocessing.StandardScaler(), [0, 1, 2]),
('nominal', sklearn.preprocessing.OneHotEncoder(
handle_unknown='ignore'), [3, 4, 5])],
remainder='passthrough')
fixture = 'sklearn.compose._column_transformer.ColumnTransformer(' \
'numeric=sklearn.preprocessing.data.StandardScaler,' \
'nominal=sklearn.preprocessing._encoders.OneHotEncoder)'
fixture_description = 'Automatically created scikit-learn flow.'
serialization = sklearn_to_flow(model)
self.assertEqual(serialization.name, fixture)
self.assertEqual(serialization.description, fixture_description)
# del serialization.model
new_model = flow_to_sklearn(serialization)
self.assertEqual(type(new_model), type(model))
self.assertIsNot(new_model, model)
serialization2 = sklearn_to_flow(new_model)
assert_flows_equal(serialization, serialization2)

@unittest.skipIf(LooseVersion(sklearn.__version__) < "0.20",
reason="columntransformer introduction in 0.20.0")
def test_serialize_column_transformer_pipeline(self):
# temporary local import, dependend on version 0.20
import sklearn.compose
inner = sklearn.compose.ColumnTransformer(
transformers=[
('numeric', sklearn.preprocessing.StandardScaler(), [0, 1, 2]),
('nominal', sklearn.preprocessing.OneHotEncoder(
handle_unknown='ignore'), [3, 4, 5])],
remainder='passthrough')
model = sklearn.pipeline.Pipeline(
steps=[('transformer', inner),
('classifier', sklearn.tree.DecisionTreeClassifier())])
fixture_name = \
'sklearn.pipeline.Pipeline('\
'transformer=sklearn.compose._column_transformer.'\
'ColumnTransformer('\
'numeric=sklearn.preprocessing.data.StandardScaler,'\
'nominal=sklearn.preprocessing._encoders.OneHotEncoder),'\
'classifier=sklearn.tree.tree.DecisionTreeClassifier)'

fixture_description = 'Automatically created scikit-learn flow.'
serialization = sklearn_to_flow(model)
self.assertEqual(serialization.name, fixture_name)
self.assertEqual(serialization.description, fixture_description)
# del serialization.model
new_model = flow_to_sklearn(serialization)
self.assertEqual(type(new_model), type(model))
self.assertIsNot(new_model, model)
serialization2 = sklearn_to_flow(new_model)
assert_flows_equal(serialization, serialization2)

def test_serialize_feature_union(self):
ohe_params = {'sparse': False}
if LooseVersion(sklearn.__version__) >= "0.20":
ohe_params['categories'] = 'auto'
ohe = sklearn.preprocessing.OneHotEncoder(**ohe_params)
scaler = sklearn.preprocessing.StandardScaler()

fu = sklearn.pipeline.FeatureUnion(
transformer_list=[('ohe', ohe), ('scaler', scaler)])
serialization = sklearn_to_flow(fu)
Expand Down Expand Up @@ -443,8 +500,8 @@ def test_serialize_complex_flow(self):
scaler = sklearn.preprocessing.StandardScaler(with_mean=False)
boosting = sklearn.ensemble.AdaBoostClassifier(
base_estimator=sklearn.tree.DecisionTreeClassifier())
model = sklearn.pipeline.Pipeline(steps=(
('ohe', ohe), ('scaler', scaler), ('boosting', boosting)))
model = sklearn.pipeline.Pipeline(steps=[
('ohe', ohe), ('scaler', scaler), ('boosting', boosting)])
parameter_grid = {
'n_estimators': [1, 5, 10, 100],
'learning_rate': scipy.stats.uniform(0.01, 0.99),
Expand All @@ -457,13 +514,14 @@ def test_serialize_complex_flow(self):
module_name_encoder = ('_encoders'
if LooseVersion(sklearn.__version__) >= "0.20"
else 'data')
fixture_name = ('sklearn.model_selection._search.RandomizedSearchCV(' \
'estimator=sklearn.pipeline.Pipeline(' \
'ohe=sklearn.preprocessing.{}.OneHotEncoder,' \
'scaler=sklearn.preprocessing.data.StandardScaler,' \
'boosting=sklearn.ensemble.weight_boosting.AdaBoostClassifier(' \
'base_estimator=sklearn.tree.tree.DecisionTreeClassifier)))'
.format(module_name_encoder))
fixture_name = \
('sklearn.model_selection._search.RandomizedSearchCV('
'estimator=sklearn.pipeline.Pipeline('
'ohe=sklearn.preprocessing.{}.OneHotEncoder,'
'scaler=sklearn.preprocessing.data.StandardScaler,'
'boosting=sklearn.ensemble.weight_boosting.AdaBoostClassifier('
'base_estimator=sklearn.tree.tree.DecisionTreeClassifier)))'.
format(module_name_encoder))
self.assertEqual(serialized.name, fixture_name)

# now do deserialization
Expand Down Expand Up @@ -711,7 +769,6 @@ def test_illegal_parameter_names_pipeline(self):
]
self.assertRaises(ValueError, sklearn.pipeline.Pipeline, steps=steps)


def test_illegal_parameter_names_featureunion(self):
# illegal name: transformer_list
transformer_list = [
Expand Down
18 changes: 17 additions & 1 deletion tests/test_runs/test_run_functions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import arff
import collections
from distutils.version import LooseVersion
import json
import os
import random
Expand All @@ -12,6 +13,7 @@
import openml.exceptions
import openml._api_calls
import sklearn
import unittest

from openml.testing import TestBase
from openml.runs.functions import _run_task_get_arffcontent, \
Expand Down Expand Up @@ -354,6 +356,21 @@ def test_run_and_upload_pipeline_dummy_pipeline(self):
('dummy', DummyClassifier(strategy='prior'))])
self._run_and_upload(pipeline1, '62501')

@unittest.skipIf(LooseVersion(sklearn.__version__) < "0.20",
reason="columntransformer introduction in 0.20.0")
def test_run_and_upload_column_transformer_pipeline(self):
import sklearn.compose
inner = sklearn.compose.ColumnTransformer(
transformers=[
('numeric', sklearn.preprocessing.StandardScaler(), [0, 1, 2]),
('nominal', sklearn.preprocessing.OneHotEncoder(
handle_unknown='ignore'), [3, 4, 5])],
remainder='passthrough')
pipeline = sklearn.pipeline.Pipeline(
steps=[('transformer', inner),
('classifier', sklearn.tree.DecisionTreeClassifier())])
self._run_and_upload(pipeline, '62501')

def test_run_and_upload_decision_tree_pipeline(self):
pipeline2 = Pipeline(steps=[('Imputer', Imputer(strategy='median')),
('VarianceThreshold', VarianceThreshold()),
Expand Down Expand Up @@ -390,7 +407,6 @@ def test_run_and_upload_maskedarrays(self):
# This testcase is important for 2 reasons:
# 1) it verifies the correct handling of masked arrays (not all parameters are active)
# 2) it verifies the correct handling of a 2-layered grid search
# Note that this is a list of dictionaries, all containing 1 hyperparameter.
gridsearch = GridSearchCV(
RandomForestClassifier(n_estimators=5),
[
Expand Down