diff --git a/openml/flows/sklearn_converter.py b/openml/flows/sklearn_converter.py index e3f22a9312..82b5895fa1 100644 --- a/openml/flows/sklearn_converter.py +++ b/openml/flows/sklearn_converter.py @@ -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: @@ -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 @@ -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) diff --git a/openml/runs/run.py b/openml/runs/run.py index 83d12e655b..9966d80e7b 100644 --- a/openml/runs/run.py +++ b/openml/runs/run.py @@ -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: + 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 diff --git a/tests/test_flows/test_sklearn.py b/tests/test_flows/test_sklearn.py index d08f63ff00..b4cf524b7e 100644 --- a/tests/test_flows/test_sklearn.py +++ b/tests/test_flows/test_sklearn.py @@ -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() @@ -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()) @@ -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,' \ @@ -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,' \ @@ -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) @@ -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), @@ -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 @@ -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 = [ diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index 1521463b13..8a5138b22a 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -1,5 +1,6 @@ import arff import collections +from distutils.version import LooseVersion import json import os import random @@ -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, \ @@ -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()), @@ -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), [