From 689e63c1616288d5537924131b8bfba99d30b3c3 Mon Sep 17 00:00:00 2001 From: Guillaume Lemaitre Date: Mon, 17 Sep 2018 17:08:55 +0200 Subject: [PATCH 1/8] MAINT: compatibility sklearn 0.20 --- openml/config.py | 2 +- openml/flows/sklearn_converter.py | 7 +- tests/test_flows/test_flow.py | 47 ++--- tests/test_flows/test_sklearn.py | 285 +++++++++++++++++------------- 4 files changed, 192 insertions(+), 149 deletions(-) diff --git a/openml/config.py b/openml/config.py index cb79da6539..7670a622cc 100644 --- a/openml/config.py +++ b/openml/config.py @@ -80,7 +80,7 @@ def _parse_config(): for line in fh: config_file_.write(line) config_file_.seek(0) - config.readfp(config_file_) + config.read_file(config_file_) except OSError as e: logging.info("Error opening file %s: %s", config_file, e.message) return config diff --git a/openml/flows/sklearn_converter.py b/openml/flows/sklearn_converter.py index c68d4cd2e4..ea270b466b 100644 --- a/openml/flows/sklearn_converter.py +++ b/openml/flows/sklearn_converter.py @@ -633,10 +633,10 @@ def check(param_dict, disallow_parameter=False): for param, value in param_dict.items(): # n_jobs is scikitlearn parameter for paralizing jobs if param.split('__')[-1] == 'n_jobs': - # 0 = illegal value (?), 1 = use one core, n = use n cores + # 0 = illegal value (?), 1/None = use one core, n = use n cores # -1 = use all available cores -> this makes it hard to # measure runtime in a fair way - if value != 1 or disallow_parameter: + if value not in (1, None) or disallow_parameter: return False return True @@ -644,7 +644,8 @@ def check(param_dict, disallow_parameter=False): isinstance(model, sklearn.model_selection._search.BaseSearchCV)): raise ValueError('model should be BaseEstimator or BaseSearchCV') - # make sure that n_jobs is not in the parameter grid of optimization procedure + # make sure that n_jobs is not in the parameter grid of optimization + # procedure if isinstance(model, sklearn.model_selection._search.BaseSearchCV): param_distributions = None if isinstance(model, sklearn.model_selection.GridSearchCV): diff --git a/tests/test_flows/test_flow.py b/tests/test_flows/test_flow.py index 54e3f28b1c..0d2fbb3707 100644 --- a/tests/test_flows/test_flow.py +++ b/tests/test_flows/test_flow.py @@ -4,6 +4,7 @@ import re import sys import time +from distutils.version import LooseVersion if sys.version_info[0] >= 3: from unittest import mock @@ -22,6 +23,12 @@ import sklearn.preprocessing import sklearn.naive_bayes import sklearn.tree + +if LooseVersion(sklearn.__version__) < "0.20": + from sklearn.preprocessing import Imputer +else: + from sklearn.impute import SimpleImputer as Imputer + import xmltodict from openml.testing import TestBase @@ -142,7 +149,7 @@ def test_publish_existing_flow(self): flow = openml.flows.sklearn_to_flow(clf) flow, _ = self._add_sentinel_to_flow_name(flow, None) flow.publish() - self.assertRaisesRegexp(openml.exceptions.OpenMLServerException, + self.assertRaisesRegex(openml.exceptions.OpenMLServerException, 'flow already exists', flow.publish) def test_publish_flow_with_similar_components(self): @@ -230,8 +237,8 @@ def test_publish_error(self, api_call_mock, get_flow_mock): def test_illegal_flow(self): # should throw error as it contains two imputers - illegal = sklearn.pipeline.Pipeline(steps=[('imputer1', sklearn.preprocessing.Imputer()), - ('imputer2', sklearn.preprocessing.Imputer()), + illegal = sklearn.pipeline.Pipeline(steps=[('imputer1', Imputer()), + ('imputer2', Imputer()), ('classif', sklearn.tree.DecisionTreeClassifier())]) self.assertRaises(ValueError, openml.flows.sklearn_to_flow, illegal) @@ -256,9 +263,11 @@ def test_existing_flow_exists(self): # create a flow nb = sklearn.naive_bayes.GaussianNB() - steps = [('imputation', sklearn.preprocessing.Imputer(strategy='median')), - ('hotencoding', sklearn.preprocessing.OneHotEncoder(sparse=False, - handle_unknown='ignore')), + ohe_params = {'sparse': False, 'handle_unknown': 'ignore'} + if LooseVersion(sklearn.__version__) >= '0.20': + ohe_params['categories'] = 'auto' + steps = [('imputation', Imputer(strategy='median')), + ('hotencoding', sklearn.preprocessing.OneHotEncoder(**ohe_params)), ('variencethreshold', sklearn.feature_selection.VarianceThreshold()), ('classifier', sklearn.tree.DecisionTreeClassifier())] complicated = sklearn.pipeline.Pipeline(steps=steps) @@ -274,7 +283,7 @@ def test_existing_flow_exists(self): # check if flow exists can find it flow = openml.flows.get_flow(flow.flow_id) downloaded_flow_id = openml.flows.flow_exists(flow.name, flow.external_version) - self.assertEquals(downloaded_flow_id, flow.flow_id) + self.assertEqual(downloaded_flow_id, flow.flow_id) def test_sklearn_to_upload_to_flow(self): iris = sklearn.datasets.load_iris() @@ -282,8 +291,10 @@ def test_sklearn_to_upload_to_flow(self): y = iris.target # Test a more complicated flow - ohe = sklearn.preprocessing.OneHotEncoder(categorical_features=[1], - handle_unknown='ignore') + ohe_params = {'handle_unknown': 'ignore'} + if LooseVersion(sklearn.__version__) >= "0.20": + ohe_params['categories'] = 'auto' + ohe = sklearn.preprocessing.OneHotEncoder(**ohe_params) scaler = sklearn.preprocessing.StandardScaler(with_mean=False) pca = sklearn.decomposition.TruncatedSVD() fs = sklearn.feature_selection.SelectPercentile( @@ -338,18 +349,12 @@ def test_sklearn_to_upload_to_flow(self): openml.flows.functions.assert_flows_equal(new_flow, flow) self.assertIsNot(new_flow, flow) - fixture_name = '%ssklearn.model_selection._search.RandomizedSearchCV(' \ - 'estimator=sklearn.pipeline.Pipeline(' \ - 'ohe=sklearn.preprocessing.data.OneHotEncoder,' \ - 'scaler=sklearn.preprocessing.data.StandardScaler,' \ - 'fu=sklearn.pipeline.FeatureUnion(' \ - 'pca=sklearn.decomposition.truncated_svd.TruncatedSVD,' \ - 'fs=sklearn.feature_selection.univariate_selection.SelectPercentile),' \ - 'boosting=sklearn.ensemble.weight_boosting.AdaBoostClassifier(' \ - 'base_estimator=sklearn.tree.tree.DecisionTreeClassifier)))' \ - % sentinel - - self.assertEqual(new_flow.name, fixture_name) + estimators_names = (sentinel, 'RandomizedSearchCV', 'Pipeline', + 'OneHotEncoder', 'StandardScaler', 'FeatureUnion', + 'TruncatedSVD', 'SelectPercentile', + 'AdaBoostClassifier', 'DecisionTreeClassifier') + for keyword in estimators_names: + self.assertTrue(keyword in new_flow.name) new_flow.model.fit(X, y) def test_extract_tags(self): diff --git a/tests/test_flows/test_sklearn.py b/tests/test_flows/test_sklearn.py index 33454b24ad..e57b6cac08 100644 --- a/tests/test_flows/test_sklearn.py +++ b/tests/test_flows/test_sklearn.py @@ -1,9 +1,9 @@ -from collections import OrderedDict import json import os import sys import unittest -import warnings +from distutils.version import LooseVersion +from collections import OrderedDict if sys.version_info[0] >= 3: from unittest import mock @@ -27,6 +27,11 @@ import sklearn.tree import sklearn.cluster +if LooseVersion(sklearn.__version__) < "0.20": + from sklearn.preprocessing import Imputer +else: + from sklearn.impute import SimpleImputer as Imputer + import openml from openml.flows import OpenMLFlow, sklearn_to_flow, flow_to_sklearn from openml.flows.functions import assert_flows_equal @@ -54,7 +59,7 @@ def fit(self, X, y): class TestSklearn(unittest.TestCase): # Splitting not helpful, these test's don't rely on the server and take less # than 1 seconds - + def setUp(self): iris = sklearn.datasets.load_iris() self.X = iris.data @@ -70,19 +75,37 @@ def test_serialize_model(self, check_dependencies_mock): fixture_description = 'Automatically created scikit-learn flow.' version_fixture = 'sklearn==%s\nnumpy>=1.6.1\nscipy>=0.9' \ % sklearn.__version__ - fixture_parameters = \ - OrderedDict((('class_weight', 'null'), - ('criterion', '"entropy"'), - ('max_depth', 'null'), - ('max_features', '"auto"'), - ('max_leaf_nodes', '2000'), - ('min_impurity_split', '1e-07'), - ('min_samples_leaf', '1'), - ('min_samples_split', '2'), - ('min_weight_fraction_leaf', '0.0'), - ('presort', 'false'), - ('random_state', 'null'), - ('splitter', '"best"'))) + # min_impurity_decrease has been introduced in 0.20 + # min_impurity_split has been deprecated in 0.20 + if LooseVersion(sklearn.__version__) < "0.20": + fixture_parameters = \ + OrderedDict((('class_weight', 'null'), + ('criterion', '"entropy"'), + ('max_depth', 'null'), + ('max_features', '"auto"'), + ('max_leaf_nodes', '2000'), + ('min_impurity_split', '1e-07'), + ('min_samples_leaf', '1'), + ('min_samples_split', '2'), + ('min_weight_fraction_leaf', '0.0'), + ('presort', 'false'), + ('random_state', 'null'), + ('splitter', '"best"'))) + else: + fixture_parameters = \ + OrderedDict((('class_weight', 'null'), + ('criterion', '"entropy"'), + ('max_depth', 'null'), + ('max_features', '"auto"'), + ('max_leaf_nodes', '2000'), + ('min_impurity_decrease', '0.0'), + ('min_impurity_split', 'null'), + ('min_samples_leaf', '1'), + ('min_samples_split', '2'), + ('min_weight_fraction_leaf', '0.0'), + ('presort', 'false'), + ('random_state', 'null'), + ('splitter', '"best"'))) serialization = sklearn_to_flow(model) @@ -111,18 +134,33 @@ def test_serialize_model_clustering(self, check_dependencies_mock): fixture_description = 'Automatically created scikit-learn flow.' version_fixture = 'sklearn==%s\nnumpy>=1.6.1\nscipy>=0.9' \ % sklearn.__version__ - fixture_parameters = \ - OrderedDict((('algorithm', '"auto"'), - ('copy_x', 'true'), - ('init', '"k-means++"'), - ('max_iter', '300'), - ('n_clusters', '8'), - ('n_init', '10'), - ('n_jobs', '1'), - ('precompute_distances', '"auto"'), - ('random_state', 'null'), - ('tol', '0.0001'), - ('verbose', '0'))) + # n_jobs default has changed to None in 0.20 + if LooseVersion(sklearn.__version__) < "0.20": + fixture_parameters = \ + OrderedDict((('algorithm', '"auto"'), + ('copy_x', 'true'), + ('init', '"k-means++"'), + ('max_iter', '300'), + ('n_clusters', '8'), + ('n_init', '10'), + ('n_jobs', '1'), + ('precompute_distances', '"auto"'), + ('random_state', 'null'), + ('tol', '0.0001'), + ('verbose', '0'))) + else: + fixture_parameters = \ + OrderedDict((('algorithm', '"auto"'), + ('copy_x', 'true'), + ('init', '"k-means++"'), + ('max_iter', '300'), + ('n_clusters', '8'), + ('n_init', '10'), + ('n_jobs', 'null'), + ('precompute_distances', '"auto"'), + ('random_state', 'null'), + ('tol', '0.0001'), + ('verbose', '0'))) serialization = sklearn_to_flow(model) @@ -198,7 +236,7 @@ def test_serialize_pipeline(self): 'dummy=sklearn.dummy.DummyClassifier)' fixture_description = 'Automatically created scikit-learn flow.' - serialization = sklearn_to_flow(model) + serialization = sklearn_to_flow(model) self.assertEqual(serialization.name, fixture_name) self.assertEqual(serialization.description, fixture_description) @@ -206,7 +244,11 @@ def test_serialize_pipeline(self): # Comparing the pipeline # The parameters only have the name of base objects(not the whole flow) # as value - self.assertEqual(len(serialization.parameters), 1) + # memory parameter has been added in 0.19 + if LooseVersion(sklearn.__version__) < "0.19.0": + self.assertEqual(len(serialization.parameters), 1) + else: + self.assertEqual(len(serialization.parameters), 2) # Hard to compare two representations of a dict due to possibly # different sorting. Making a json makes it easier self.assertEqual(json.loads(serialization.parameters['steps']), @@ -264,7 +306,11 @@ def test_serialize_pipeline_clustering(self): # Comparing the pipeline # The parameters only have the name of base objects(not the whole flow) # as value - self.assertEqual(len(serialization.parameters), 1) + # memory parameter has been added in 0.19 + if LooseVersion(sklearn.__version__) < "0.19.0": + self.assertEqual(len(serialization.parameters), 1) + else: + self.assertEqual(len(serialization.parameters), 2) # Hard to compare two representations of a dict due to possibly # different sorting. Making a json makes it easier self.assertEqual(json.loads(serialization.parameters['steps']), @@ -304,15 +350,17 @@ def test_serialize_pipeline_clustering(self): new_model.fit(self.X, self.y) def test_serialize_feature_union(self): - ohe = sklearn.preprocessing.OneHotEncoder(sparse=False) + 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) - self.assertEqual(serialization.name, - 'sklearn.pipeline.FeatureUnion(' - 'ohe=sklearn.preprocessing.data.OneHotEncoder,' - 'scaler=sklearn.preprocessing.data.StandardScaler)') + fu = sklearn.pipeline.FeatureUnion( + transformer_list=[('ohe', ohe), ('scaler', scaler)]) + serialization = sklearn_to_flow(fu) + estimators_names = ('FeatureUnion', 'OneHotEncoder', 'StandardScaler') + for keyword in estimators_names: + self.assertTrue(keyword in serialization.name) new_model = flow_to_sklearn(serialization) self.assertEqual(type(new_model), type(fu)) @@ -328,8 +376,10 @@ def test_serialize_feature_union(self): self.assertEqual([step[0] for step in new_model.transformer_list], [step[0] for step in fu.transformer_list]) - self.assertIsNot(new_model.transformer_list[0][1], fu.transformer_list[0][1]) - self.assertIsNot(new_model.transformer_list[1][1], fu.transformer_list[1][1]) + self.assertIsNot(new_model.transformer_list[0][1], + fu.transformer_list[0][1]) + self.assertIsNot(new_model.transformer_list[1][1], + fu.transformer_list[1][1]) new_model_params = new_model.get_params() del new_model_params['ohe'] @@ -345,31 +395,29 @@ def test_serialize_feature_union(self): fu.set_params(scaler=None) serialization = sklearn_to_flow(fu) - self.assertEqual(serialization.name, - 'sklearn.pipeline.FeatureUnion(' - 'ohe=sklearn.preprocessing.data.OneHotEncoder)') + estimators_names = ('FeatureUnion', 'OneHotEncoder') + for keyword in estimators_names: + self.assertTrue(keyword in estimators_names) new_model = flow_to_sklearn(serialization) self.assertEqual(type(new_model), type(fu)) self.assertIsNot(new_model, fu) self.assertIs(new_model.transformer_list[1][1], None) def test_serialize_feature_union_switched_names(self): - ohe = sklearn.preprocessing.OneHotEncoder() + ohe_params = ({'categories': 'auto'} + if LooseVersion(sklearn.__version__) >= "0.20" else {}) + ohe = sklearn.preprocessing.OneHotEncoder(**ohe_params) scaler = sklearn.preprocessing.StandardScaler() - fu1 = sklearn.pipeline.FeatureUnion(transformer_list=[('ohe', ohe), ('scaler', scaler)]) - fu2 = sklearn.pipeline.FeatureUnion(transformer_list=[('scaler', ohe), ('ohe', scaler)]) + fu1 = sklearn.pipeline.FeatureUnion( + transformer_list=[('ohe', ohe), ('scaler', scaler)]) + fu2 = sklearn.pipeline.FeatureUnion( + transformer_list=[('scaler', ohe), ('ohe', scaler)]) fu1_serialization = sklearn_to_flow(fu1) fu2_serialization = sklearn_to_flow(fu2) - self.assertEqual( - fu1_serialization.name, - "sklearn.pipeline.FeatureUnion(" - "ohe=sklearn.preprocessing.data.OneHotEncoder," - "scaler=sklearn.preprocessing.data.StandardScaler)") - self.assertEqual( - fu2_serialization.name, - "sklearn.pipeline.FeatureUnion(" - "scaler=sklearn.preprocessing.data.OneHotEncoder," - "ohe=sklearn.preprocessing.data.StandardScaler)") + estimators_names = ('FeatureUnion', 'OneHotEncoder', 'StandardScaler') + for keyword in estimators_names: + self.assertTrue(keyword in fu1_serialization.name) + self.assertTrue(keyword in fu2_serialization.name) def test_serialize_complex_flow(self): ohe = sklearn.preprocessing.OneHotEncoder(categorical_features=[0]) @@ -378,22 +426,21 @@ def test_serialize_complex_flow(self): base_estimator=sklearn.tree.DecisionTreeClassifier()) 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), - 'base_estimator__max_depth': scipy.stats.randint(1, - 10)} + parameter_grid = { + 'n_estimators': [1, 5, 10, 100], + 'learning_rate': scipy.stats.uniform(0.01, 0.99), + 'base_estimator__max_depth': scipy.stats.randint(1, 10)} cv = sklearn.model_selection.StratifiedKFold(n_splits=5, shuffle=True) rs = sklearn.model_selection.RandomizedSearchCV( estimator=model, param_distributions=parameter_grid, cv=cv) serialized = sklearn_to_flow(rs) - fixture_name = 'sklearn.model_selection._search.RandomizedSearchCV(' \ - 'estimator=sklearn.pipeline.Pipeline(' \ - 'ohe=sklearn.preprocessing.data.OneHotEncoder,' \ - 'scaler=sklearn.preprocessing.data.StandardScaler,' \ - 'boosting=sklearn.ensemble.weight_boosting.AdaBoostClassifier(' \ - 'base_estimator=sklearn.tree.tree.DecisionTreeClassifier)))' - self.assertEqual(serialized.name, fixture_name) + # check that the name of the estimator occur in the name of the flow + estimator_names = ('RandomizedSearchCV', 'Pipeline', 'OneHotEncoder', + 'StandardScaler', 'AdaBoostClassifier', + 'DecisionTreeClassifier') + for keyword in estimator_names: + self.assertTrue(keyword in serialized.name) # now do deserialization deserialized = flow_to_sklearn(serialized) @@ -561,9 +608,9 @@ def test_gaussian_process(self): kernel = sklearn.gaussian_process.kernels.Matern() gp = sklearn.gaussian_process.GaussianProcessClassifier( kernel=kernel, optimizer=opt) - self.assertRaisesRegexp(TypeError, "Matern\(length_scale=1, nu=1.5\), " - "", - sklearn_to_flow, gp) + self.assertRaisesRegex(TypeError, "Matern\(length_scale=1, nu=1.5\), " + "", + sklearn_to_flow, gp) def test_error_on_adding_component_multiple_times_to_flow(self): # this function implicitly checks @@ -571,46 +618,21 @@ def test_error_on_adding_component_multiple_times_to_flow(self): pca = sklearn.decomposition.PCA() pca2 = sklearn.decomposition.PCA() pipeline = sklearn.pipeline.Pipeline((('pca1', pca), ('pca2', pca2))) - fixture = "Found a second occurence of component sklearn.decomposition.pca.PCA" \ - " when trying to serialize Pipeline\(steps=\(\('pca1', " \ - "PCA\(copy=True, iterated_power='auto', n_components=None, " \ - "random_state=None,\n" \ - " svd_solver='auto', tol=0.0, whiten=False\)\), " \ - "\('pca2', PCA\(copy=True, iterated_power='auto', " \ - "n_components=None, random_state=None,\n" \ - " svd_solver='auto', tol=0.0, whiten=False\)\)\)\)." - self.assertRaisesRegexp(ValueError, fixture, sklearn_to_flow, pipeline) + fixture = "Found a second occurence of component .*.PCA when trying " \ + "to serialize Pipeline" + self.assertRaisesRegex(ValueError, fixture, sklearn_to_flow, pipeline) fu = sklearn.pipeline.FeatureUnion((('pca1', pca), ('pca2', pca2))) - fixture = "Found a second occurence of component sklearn.decomposition.pca.PCA when trying to serialize " \ - "FeatureUnion\(n_jobs=1,\n" \ - " transformer_list=\(\('pca1', PCA\(copy=True, " \ - "iterated_power='auto'," \ - " n_components=None, random_state=None,\n" \ - " svd_solver='auto', tol=0.0, whiten=False\)\), \('pca2', " \ - "PCA\(copy=True, iterated_power='auto'," \ - " n_components=None, random_state=None,\n" \ - " svd_solver='auto', tol=0.0, whiten=False\)\)\),\n" \ - " transformer_weights=None\)." - self.assertRaisesRegexp(ValueError, fixture, sklearn_to_flow, fu) + fixture = "Found a second occurence of component .*.PCA when trying " \ + "to serialize FeatureUnion" + self.assertRaisesRegex(ValueError, fixture, sklearn_to_flow, fu) fs = sklearn.feature_selection.SelectKBest() fu2 = sklearn.pipeline.FeatureUnion((('pca1', pca), ('fs', fs))) pipeline2 = sklearn.pipeline.Pipeline((('fu', fu2), ('pca2', pca2))) - fixture = "Found a second occurence of component " \ - "sklearn.decomposition.pca.PCA when trying to serialize " \ - "Pipeline\(steps=\(\('fu', FeatureUnion\(n_jobs=1,\n" \ - " transformer_list=\(\('pca1', PCA\(copy=True, " \ - "iterated_power='auto'," \ - " n_components=None, random_state=None,\n" \ - " svd_solver='auto', tol=0.0, whiten=False\)\), " \ - "\('fs', SelectKBest\(k=10, score_func=\)\)\),\n" \ - " transformer_weights=None\)\), \('pca2', " \ - "PCA\(copy=True, iterated_power='auto'," \ - " n_components=None, random_state=None,\n" \ - " svd_solver='auto', tol=0.0, whiten=False\)\)\)\)." - self.assertRaisesRegexp(ValueError, fixture, sklearn_to_flow, pipeline2) + fixture = "Found a second occurence of component .*.PCA when trying " \ + "to serialize Pipeline" + self.assertRaisesRegex(ValueError, fixture, sklearn_to_flow, pipeline2) def test_subflow_version_propagated(self): this_directory = os.path.dirname(os.path.abspath(__file__)) @@ -652,9 +674,12 @@ def test_illegal_parameter_names(self): def test_illegal_parameter_names_pipeline(self): # illegal name: steps steps = [ - ('Imputer', sklearn.preprocessing.Imputer(strategy='median')), - ('OneHotEncoder', sklearn.preprocessing.OneHotEncoder(sparse=False, handle_unknown='ignore')), - ('steps', sklearn.ensemble.BaggingClassifier(base_estimator=sklearn.tree.DecisionTreeClassifier)) + ('Imputer', Imputer(strategy='median')), + ('OneHotEncoder', + sklearn.preprocessing.OneHotEncoder(sparse=False, + handle_unknown='ignore')), + ('steps', sklearn.ensemble.BaggingClassifier( + base_estimator=sklearn.tree.DecisionTreeClassifier)) ] self.assertRaises(ValueError, sklearn.pipeline.Pipeline, steps=steps) @@ -662,18 +687,23 @@ def test_illegal_parameter_names_pipeline(self): def test_illegal_parameter_names_featureunion(self): # illegal name: transformer_list transformer_list = [ - ('transformer_list', sklearn.preprocessing.Imputer(strategy='median')), - ('OneHotEncoder', sklearn.preprocessing.OneHotEncoder(sparse=False, handle_unknown='ignore')) + ('transformer_list', + Imputer(strategy='median')), + ('OneHotEncoder', + sklearn.preprocessing.OneHotEncoder(sparse=False, + handle_unknown='ignore')) ] - self.assertRaises(ValueError, sklearn.pipeline.FeatureUnion, transformer_list=transformer_list) + self.assertRaises(ValueError, sklearn.pipeline.FeatureUnion, + transformer_list=transformer_list) def test_paralizable_check(self): - # using this model should pass the test (if param distribution is legal) + # using this model should pass the test (if param distribution is + # legal) singlecore_bagging = sklearn.ensemble.BaggingClassifier() # using this model should return false (if param distribution is legal) multicore_bagging = sklearn.ensemble.BaggingClassifier(n_jobs=5) # using this param distribution should raise an exception - illegal_param_dist = {"base__n_jobs": [-1, 0, 1] } + illegal_param_dist = {"base__n_jobs": [-1, 0, 1]} # using this param distribution should not raise an exception legal_param_dist = {"base__max_depth": [2, 3, 4]} @@ -681,24 +711,31 @@ def test_paralizable_check(self): sklearn.ensemble.RandomForestClassifier(), sklearn.ensemble.RandomForestClassifier(n_jobs=5), sklearn.ensemble.RandomForestClassifier(n_jobs=-1), - sklearn.pipeline.Pipeline(steps=[('bag', sklearn.ensemble.BaggingClassifier(n_jobs=1))]), - sklearn.pipeline.Pipeline(steps=[('bag', sklearn.ensemble.BaggingClassifier(n_jobs=5))]), - sklearn.pipeline.Pipeline(steps=[('bag', sklearn.ensemble.BaggingClassifier(n_jobs=-1))]), - sklearn.model_selection.GridSearchCV(singlecore_bagging, legal_param_dist), - sklearn.model_selection.GridSearchCV(multicore_bagging, legal_param_dist) + sklearn.pipeline.Pipeline( + steps=[('bag', sklearn.ensemble.BaggingClassifier(n_jobs=1))]), + sklearn.pipeline.Pipeline( + steps=[('bag', sklearn.ensemble.BaggingClassifier(n_jobs=5))]), + sklearn.pipeline.Pipeline( + steps=[('bag', sklearn.ensemble.BaggingClassifier(n_jobs=-1))]), + sklearn.model_selection.GridSearchCV(singlecore_bagging, + legal_param_dist), + sklearn.model_selection.GridSearchCV(multicore_bagging, + legal_param_dist) ] illegal_models = [ - sklearn.model_selection.GridSearchCV(singlecore_bagging, illegal_param_dist), - sklearn.model_selection.GridSearchCV(multicore_bagging, illegal_param_dist) + sklearn.model_selection.GridSearchCV(singlecore_bagging, + illegal_param_dist), + sklearn.model_selection.GridSearchCV(multicore_bagging, + illegal_param_dist) ] answers = [True, False, False, True, False, False, True, False] - for i in range(len(legal_models)): - self.assertTrue(_check_n_jobs(legal_models[i]) == answers[i]) + for model, expected_answer in zip(legal_models, answers): + self.assertTrue(_check_n_jobs(model) == expected_answer) - for i in range(len(illegal_models)): - self.assertRaises(PyOpenMLError, _check_n_jobs, illegal_models[i]) + for model in illegal_models: + self.assertRaises(PyOpenMLError, _check_n_jobs, model) def test__get_fn_arguments_with_defaults(self): fns = [ From 907fac4bc6f35f77f81a19e5d261b6ddf88fc6d1 Mon Sep 17 00:00:00 2001 From: Guillaume Lemaitre Date: Mon, 17 Sep 2018 17:20:07 +0200 Subject: [PATCH 2/8] uiter --- openml/config.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openml/config.py b/openml/config.py index 7670a622cc..cb79da6539 100644 --- a/openml/config.py +++ b/openml/config.py @@ -80,7 +80,7 @@ def _parse_config(): for line in fh: config_file_.write(line) config_file_.seek(0) - config.read_file(config_file_) + config.readfp(config_file_) except OSError as e: logging.info("Error opening file %s: %s", config_file, e.message) return config From b75217831663f2c3304f0e263bace1171d20f8a4 Mon Sep 17 00:00:00 2001 From: Guillaume Lemaitre Date: Mon, 17 Sep 2018 17:38:09 +0200 Subject: [PATCH 3/8] iter --- tests/test_flows/test_sklearn.py | 86 ++++++++++++++++++++------------ 1 file changed, 54 insertions(+), 32 deletions(-) diff --git a/tests/test_flows/test_sklearn.py b/tests/test_flows/test_sklearn.py index e57b6cac08..898f1a116f 100644 --- a/tests/test_flows/test_sklearn.py +++ b/tests/test_flows/test_sklearn.py @@ -636,7 +636,8 @@ def test_error_on_adding_component_multiple_times_to_flow(self): def test_subflow_version_propagated(self): this_directory = os.path.dirname(os.path.abspath(__file__)) - tests_directory = os.path.abspath(os.path.join(this_directory, '..', '..')) + tests_directory = os.path.abspath(os.path.join(this_directory, + '..', '..')) sys.path.append(tests_directory) import tests.test_flows.dummy_learn.dummy_forest pca = sklearn.decomposition.PCA() @@ -654,18 +655,21 @@ def test_subflow_version_propagated(self): @mock.patch('warnings.warn') def test_check_dependencies(self, warnings_mock): - dependencies = ['sklearn==0.1', 'sklearn>=99.99.99', 'sklearn>99.99.99'] + dependencies = ['sklearn==0.1', 'sklearn>=99.99.99', + 'sklearn>99.99.99'] for dependency in dependencies: self.assertRaises(ValueError, _check_dependencies, dependency) def test_illegal_parameter_names(self): # illegal name: estimators clf1 = sklearn.ensemble.VotingClassifier( - estimators=[('estimators', sklearn.ensemble.RandomForestClassifier()), - ('whatevs', sklearn.ensemble.ExtraTreesClassifier())]) + estimators=[ + ('estimators', sklearn.ensemble.RandomForestClassifier()), + ('whatevs', sklearn.ensemble.ExtraTreesClassifier())]) clf2 = sklearn.ensemble.VotingClassifier( - estimators=[('whatevs', sklearn.ensemble.RandomForestClassifier()), - ('estimators', sklearn.ensemble.ExtraTreesClassifier())]) + estimators=[ + ('whatevs', sklearn.ensemble.RandomForestClassifier()), + ('estimators', sklearn.ensemble.ExtraTreesClassifier())]) cases = [clf1, clf2] for case in cases: @@ -739,9 +743,9 @@ def test_paralizable_check(self): def test__get_fn_arguments_with_defaults(self): fns = [ - (sklearn.ensemble.RandomForestRegressor.__init__, 15), - (sklearn.tree.DecisionTreeClassifier.__init__, 12), - (sklearn.pipeline.Pipeline.__init__, 0) + (sklearn.ensemble.RandomForestRegressor.__init__, 16), + (sklearn.tree.DecisionTreeClassifier.__init__, 13), + (sklearn.pipeline.Pipeline.__init__, 1) ] for fn, num_params_with_defaults in fns: @@ -749,50 +753,66 @@ def test__get_fn_arguments_with_defaults(self): self.assertIsInstance(defaults, dict) self.assertIsInstance(defaultless, set) # check whether we have both defaults and defaultless params - self.assertEquals(len(defaults), num_params_with_defaults) + self.assertEqual(len(defaults), num_params_with_defaults) self.assertGreater(len(defaultless), 0) # check no overlap - self.assertSetEqual(set(defaults.keys()), set(defaults.keys()) - defaultless) - self.assertSetEqual(defaultless, defaultless - set(defaults.keys())) + self.assertSetEqual(set(defaults.keys()), + set(defaults.keys()) - defaultless) + self.assertSetEqual(defaultless, + defaultless - set(defaults.keys())) def test_deserialize_with_defaults(self): - # used the 'initialize_with_defaults' flag of the deserialization method to return a flow - # that contains default hyperparameter settings. - steps = [('Imputer', sklearn.preprocessing.Imputer()), + # used the 'initialize_with_defaults' flag of the deserialization + # method to return a flow that contains default hyperparameter + # settings. + steps = [('Imputer', Imputer()), ('OneHotEncoder', sklearn.preprocessing.OneHotEncoder()), ('Estimator', sklearn.tree.DecisionTreeClassifier())] pipe_orig = sklearn.pipeline.Pipeline(steps=steps) pipe_adjusted = sklearn.clone(pipe_orig) - params = {'Imputer__strategy': 'median', 'OneHotEncoder__sparse': False, 'Estimator__min_samples_leaf': 42} + params = {'Imputer__strategy': 'median', + 'OneHotEncoder__sparse': False, + 'Estimator__min_samples_leaf': 42} pipe_adjusted.set_params(**params) flow = openml.flows.sklearn_to_flow(pipe_adjusted) - pipe_deserialized = openml.flows.flow_to_sklearn(flow, initialize_with_defaults=True) + pipe_deserialized = openml.flows.flow_to_sklearn( + flow, initialize_with_defaults=True) - # we want to compare pipe_deserialized and pipe_orig. We use the flow equals function for this - assert_flows_equal(openml.flows.sklearn_to_flow(pipe_orig), openml.flows.sklearn_to_flow(pipe_deserialized)) + # we want to compare pipe_deserialized and pipe_orig. We use the flow + # equals function for this + assert_flows_equal(openml.flows.sklearn_to_flow(pipe_orig), + openml.flows.sklearn_to_flow(pipe_deserialized)) def test_deserialize_adaboost_with_defaults(self): - # used the 'initialize_with_defaults' flag of the deserialization method to return a flow - # that contains default hyperparameter settings. - steps = [('Imputer', sklearn.preprocessing.Imputer()), + # used the 'initialize_with_defaults' flag of the deserialization + # method to return a flow that contains default hyperparameter + # settings. + steps = [('Imputer', Imputer()), ('OneHotEncoder', sklearn.preprocessing.OneHotEncoder()), - ('Estimator', sklearn.ensemble.AdaBoostClassifier(sklearn.tree.DecisionTreeClassifier()))] + ('Estimator', sklearn.ensemble.AdaBoostClassifier( + sklearn.tree.DecisionTreeClassifier()))] pipe_orig = sklearn.pipeline.Pipeline(steps=steps) pipe_adjusted = sklearn.clone(pipe_orig) - params = {'Imputer__strategy': 'median', 'OneHotEncoder__sparse': False, 'Estimator__n_estimators': 10} + params = {'Imputer__strategy': 'median', + 'OneHotEncoder__sparse': False, + 'Estimator__n_estimators': 10} pipe_adjusted.set_params(**params) flow = openml.flows.sklearn_to_flow(pipe_adjusted) - pipe_deserialized = openml.flows.flow_to_sklearn(flow, initialize_with_defaults=True) + pipe_deserialized = openml.flows.flow_to_sklearn( + flow, initialize_with_defaults=True) - # we want to compare pipe_deserialized and pipe_orig. We use the flow equals function for this - assert_flows_equal(openml.flows.sklearn_to_flow(pipe_orig), openml.flows.sklearn_to_flow(pipe_deserialized)) + # we want to compare pipe_deserialized and pipe_orig. We use the flow + # equals function for this + assert_flows_equal(openml.flows.sklearn_to_flow(pipe_orig), + openml.flows.sklearn_to_flow(pipe_deserialized)) def test_deserialize_complex_with_defaults(self): - # used the 'initialize_with_defaults' flag of the deserialization method to return a flow - # that contains default hyperparameter settings. - steps = [('Imputer', sklearn.preprocessing.Imputer()), + # used the 'initialize_with_defaults' flag of the deserialization + # method to return a flow that contains default hyperparameter + # settings. + steps = [('Imputer', Imputer()), ('OneHotEncoder', sklearn.preprocessing.OneHotEncoder()), ('Estimator', sklearn.ensemble.AdaBoostClassifier( sklearn.ensemble.BaggingClassifier( @@ -811,5 +831,7 @@ def test_deserialize_complex_with_defaults(self): flow = openml.flows.sklearn_to_flow(pipe_adjusted) pipe_deserialized = openml.flows.flow_to_sklearn(flow, initialize_with_defaults=True) - # we want to compare pipe_deserialized and pipe_orig. We use the flow equals function for this - assert_flows_equal(openml.flows.sklearn_to_flow(pipe_orig), openml.flows.sklearn_to_flow(pipe_deserialized)) + # we want to compare pipe_deserialized and pipe_orig. We use the flow + # equals function for this + assert_flows_equal(openml.flows.sklearn_to_flow(pipe_orig), + openml.flows.sklearn_to_flow(pipe_deserialized)) From e89a979a92431edba87912bdacc4929b2ee7739a Mon Sep 17 00:00:00 2001 From: Guillaume Lemaitre Date: Mon, 17 Sep 2018 18:10:26 +0200 Subject: [PATCH 4/8] iter --- tests/test_flows/test_flow.py | 2 +- tests/test_flows/test_sklearn.py | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/test_flows/test_flow.py b/tests/test_flows/test_flow.py index 0d2fbb3707..5a7ab994b2 100644 --- a/tests/test_flows/test_flow.py +++ b/tests/test_flows/test_flow.py @@ -149,7 +149,7 @@ def test_publish_existing_flow(self): flow = openml.flows.sklearn_to_flow(clf) flow, _ = self._add_sentinel_to_flow_name(flow, None) flow.publish() - self.assertRaisesRegex(openml.exceptions.OpenMLServerException, + self.assertRaisesRegexp(openml.exceptions.OpenMLServerException, 'flow already exists', flow.publish) def test_publish_flow_with_similar_components(self): diff --git a/tests/test_flows/test_sklearn.py b/tests/test_flows/test_sklearn.py index 898f1a116f..785b0f491c 100644 --- a/tests/test_flows/test_sklearn.py +++ b/tests/test_flows/test_sklearn.py @@ -608,9 +608,9 @@ def test_gaussian_process(self): kernel = sklearn.gaussian_process.kernels.Matern() gp = sklearn.gaussian_process.GaussianProcessClassifier( kernel=kernel, optimizer=opt) - self.assertRaisesRegex(TypeError, "Matern\(length_scale=1, nu=1.5\), " - "", - sklearn_to_flow, gp) + self.assertRaisesRegexp(TypeError, "Matern\(length_scale=1, nu=1.5\), " + "", + sklearn_to_flow, gp) def test_error_on_adding_component_multiple_times_to_flow(self): # this function implicitly checks @@ -620,19 +620,19 @@ def test_error_on_adding_component_multiple_times_to_flow(self): pipeline = sklearn.pipeline.Pipeline((('pca1', pca), ('pca2', pca2))) fixture = "Found a second occurence of component .*.PCA when trying " \ "to serialize Pipeline" - self.assertRaisesRegex(ValueError, fixture, sklearn_to_flow, pipeline) + self.assertRaisesRegexp(ValueError, fixture, sklearn_to_flow, pipeline) fu = sklearn.pipeline.FeatureUnion((('pca1', pca), ('pca2', pca2))) fixture = "Found a second occurence of component .*.PCA when trying " \ "to serialize FeatureUnion" - self.assertRaisesRegex(ValueError, fixture, sklearn_to_flow, fu) + self.assertRaisesRegexp(ValueError, fixture, sklearn_to_flow, fu) fs = sklearn.feature_selection.SelectKBest() fu2 = sklearn.pipeline.FeatureUnion((('pca1', pca), ('fs', fs))) pipeline2 = sklearn.pipeline.Pipeline((('fu', fu2), ('pca2', pca2))) fixture = "Found a second occurence of component .*.PCA when trying " \ "to serialize Pipeline" - self.assertRaisesRegex(ValueError, fixture, sklearn_to_flow, pipeline2) + self.assertRaisesRegexp(ValueError, fixture, sklearn_to_flow, pipeline2) def test_subflow_version_propagated(self): this_directory = os.path.dirname(os.path.abspath(__file__)) From fcb0a3d7ad88e81b8d510610d688ff8b1beb70b9 Mon Sep 17 00:00:00 2001 From: Guillaume Lemaitre Date: Tue, 18 Sep 2018 10:30:23 +0200 Subject: [PATCH 5/8] compat 0.18 0.20 --- tests/test_flows/test_sklearn.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/tests/test_flows/test_sklearn.py b/tests/test_flows/test_sklearn.py index 785b0f491c..8906463ef4 100644 --- a/tests/test_flows/test_sklearn.py +++ b/tests/test_flows/test_sklearn.py @@ -742,11 +742,18 @@ def test_paralizable_check(self): self.assertRaises(PyOpenMLError, _check_n_jobs, model) def test__get_fn_arguments_with_defaults(self): - fns = [ - (sklearn.ensemble.RandomForestRegressor.__init__, 16), - (sklearn.tree.DecisionTreeClassifier.__init__, 13), - (sklearn.pipeline.Pipeline.__init__, 1) - ] + if LooseVersion(sklearn.__version__) < "0.20": + fns = [ + (sklearn.ensemble.RandomForestRegressor.__init__, 16), + (sklearn.tree.DecisionTreeClassifier.__init__, 13), + (sklearn.pipeline.Pipeline.__init__, 1) + ] + else: + fns = [ + (sklearn.ensemble.RandomForestRegressor.__init__, 15), + (sklearn.tree.DecisionTreeClassifier.__init__, 12), + (sklearn.pipeline.Pipeline.__init__, 0) + ] for fn, num_params_with_defaults in fns: defaults, defaultless = openml.flows.sklearn_converter._get_fn_arguments_with_defaults(fn) From 5102eb70f7c35f5c465bd2dd4be66e99ac7399b9 Mon Sep 17 00:00:00 2001 From: Guillaume Lemaitre Date: Tue, 18 Sep 2018 11:08:46 +0200 Subject: [PATCH 6/8] fix --- tests/test_flows/test_sklearn.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/test_flows/test_sklearn.py b/tests/test_flows/test_sklearn.py index 8906463ef4..2065495492 100644 --- a/tests/test_flows/test_sklearn.py +++ b/tests/test_flows/test_sklearn.py @@ -743,17 +743,17 @@ def test_paralizable_check(self): def test__get_fn_arguments_with_defaults(self): if LooseVersion(sklearn.__version__) < "0.20": - fns = [ - (sklearn.ensemble.RandomForestRegressor.__init__, 16), - (sklearn.tree.DecisionTreeClassifier.__init__, 13), - (sklearn.pipeline.Pipeline.__init__, 1) - ] - else: fns = [ (sklearn.ensemble.RandomForestRegressor.__init__, 15), (sklearn.tree.DecisionTreeClassifier.__init__, 12), (sklearn.pipeline.Pipeline.__init__, 0) ] + else: + fns = [ + (sklearn.ensemble.RandomForestRegressor.__init__, 16), + (sklearn.tree.DecisionTreeClassifier.__init__, 13), + (sklearn.pipeline.Pipeline.__init__, 1) + ] for fn, num_params_with_defaults in fns: defaults, defaultless = openml.flows.sklearn_converter._get_fn_arguments_with_defaults(fn) From 2093a8e289df15b3544f2736eac438c2e68860bf Mon Sep 17 00:00:00 2001 From: Guillaume Lemaitre Date: Tue, 18 Sep 2018 14:58:30 +0200 Subject: [PATCH 7/8] fix for compat scikit-learn 0.19 --- tests/test_flows/test_sklearn.py | 48 ++++++++++++++++---------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/tests/test_flows/test_sklearn.py b/tests/test_flows/test_sklearn.py index 2065495492..6daf3207c6 100644 --- a/tests/test_flows/test_sklearn.py +++ b/tests/test_flows/test_sklearn.py @@ -77,7 +77,7 @@ def test_serialize_model(self, check_dependencies_mock): % sklearn.__version__ # min_impurity_decrease has been introduced in 0.20 # min_impurity_split has been deprecated in 0.20 - if LooseVersion(sklearn.__version__) < "0.20": + if LooseVersion(sklearn.__version__) < "0.19": fixture_parameters = \ OrderedDict((('class_weight', 'null'), ('criterion', '"entropy"'), @@ -138,29 +138,29 @@ def test_serialize_model_clustering(self, check_dependencies_mock): if LooseVersion(sklearn.__version__) < "0.20": fixture_parameters = \ OrderedDict((('algorithm', '"auto"'), - ('copy_x', 'true'), - ('init', '"k-means++"'), - ('max_iter', '300'), - ('n_clusters', '8'), - ('n_init', '10'), - ('n_jobs', '1'), - ('precompute_distances', '"auto"'), - ('random_state', 'null'), - ('tol', '0.0001'), - ('verbose', '0'))) + ('copy_x', 'true'), + ('init', '"k-means++"'), + ('max_iter', '300'), + ('n_clusters', '8'), + ('n_init', '10'), + ('n_jobs', '1'), + ('precompute_distances', '"auto"'), + ('random_state', 'null'), + ('tol', '0.0001'), + ('verbose', '0'))) else: fixture_parameters = \ OrderedDict((('algorithm', '"auto"'), - ('copy_x', 'true'), - ('init', '"k-means++"'), - ('max_iter', '300'), - ('n_clusters', '8'), - ('n_init', '10'), - ('n_jobs', 'null'), - ('precompute_distances', '"auto"'), - ('random_state', 'null'), - ('tol', '0.0001'), - ('verbose', '0'))) + ('copy_x', 'true'), + ('init', '"k-means++"'), + ('max_iter', '300'), + ('n_clusters', '8'), + ('n_init', '10'), + ('n_jobs', 'null'), + ('precompute_distances', '"auto"'), + ('random_state', 'null'), + ('tol', '0.0001'), + ('verbose', '0'))) serialization = sklearn_to_flow(model) @@ -245,7 +245,7 @@ def test_serialize_pipeline(self): # The parameters only have the name of base objects(not the whole flow) # as value # memory parameter has been added in 0.19 - if LooseVersion(sklearn.__version__) < "0.19.0": + if LooseVersion(sklearn.__version__) < "0.19": self.assertEqual(len(serialization.parameters), 1) else: self.assertEqual(len(serialization.parameters), 2) @@ -307,7 +307,7 @@ def test_serialize_pipeline_clustering(self): # The parameters only have the name of base objects(not the whole flow) # as value # memory parameter has been added in 0.19 - if LooseVersion(sklearn.__version__) < "0.19.0": + if LooseVersion(sklearn.__version__) < "0.19": self.assertEqual(len(serialization.parameters), 1) else: self.assertEqual(len(serialization.parameters), 2) @@ -742,7 +742,7 @@ def test_paralizable_check(self): self.assertRaises(PyOpenMLError, _check_n_jobs, model) def test__get_fn_arguments_with_defaults(self): - if LooseVersion(sklearn.__version__) < "0.20": + if LooseVersion(sklearn.__version__) < "0.19": fns = [ (sklearn.ensemble.RandomForestRegressor.__init__, 15), (sklearn.tree.DecisionTreeClassifier.__init__, 12), From 8ea33009be634eabe6b9d8cf870e50c7bfb6ce21 Mon Sep 17 00:00:00 2001 From: Guillaume Lemaitre Date: Thu, 20 Sep 2018 11:19:51 +0200 Subject: [PATCH 8/8] Revert some string change --- tests/test_flows/test_flow.py | 21 ++++++++---- tests/test_flows/test_sklearn.py | 58 ++++++++++++++++++++++---------- 2 files changed, 56 insertions(+), 23 deletions(-) diff --git a/tests/test_flows/test_flow.py b/tests/test_flows/test_flow.py index 5a7ab994b2..39c03fee12 100644 --- a/tests/test_flows/test_flow.py +++ b/tests/test_flows/test_flow.py @@ -349,12 +349,21 @@ def test_sklearn_to_upload_to_flow(self): openml.flows.functions.assert_flows_equal(new_flow, flow) self.assertIsNot(new_flow, flow) - estimators_names = (sentinel, 'RandomizedSearchCV', 'Pipeline', - 'OneHotEncoder', 'StandardScaler', 'FeatureUnion', - 'TruncatedSVD', 'SelectPercentile', - 'AdaBoostClassifier', 'DecisionTreeClassifier') - for keyword in estimators_names: - self.assertTrue(keyword in new_flow.name) + # OneHotEncoder was moved to _encoders module in 0.20 + module_name_encoder = ('_encoders' + if LooseVersion(sklearn.__version__) >= "0.20" + else 'data') + fixture_name = '%ssklearn.model_selection._search.RandomizedSearchCV(' \ + 'estimator=sklearn.pipeline.Pipeline(' \ + 'ohe=sklearn.preprocessing.%s.OneHotEncoder,' \ + 'scaler=sklearn.preprocessing.data.StandardScaler,' \ + 'fu=sklearn.pipeline.FeatureUnion(' \ + 'pca=sklearn.decomposition.truncated_svd.TruncatedSVD,' \ + 'fs=sklearn.feature_selection.univariate_selection.SelectPercentile),' \ + 'boosting=sklearn.ensemble.weight_boosting.AdaBoostClassifier(' \ + 'base_estimator=sklearn.tree.tree.DecisionTreeClassifier)))' \ + % (sentinel, module_name_encoder) + self.assertEqual(new_flow.name, fixture_name) new_flow.model.fit(X, y) def test_extract_tags(self): diff --git a/tests/test_flows/test_sklearn.py b/tests/test_flows/test_sklearn.py index 6daf3207c6..d08f63ff00 100644 --- a/tests/test_flows/test_sklearn.py +++ b/tests/test_flows/test_sklearn.py @@ -358,9 +358,15 @@ def test_serialize_feature_union(self): fu = sklearn.pipeline.FeatureUnion( transformer_list=[('ohe', ohe), ('scaler', scaler)]) serialization = sklearn_to_flow(fu) - estimators_names = ('FeatureUnion', 'OneHotEncoder', 'StandardScaler') - for keyword in estimators_names: - self.assertTrue(keyword in serialization.name) + # OneHotEncoder was moved to _encoders module in 0.20 + module_name_encoder = ('_encoders' + if LooseVersion(sklearn.__version__) >= "0.20" + else 'data') + self.assertEqual(serialization.name, + 'sklearn.pipeline.FeatureUnion(' + 'ohe=sklearn.preprocessing.{}.OneHotEncoder,' + 'scaler=sklearn.preprocessing.data.StandardScaler)' + .format(module_name_encoder)) new_model = flow_to_sklearn(serialization) self.assertEqual(type(new_model), type(fu)) @@ -395,9 +401,10 @@ def test_serialize_feature_union(self): fu.set_params(scaler=None) serialization = sklearn_to_flow(fu) - estimators_names = ('FeatureUnion', 'OneHotEncoder') - for keyword in estimators_names: - self.assertTrue(keyword in estimators_names) + self.assertEqual(serialization.name, + 'sklearn.pipeline.FeatureUnion(' + 'ohe=sklearn.preprocessing.{}.OneHotEncoder)' + .format(module_name_encoder)) new_model = flow_to_sklearn(serialization) self.assertEqual(type(new_model), type(fu)) self.assertIsNot(new_model, fu) @@ -414,10 +421,22 @@ def test_serialize_feature_union_switched_names(self): transformer_list=[('scaler', ohe), ('ohe', scaler)]) fu1_serialization = sklearn_to_flow(fu1) fu2_serialization = sklearn_to_flow(fu2) - estimators_names = ('FeatureUnion', 'OneHotEncoder', 'StandardScaler') - for keyword in estimators_names: - self.assertTrue(keyword in fu1_serialization.name) - self.assertTrue(keyword in fu2_serialization.name) + # OneHotEncoder was moved to _encoders module in 0.20 + module_name_encoder = ('_encoders' + if LooseVersion(sklearn.__version__) >= "0.20" + else 'data') + self.assertEqual( + fu1_serialization.name, + "sklearn.pipeline.FeatureUnion(" + "ohe=sklearn.preprocessing.{}.OneHotEncoder," + "scaler=sklearn.preprocessing.data.StandardScaler)" + .format(module_name_encoder)) + self.assertEqual( + fu2_serialization.name, + "sklearn.pipeline.FeatureUnion(" + "scaler=sklearn.preprocessing.{}.OneHotEncoder," + "ohe=sklearn.preprocessing.data.StandardScaler)" + .format(module_name_encoder)) def test_serialize_complex_flow(self): ohe = sklearn.preprocessing.OneHotEncoder(categorical_features=[0]) @@ -434,13 +453,18 @@ def test_serialize_complex_flow(self): rs = sklearn.model_selection.RandomizedSearchCV( estimator=model, param_distributions=parameter_grid, cv=cv) serialized = sklearn_to_flow(rs) - - # check that the name of the estimator occur in the name of the flow - estimator_names = ('RandomizedSearchCV', 'Pipeline', 'OneHotEncoder', - 'StandardScaler', 'AdaBoostClassifier', - 'DecisionTreeClassifier') - for keyword in estimator_names: - self.assertTrue(keyword in serialized.name) + # OneHotEncoder was moved to _encoders module in 0.20 + 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)) + self.assertEqual(serialized.name, fixture_name) # now do deserialization deserialized = flow_to_sklearn(serialized)