From 54b1fc13291e7b8cf28129bbb1b6587b60374c09 Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Wed, 22 Aug 2018 10:36:15 -0400 Subject: [PATCH 01/18] added check for masked constants --- openml/runs/functions.py | 8 +++- tests/test_runs/test_run_functions.py | 56 ++++++++++++++++++++++++++- 2 files changed, 60 insertions(+), 4 deletions(-) diff --git a/openml/runs/functions.py b/openml/runs/functions.py index 464456d9ba..188ef3234d 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -639,7 +639,11 @@ def _extract_arfftrace(model, rep_no, fold_no): arff_line = [rep_no, fold_no, itt_no, test_score, selected] for key in model.cv_results_: if key.startswith('param_'): - serialized_value = json.dumps(model.cv_results_[key][itt_no]) + value = model.cv_results_[key][itt_no] + if value is not np.ma.masked: + serialized_value = json.dumps(value) + else: + serialized_value = np.nan arff_line.append(serialized_value) arff_tracecontent.append(arff_line) return arff_tracecontent @@ -665,7 +669,7 @@ def _extract_arfftrace_attributes(model): # supported types should include all types, including bool, int float supported_basic_types = (bool, int, float, six.string_types) for param_value in model.cv_results_[key]: - if isinstance(param_value, supported_basic_types) or param_value is None: + if isinstance(param_value, supported_basic_types) or param_value is None or param_value is np.ma.masked: # basic string values type = 'STRING' elif isinstance(param_value, list) and all(isinstance(i, int) for i in param_value): diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index dee2515157..0d8772e40b 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -35,6 +35,7 @@ StratifiedKFold from sklearn.pipeline import Pipeline +__version__ = '0.0.1' # neccessary for serialization of dummy estimators class HardNaiveBayes(GaussianNB): # class for testing a naive bayes classifier that does not allow soft predictions @@ -44,6 +45,39 @@ def __init__(self, priors=None): def predict_proba(*args, **kwargs): raise AttributeError('predict_proba is not available when probability=False') +class DefaultSearchCV(BaseSearchCV): + + def __init__(self, estimator, defaults, scoring=None, + fit_params=None, n_jobs=1, iid='warn', refit=True, cv=None, + verbose=0, pre_dispatch='2*n_jobs', + error_score='raise', return_train_score="warn"): + self.defaults = defaults + self.param_distributions = DefaultSearchCV._determine_param_distributions(defaults) + super(DefaultSearchCV, self).__init__( + estimator=estimator, scoring=scoring, fit_params=fit_params, + n_jobs=n_jobs, iid=iid, refit=refit, cv=cv, verbose=verbose, + pre_dispatch=pre_dispatch, error_score=error_score, + return_train_score=return_train_score) + + @staticmethod + def _determine_param_distributions(defaults): + result = {} + for default in defaults: + for param, value in default.items(): + if param not in result: + result[param] = list() + if value not in result[param]: + result[param].append(value) + return result + + # For sklearn version 0.19.0 and up + # def _get_param_iterator(self): + # """Return ParameterSampler instance for the given distributions""" + # return self.defaults + + def fit(self, X, y=None, groups=None): + return self._fit(X, y, groups, self.defaults) + class TestRun(TestBase): _multiprocess_can_split_ = True @@ -136,7 +170,8 @@ def _remove_random_state(flow): if flow.class_name not in \ ['sklearn.model_selection._search.GridSearchCV', - 'sklearn.pipeline.Pipeline']: + 'sklearn.pipeline.Pipeline', + 'test_run_functions.DefaultSearchCV']: # If the flow is initialized from a model without a random state, # the flow is on the server without any random state self.assertEqual(flow.parameters['random_state'], 'null') @@ -155,7 +190,8 @@ def _remove_random_state(flow): flow_server2 = openml.flows.sklearn_to_flow(clf_server2) if flow.class_name not in \ ['sklearn.model_selection._search.GridSearchCV', - 'sklearn.pipeline.Pipeline']: + 'sklearn.pipeline.Pipeline', + 'test_run_functions.DefaultSearchCV']: self.assertEqual(flow_server2.parameters['random_state'], random_state_value) @@ -374,6 +410,22 @@ def test_run_and_upload_randomsearch(self): # it has a different value than the other examples before self._run_and_upload(randomsearch, '12172') + + def test_run_and_upload_defaultsearch(self): + # more complicated, as it can have hierarchical parameters + defaultsearch = DefaultSearchCV( + RandomForestClassifier(n_estimators=5), + [{'max_features': 4}, + {'min_samples_leaf': 1}, + {'min_samples_leaf': 2}, + {'min_samples_leaf': 3}, + {'max_features': 4, 'min_samples_leaf': 3}], + cv=StratifiedKFold(n_splits=2, shuffle=True)) + # The random states for the RandomizedSearchCV is set after the + # random state of the RandomForestClassifier is set, therefore, + # it has a different value than the other examples before + self._run_and_upload(defaultsearch, '12172') + ############################################################################ def test_learning_curve_task_1(self): From 107df59d418c329072eb0dda65aefc5a8f19d977 Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Wed, 22 Aug 2018 12:13:29 -0400 Subject: [PATCH 02/18] improved error message --- tests/test_runs/test_run_functions.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index 0d8772e40b..945bdd5025 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -172,6 +172,8 @@ def _remove_random_state(flow): ['sklearn.model_selection._search.GridSearchCV', 'sklearn.pipeline.Pipeline', 'test_run_functions.DefaultSearchCV']: + error_msg = 'Flow %s (id=%d) does not have a random state parameter' % (flow.name, flow.flow_id) + self.assertIn('random_state', flow.parameters, error_msg) # If the flow is initialized from a model without a random state, # the flow is on the server without any random state self.assertEqual(flow.parameters['random_state'], 'null') From f5c60d81ebcacb6d27e96d5971fcd0ec947ff6ad Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Wed, 22 Aug 2018 12:27:25 -0400 Subject: [PATCH 03/18] added flow class --- tests/test_runs/test_run_functions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index 945bdd5025..40cb6c6b3f 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -172,7 +172,7 @@ def _remove_random_state(flow): ['sklearn.model_selection._search.GridSearchCV', 'sklearn.pipeline.Pipeline', 'test_run_functions.DefaultSearchCV']: - error_msg = 'Flow %s (id=%d) does not have a random state parameter' % (flow.name, flow.flow_id) + error_msg = 'Flow class %s (id=%d) does not have a random state parameter' % (flow.class_name, flow.flow_id) self.assertIn('random_state', flow.parameters, error_msg) # If the flow is initialized from a model without a random state, # the flow is on the server without any random state From a90ba877e48808a97dcd87258fd9df0bb8a82823 Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Wed, 22 Aug 2018 12:38:29 -0400 Subject: [PATCH 04/18] refactored testcase --- tests/test_runs/test_run_functions.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index 40cb6c6b3f..2241e479df 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -138,7 +138,12 @@ def _check_serialized_optimized_run(self, run_id): def _perform_run(self, task_id, num_instances, clf, random_state_value=None, check_setup=True): - + # last case (DefaultSearchCV) relies on where the test is invoked from + # TODO: move it to a 'permanent' place? + classes_without_random_state = \ + ['sklearn.model_selection._search.GridSearchCV', + 'sklearn.pipeline.Pipeline', + 'tests.test_runs.test_run_functions.DefaultSearchCV'] def _remove_random_state(flow): if 'random_state' in flow.parameters: del flow.parameters['random_state'] @@ -168,10 +173,7 @@ def _remove_random_state(flow): flow_local = openml.flows.sklearn_to_flow(clf) flow_server = openml.flows.sklearn_to_flow(clf_server) - if flow.class_name not in \ - ['sklearn.model_selection._search.GridSearchCV', - 'sklearn.pipeline.Pipeline', - 'test_run_functions.DefaultSearchCV']: + if flow.class_name not in classes_without_random_state: error_msg = 'Flow class %s (id=%d) does not have a random state parameter' % (flow.class_name, flow.flow_id) self.assertIn('random_state', flow.parameters, error_msg) # If the flow is initialized from a model without a random state, @@ -190,10 +192,7 @@ def _remove_random_state(flow): # and test the initialize setup from run function clf_server2 = openml.runs.initialize_model_from_run(run_server.run_id) flow_server2 = openml.flows.sklearn_to_flow(clf_server2) - if flow.class_name not in \ - ['sklearn.model_selection._search.GridSearchCV', - 'sklearn.pipeline.Pipeline', - 'test_run_functions.DefaultSearchCV']: + if flow.class_name not in classes_without_random_state: self.assertEqual(flow_server2.parameters['random_state'], random_state_value) From 7a47652bdf0b8f295137c0e928976dd16bfbc5b4 Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Tue, 11 Sep 2018 18:40:12 -0400 Subject: [PATCH 05/18] moved testcase --- openml/runs/functions.py | 4 +- openml/runs/trace.py | 4 +- tests/test_runs/test_run_functions.py | 92 ++++++++++----------------- 3 files changed, 39 insertions(+), 61 deletions(-) diff --git a/openml/runs/functions.py b/openml/runs/functions.py index 188ef3234d..d382eac54a 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -223,7 +223,7 @@ def initialize_model_from_run(run_id): def initialize_model_from_trace(run_id, repeat, fold, iteration=None): - ''' + """ Initialize a model based on the parameters that were set by an optimization procedure (i.e., using the exact same parameter settings) @@ -250,7 +250,7 @@ def initialize_model_from_trace(run_id, repeat, fold, iteration=None): ------- model : sklearn model the scikit-learn model with all parameters initailized - ''' + """ run_trace = get_run_trace(run_id) if iteration is None: diff --git a/openml/runs/trace.py b/openml/runs/trace.py index f653cb2c2a..b1cc088f1a 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -117,10 +117,10 @@ def get_parameters(self): result = {} # parameters have prefix 'parameter_' prefix = 'parameter_' - for param in self.setup_string: key = param[len(prefix):] - result[key] = json.loads(self.setup_string[param]) + value = self.setup_string[param] + result[key] = json.loads(value) return result def __str__(self): diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index 2241e479df..505e5b8d74 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -35,7 +35,6 @@ StratifiedKFold from sklearn.pipeline import Pipeline -__version__ = '0.0.1' # neccessary for serialization of dummy estimators class HardNaiveBayes(GaussianNB): # class for testing a naive bayes classifier that does not allow soft predictions @@ -45,39 +44,6 @@ def __init__(self, priors=None): def predict_proba(*args, **kwargs): raise AttributeError('predict_proba is not available when probability=False') -class DefaultSearchCV(BaseSearchCV): - - def __init__(self, estimator, defaults, scoring=None, - fit_params=None, n_jobs=1, iid='warn', refit=True, cv=None, - verbose=0, pre_dispatch='2*n_jobs', - error_score='raise', return_train_score="warn"): - self.defaults = defaults - self.param_distributions = DefaultSearchCV._determine_param_distributions(defaults) - super(DefaultSearchCV, self).__init__( - estimator=estimator, scoring=scoring, fit_params=fit_params, - n_jobs=n_jobs, iid=iid, refit=refit, cv=cv, verbose=verbose, - pre_dispatch=pre_dispatch, error_score=error_score, - return_train_score=return_train_score) - - @staticmethod - def _determine_param_distributions(defaults): - result = {} - for default in defaults: - for param, value in default.items(): - if param not in result: - result[param] = list() - if value not in result[param]: - result[param].append(value) - return result - - # For sklearn version 0.19.0 and up - # def _get_param_iterator(self): - # """Return ParameterSampler instance for the given distributions""" - # return self.defaults - - def fit(self, X, y=None, groups=None): - return self._fit(X, y, groups, self.defaults) - class TestRun(TestBase): _multiprocess_can_split_ = True @@ -142,8 +108,8 @@ def _perform_run(self, task_id, num_instances, clf, # TODO: move it to a 'permanent' place? classes_without_random_state = \ ['sklearn.model_selection._search.GridSearchCV', - 'sklearn.pipeline.Pipeline', - 'tests.test_runs.test_run_functions.DefaultSearchCV'] + 'sklearn.pipeline.Pipeline'] + def _remove_random_state(flow): if 'random_state' in flow.parameters: del flow.parameters['random_state'] @@ -199,7 +165,7 @@ def _remove_random_state(flow): _remove_random_state(flow_server2) openml.flows.assert_flows_equal(flow_local, flow_server2) - #self.assertEquals(clf.get_params(), clf_prime.get_params()) + # self.assertEquals(clf.get_params(), clf_prime.get_params()) # self.assertEquals(clf, clf_prime) downloaded = openml.runs.get_run(run_.run_id) @@ -208,14 +174,14 @@ def _remove_random_state(flow): return run def _check_fold_evaluations(self, fold_evaluations, num_repeats, num_folds, max_time_allowed=60000): - ''' + """ Checks whether the right timing measures are attached to the run (before upload). Test is only performed for versions >= Python3.3 In case of check_n_jobs(clf) == false, please do not perform this check (check this condition outside of this function. ) default max_time_allowed (per fold, in milli seconds) = 1 minute, quite pessimistic - ''' + """ # a dict mapping from openml measure to a tuple with the minimum and maximum allowed value check_measures = {'usercpu_time_millis_testing': (0, max_time_allowed), @@ -243,16 +209,15 @@ def _check_fold_evaluations(self, fold_evaluations, num_repeats, num_folds, max_ self.assertGreaterEqual(evaluation, min_val) self.assertLessEqual(evaluation, max_val) - def _check_sample_evaluations(self, sample_evaluations, num_repeats, num_folds, num_samples, max_time_allowed=60000): - ''' + """ Checks whether the right timing measures are attached to the run (before upload). Test is only performed for versions >= Python3.3 In case of check_n_jobs(clf) == false, please do not perform this check (check this condition outside of this function. ) default max_time_allowed (per fold, in milli seconds) = 1 minute, quite pessimistic - ''' + """ # a dict mapping from openml measure to a tuple with the minimum and maximum allowed value check_measures = {'usercpu_time_millis_testing': (0, max_time_allowed), @@ -334,6 +299,20 @@ def test__publish_flow_if_necessary(self): # like unittest2 def _run_and_upload(self, clf, rsv): + def determine_grid_size(param_grid): + if isinstance(param_grid, dict): + grid_iterations = 1 + for param in param_grid: + grid_iterations *= len(param_grid[param]) + return grid_iterations + elif isinstance(param_grid, list): + grid_iterations = 0 + for sub_grid in param_grid: + grid_iterations += determine_grid_size(sub_grid) + return grid_iterations + else: + raise TypeError('Param Grid should be of type list (GridSearch only) or dict') + task_id = 119 # diabates dataset num_test_instances = 253 # 33% holdout task num_folds = 1 # because of holdout @@ -354,9 +333,7 @@ def _run_and_upload(self, clf, rsv): if isinstance(clf, BaseSearchCV): if isinstance(clf, GridSearchCV): - grid_iterations = 1 - for param in clf.param_grid: - grid_iterations *= len(clf.param_grid[param]) + grid_iterations = determine_grid_size(clf.param_grid) self.assertEqual(len(run.trace_content), grid_iterations * num_folds) else: @@ -411,21 +388,22 @@ def test_run_and_upload_randomsearch(self): # it has a different value than the other examples before self._run_and_upload(randomsearch, '12172') - - def test_run_and_upload_defaultsearch(self): - # more complicated, as it can have hierarchical parameters - defaultsearch = DefaultSearchCV( + 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 + gridsearch = GridSearchCV( RandomForestClassifier(n_estimators=5), - [{'max_features': 4}, - {'min_samples_leaf': 1}, - {'min_samples_leaf': 2}, - {'min_samples_leaf': 3}, - {'max_features': 4, 'min_samples_leaf': 3}], - cv=StratifiedKFold(n_splits=2, shuffle=True)) - # The random states for the RandomizedSearchCV is set after the + [ + {'max_features': [2, 4]}, + {'min_samples_leaf': [1, 10]} + ], + cv=StratifiedKFold(n_splits=2, shuffle=True) + ) + # The random states for the GridSearchCV is set after the # random state of the RandomForestClassifier is set, therefore, # it has a different value than the other examples before - self._run_and_upload(defaultsearch, '12172') + self._run_and_upload(gridsearch, '12172') ############################################################################ From cd8b2ed9a685ba8451e01c2fa1cb49cec49908fc Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Wed, 12 Sep 2018 09:20:00 -0400 Subject: [PATCH 06/18] reparameterized check n jobs internal function --- openml/flows/sklearn_converter.py | 35 +++++++++++++---------- tests/test_runs/test_run_functions.py | 40 +++++++++++++-------------- 2 files changed, 40 insertions(+), 35 deletions(-) diff --git a/openml/flows/sklearn_converter.py b/openml/flows/sklearn_converter.py index c68d4cd2e4..13ed316436 100644 --- a/openml/flows/sklearn_converter.py +++ b/openml/flows/sklearn_converter.py @@ -625,20 +625,26 @@ def _serialize_cross_validator(o): def _check_n_jobs(model): - ''' + """ Returns True if the parameter settings of model are chosen s.t. the model - will run on a single core (in that case, openml-python can measure runtimes) - ''' - 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 - # -1 = use all available cores -> this makes it hard to - # measure runtime in a fair way - if value != 1 or disallow_parameter: + will run on a single core (in that case, openml-python can measure runtimes) + """ + def check(param_grid, restricted_parameter_name, legal_values): + if isinstance(param_grid, dict): + for param, value in param_grid.items(): + # n_jobs is scikitlearn parameter for paralizing jobs + if param.split('__')[-1] == restricted_parameter_name: + # 0 = illegal value (?), 1 = use one core, n = use n cores + # -1 = use all available cores -> this makes it hard to + # measure runtime in a fair way + if legal_values is None or value not in legal_values: + return False + return True + elif isinstance(param_grid, list): + for sub_grid in param_grid: + if not check(sub_grid, restricted_parameter_name, legal_values): return False - return True + return True if not (isinstance(model, sklearn.base.BaseEstimator) or isinstance(model, sklearn.model_selection._search.BaseSearchCV)): @@ -646,7 +652,6 @@ def check(param_dict, disallow_parameter=False): # 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): param_distributions = model.param_grid elif isinstance(model, sklearn.model_selection.RandomizedSearchCV): @@ -659,12 +664,12 @@ def check(param_dict, disallow_parameter=False): print('Warning! Using subclass BaseSearchCV other than ' \ '{GridSearchCV, RandomizedSearchCV}. Should implement param check. ') - if not check(param_distributions, True): + if not check(param_distributions, 'n_jobs', None): raise PyOpenMLError('openml-python should not be used to ' 'optimize the n_jobs parameter.') # check the parameters for n_jobs - return check(model.get_params(), False) + return check(model.get_params(), 'n_jobs', [1]) def _deserialize_cross_validator(value): diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index 505e5b8d74..606cbe2f2e 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -88,7 +88,7 @@ def _check_serialized_optimized_run(self, run_id): seed=1) predictions_prime = run_prime._generate_arff_dict() - self.assertEquals(len(predictions_prime['data']), len(predictions['data'])) + self.assertEqual(len(predictions_prime['data']), len(predictions['data'])) # The original search model does not submit confidence bounds, # so we can not compare the arff line @@ -98,7 +98,7 @@ def _check_serialized_optimized_run(self, run_id): # that does not necessarily hold. # But with the current code base, it holds. for col_idx in compare_slice: - self.assertEquals(predictions['data'][idx][col_idx], predictions_prime['data'][idx][col_idx]) + self.assertEqual(predictions['data'][idx][col_idx], predictions_prime['data'][idx][col_idx]) return True @@ -165,8 +165,8 @@ def _remove_random_state(flow): _remove_random_state(flow_server2) openml.flows.assert_flows_equal(flow_local, flow_server2) - # self.assertEquals(clf.get_params(), clf_prime.get_params()) - # self.assertEquals(clf, clf_prime) + # self.assertEqual(clf.get_params(), clf_prime.get_params()) + # self.assertEqual(clf, clf_prime) downloaded = openml.runs.get_run(run_.run_id) assert('openml-python' in downloaded.tags) @@ -192,17 +192,17 @@ def _check_fold_evaluations(self, fold_evaluations, num_repeats, num_folds, max_ self.assertIsInstance(fold_evaluations, dict) if sys.version_info[:2] >= (3, 3): # this only holds if we are allowed to record time (otherwise some are missing) - self.assertEquals(set(fold_evaluations.keys()), set(check_measures.keys())) + self.assertEqual(set(fold_evaluations.keys()), set(check_measures.keys())) for measure in check_measures.keys(): if measure in fold_evaluations: num_rep_entrees = len(fold_evaluations[measure]) - self.assertEquals(num_rep_entrees, num_repeats) + self.assertEqual(num_rep_entrees, num_repeats) min_val = check_measures[measure][0] max_val = check_measures[measure][1] for rep in range(num_rep_entrees): num_fold_entrees = len(fold_evaluations[measure][rep]) - self.assertEquals(num_fold_entrees, num_folds) + self.assertEqual(num_fold_entrees, num_folds) for fold in range(num_fold_entrees): evaluation = fold_evaluations[measure][rep][fold] self.assertIsInstance(evaluation, float) @@ -228,18 +228,18 @@ def _check_sample_evaluations(self, sample_evaluations, num_repeats, num_folds, self.assertIsInstance(sample_evaluations, dict) if sys.version_info[:2] >= (3, 3): # this only holds if we are allowed to record time (otherwise some are missing) - self.assertEquals(set(sample_evaluations.keys()), set(check_measures.keys())) + self.assertEqual(set(sample_evaluations.keys()), set(check_measures.keys())) for measure in check_measures.keys(): if measure in sample_evaluations: num_rep_entrees = len(sample_evaluations[measure]) - self.assertEquals(num_rep_entrees, num_repeats) + self.assertEqual(num_rep_entrees, num_repeats) for rep in range(num_rep_entrees): num_fold_entrees = len(sample_evaluations[measure][rep]) - self.assertEquals(num_fold_entrees, num_folds) + self.assertEqual(num_fold_entrees, num_folds) for fold in range(num_fold_entrees): num_sample_entrees = len(sample_evaluations[measure][rep][fold]) - self.assertEquals(num_sample_entrees, num_samples) + self.assertEqual(num_sample_entrees, num_samples) for sample in range(num_sample_entrees): evaluation = sample_evaluations[measure][rep][fold][sample] self.assertIsInstance(evaluation, float) @@ -329,7 +329,7 @@ def determine_grid_size(param_grid): for fold in run.fold_evaluations['predictive_accuracy'][rep].keys(): accuracy_scores_provided.append( run.fold_evaluations['predictive_accuracy'][rep][fold]) - self.assertEquals(sum(accuracy_scores_provided), sum(accuracy_scores)) + self.assertEqual(sum(accuracy_scores_provided), sum(accuracy_scores)) if isinstance(clf, BaseSearchCV): if isinstance(clf, GridSearchCV): @@ -461,7 +461,7 @@ def test_initialize_cv_from_run(self): modelR = openml.runs.initialize_model_from_run(run.run_id) modelS = openml.setups.initialize_model(run.setup_id) - self.assertEquals(modelS.cv.random_state, 62501) + self.assertEqual(modelS.cv.random_state, 62501) self.assertEqual(modelR.cv.random_state, 62501) def _test_local_evaluations(self, run): @@ -483,7 +483,7 @@ def _test_local_evaluations(self, run): (sklearn.metrics.brier_score_loss, {})] for test_idx, test in enumerate(tests): alt_scores = run.get_metric_fn(test[0], test[1]) - self.assertEquals(len(alt_scores), 10) + self.assertEqual(len(alt_scores), 10) for idx in range(len(alt_scores)): self.assertGreaterEqual(alt_scores[idx], 0) self.assertLessEqual(alt_scores[idx], 1) @@ -551,8 +551,8 @@ def test_initialize_model_from_run(self): openml.flows.assert_flows_equal(flowR, flowL) openml.flows.assert_flows_equal(flowS, flowL) - self.assertEquals(flowS.components['Imputer'].parameters['strategy'], '"median"') - self.assertEquals(flowS.components['VarianceThreshold'].parameters['threshold'], '0.05') + self.assertEqual(flowS.components['Imputer'].parameters['strategy'], '"median"') + self.assertEqual(flowS.components['VarianceThreshold'].parameters['threshold'], '0.05') def test_get_run_trace(self): # get_run_trace is already tested implicitly in test_run_and_publish @@ -575,7 +575,7 @@ def test_get_run_trace(self): # in case the run did not exists yet run = openml.runs.run_model_on_task(task, clf, avoid_duplicate_runs=True) trace = openml.runs.functions._create_trace_from_arff(run._generate_trace_arff_dict()) - self.assertEquals( + self.assertEqual( len(trace.trace_iterations), num_iterations * num_folds, ) @@ -702,9 +702,9 @@ def test__extract_arfftrace(self): trace_attribute_list = _extract_arfftrace_attributes(clf) trace_list = _extract_arfftrace(clf, 0, 0) self.assertIsInstance(trace_attribute_list, list) - self.assertEquals(len(trace_attribute_list), 5 + len(param_grid)) + self.assertEqual(len(trace_attribute_list), 5 + len(param_grid)) self.assertIsInstance(trace_list, list) - self.assertEquals(len(trace_list), num_iters) + self.assertEqual(len(trace_list), num_iters) # found parameters optimized_params = set() @@ -869,7 +869,7 @@ def test__run_model_on_fold(self): self.assertIsInstance(arff_datacontent, list) # trace. SGD does not produce any self.assertIsInstance(arff_tracecontent, list) - self.assertEquals(len(arff_tracecontent), 0) + self.assertEqual(len(arff_tracecontent), 0) fold_evaluations = collections.defaultdict(lambda: collections.defaultdict(dict)) for measure in user_defined_measures: From 89935c05402287d3a6f447f79fce0f1ce452eb62 Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Wed, 12 Sep 2018 12:04:33 -0400 Subject: [PATCH 07/18] small update fixing doc strings --- openml/runs/functions.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/openml/runs/functions.py b/openml/runs/functions.py index d382eac54a..3ecec7b5f6 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -187,24 +187,24 @@ def _publish_flow_if_necessary(flow): def get_run_trace(run_id): - """Get the optimization trace object for a given run id. + """ + Get the optimization trace object for a given run id. - Parameters - ---------- - run_id : int + Parameters + ---------- + run_id : int - Returns - ------- - openml.runs.OpenMLTrace + Returns + ------- + openml.runs.OpenMLTrace """ - trace_xml = openml._api_calls._perform_api_call('run/trace/%d' % run_id) run_trace = _create_trace_from_description(trace_xml) return run_trace def initialize_model_from_run(run_id): - ''' + """ Initialized a model based on a run_id (i.e., using the exact same parameter settings) @@ -217,7 +217,7 @@ def initialize_model_from_run(run_id): ------- model : sklearn model the scikitlearn model with all parameters initailized - ''' + """ run = get_run(run_id) return initialize_model(run.setup_id) From 51857cd897824359c0d4b985355595535a5cc271 Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Thu, 13 Sep 2018 11:41:20 -0400 Subject: [PATCH 08/18] added columntransformer fix --- openml/flows/sklearn_converter.py | 15 +++++++++--- tests/test_flows/test_sklearn.py | 38 +++++++++++++++++++++++-------- 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/openml/flows/sklearn_converter.py b/openml/flows/sklearn_converter.py index 13ed316436..5343f35264 100644 --- a/openml/flows/sklearn_converter.py +++ b/openml/flows/sklearn_converter.py @@ -305,15 +305,22 @@ 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([type(rval[0]) == type(rval[i]) for i in range(len(rval))])): # 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 + raise ValueError('Length of tuple does not match assumptions') + if not isinstance(sub_component, OpenMLFlow): + raise ValueError('Second item of tuple does not match assumptions') if identifier in reserved_keywords: parent_model_name = model.__module__ + "." + \ @@ -342,6 +349,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['param_1'] = sub_component_tuple[2] component_reference['value'] = cr_value parameter_value.append(component_reference) @@ -420,7 +429,7 @@ def _get_fn_arguments_with_defaults(fn_name): def _deserialize_model(flow, keep_defaults): model_name = flow.class_name - _check_dependencies(flow.dependencies) + #_check_dependencies(flow.dependencies) parameters = flow.parameters components = flow.components diff --git a/tests/test_flows/test_sklearn.py b/tests/test_flows/test_sklearn.py index 33454b24ad..aeb9920cec 100644 --- a/tests/test_flows/test_sklearn.py +++ b/tests/test_flows/test_sklearn.py @@ -14,6 +14,7 @@ import scipy.optimize import scipy.stats import sklearn.base +import sklearn.compose import sklearn.datasets import sklearn.decomposition import sklearn.dummy @@ -102,7 +103,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() @@ -142,7 +142,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()) @@ -190,8 +189,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,' \ @@ -248,8 +247,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,' \ @@ -303,12 +302,32 @@ def test_serialize_pipeline_clustering(self): self.assertEqual(new_model_params, fu_params) new_model.fit(self.X, self.y) + def test_serialize_column_transformer(self): + 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_name = 'sklearn.compose.ColumnTransformer(' \ + 'numeric=sklearn.preprocessing.StandardScaler,' \ + 'nominal=sklearn.preprocessing.OneHotEncoder)' + 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 = sklearn.preprocessing.OneHotEncoder(sparse=False) scaler = sklearn.preprocessing.StandardScaler() fu = sklearn.pipeline.FeatureUnion(transformer_list=[('ohe', ohe), ('scaler', scaler)]) - serialization = sklearn_to_flow(fu) + serialization = sklearn_to_flow(fu) self.assertEqual(serialization.name, 'sklearn.pipeline.FeatureUnion(' 'ohe=sklearn.preprocessing.data.OneHotEncoder,' @@ -376,8 +395,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), 'base_estimator__max_depth': scipy.stats.randint(1, @@ -658,7 +677,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 = [ From fcdaa2b6552802c0dafcc53c2c5537e382265892 Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Thu, 13 Sep 2018 12:06:28 -0400 Subject: [PATCH 09/18] readded dependency check --- openml/flows/sklearn_converter.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openml/flows/sklearn_converter.py b/openml/flows/sklearn_converter.py index 5343f35264..4208a89e52 100644 --- a/openml/flows/sklearn_converter.py +++ b/openml/flows/sklearn_converter.py @@ -429,7 +429,7 @@ def _get_fn_arguments_with_defaults(fn_name): def _deserialize_model(flow, keep_defaults): model_name = flow.class_name - #_check_dependencies(flow.dependencies) + _check_dependencies(flow.dependencies) parameters = flow.parameters components = flow.components From 49cc83f61ebb87f6af9e3b8e6705b2b3fa1379fd Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Thu, 13 Sep 2018 13:16:22 -0400 Subject: [PATCH 10/18] added deserialization to column_transformer --- openml/flows/sklearn_converter.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/openml/flows/sklearn_converter.py b/openml/flows/sklearn_converter.py index 4208a89e52..6051b320e7 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 'param_1' not in value: rval = (step_name, component) + else: + rval = (step_name, component, value['param_1']) elif serialized_type == 'cv_object': rval = _deserialize_cross_validator(value) else: From 6071e389454b46b5cb608c6bb980eb155d3eb705 Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Fri, 21 Sep 2018 07:13:37 -0400 Subject: [PATCH 11/18] fixes unit tests --- openml/flows/sklearn_converter.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/openml/flows/sklearn_converter.py b/openml/flows/sklearn_converter.py index 364940ea9f..32349e09cf 100644 --- a/openml/flows/sklearn_converter.py +++ b/openml/flows/sklearn_converter.py @@ -321,8 +321,9 @@ def _extract_information_from_model(model): # length 2 is for {VotingClassifier.estimators, Pipeline.steps, FeatureUnion.transformer_list} # length 3 is for ColumnTransformer raise ValueError('Length of tuple does not match assumptions') - if not isinstance(sub_component, OpenMLFlow): - raise ValueError('Second item of tuple does not match assumptions') + if not isinstance(sub_component, (OpenMLFlow, type(None))): + raise ValueError('Second item of tuple does not match assumptions. '\ + 'Expected OpenMLFlow, got %s' % type(sub_component)) if identifier in reserved_keywords: parent_model_name = model.__module__ + "." + \ From 35818976c2162a35b0eff15dcfec0c890c18717f Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Fri, 21 Sep 2018 07:13:58 -0400 Subject: [PATCH 12/18] extended unit tests --- tests/test_flows/test_sklearn.py | 41 ++++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/tests/test_flows/test_sklearn.py b/tests/test_flows/test_sklearn.py index d1f21c7198..b6c7f09f0d 100644 --- a/tests/test_flows/test_sklearn.py +++ b/tests/test_flows/test_sklearn.py @@ -14,7 +14,6 @@ import scipy.optimize import scipy.stats import sklearn.base -import sklearn.compose import sklearn.datasets import sklearn.decomposition import sklearn.dummy @@ -27,6 +26,7 @@ import sklearn.preprocessing import sklearn.tree import sklearn.cluster +import pytest if LooseVersion(sklearn.__version__) < "0.20": from sklearn.preprocessing import Imputer @@ -348,15 +348,48 @@ def test_serialize_pipeline_clustering(self): self.assertEqual(new_model_params, fu_params) new_model.fit(self.X, self.y) + @pytest.mark.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_name = 'sklearn.compose.ColumnTransformer(' \ - 'numeric=sklearn.preprocessing.StandardScaler,' \ - 'nominal=sklearn.preprocessing.OneHotEncoder)' + fixture_name = '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_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) + + @pytest.mark.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) From 6b87679b6bb757fdc81237f94d5cc8fe49c15702 Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Fri, 21 Sep 2018 07:27:23 -0400 Subject: [PATCH 13/18] additional unit test --- openml/runs/run.py | 4 +++- tests/test_runs/test_run_functions.py | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/openml/runs/run.py b/openml/runs/run.py index 598dbeb48b..7b720e08b0 100644 --- a/openml/runs/run.py +++ b/openml/runs/run.py @@ -442,7 +442,9 @@ 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: + for _temp_step in _tmp: + step_name = _temp_step[0] + step = _temp_step[1] if isinstance(step_name, openml.flows.OpenMLFlow): raise e elif not isinstance(step, openml.flows.OpenMLFlow): diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index e01002f29f..24f42beb34 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 pytest from openml.testing import TestBase from openml.runs.functions import _run_task_get_arffcontent, \ @@ -354,6 +356,20 @@ def test_run_and_upload_pipeline_dummy_pipeline(self): ('dummy', DummyClassifier(strategy='prior'))]) self._run_and_upload(pipeline1, '62501') + @pytest.mark.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()), From 7b4de6eb60e1d4deb2ae49b8b24fcde84d71f1f4 Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Fri, 21 Sep 2018 08:05:36 -0400 Subject: [PATCH 14/18] pep8 --- tests/test_runs/test_run_functions.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index 24f42beb34..2c0b936871 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -363,7 +363,8 @@ def test_run_and_upload_column_transformer_pipeline(self): inner = sklearn.compose.ColumnTransformer( transformers=[ ('numeric', sklearn.preprocessing.StandardScaler(), [0, 1, 2]), - ('nominal', sklearn.preprocessing.OneHotEncoder(handle_unknown='ignore'), [3, 4, 5])], + ('nominal', sklearn.preprocessing.OneHotEncoder( + handle_unknown='ignore'), [3, 4, 5])], remainder='passthrough') pipeline = sklearn.pipeline.Pipeline( steps=[('transformer', inner), From c1b4278f9f8edb2bffad0f20fb88fcbeaae2b448 Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Thu, 27 Sep 2018 11:10:35 -0400 Subject: [PATCH 15/18] PEP8 fixes --- openml/flows/sklearn_converter.py | 23 +++++++++----- tests/test_flows/test_sklearn.py | 53 +++++++++++++++++-------------- 2 files changed, 45 insertions(+), 31 deletions(-) diff --git a/openml/flows/sklearn_converter.py b/openml/flows/sklearn_converter.py index 32349e09cf..4075f2c345 100644 --- a/openml/flows/sklearn_converter.py +++ b/openml/flows/sklearn_converter.py @@ -307,9 +307,11 @@ def _extract_information_from_model(model): if (isinstance(rval, (list, tuple)) and len(rval) > 0 and isinstance(rval[0], (list, tuple)) and - all([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()) @@ -318,18 +320,23 @@ def _extract_information_from_model(model): 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 2 is for {VotingClassifier.estimators, + # Pipeline.steps, FeatureUnion.transformer_list} # length 3 is for ColumnTransformer - raise ValueError('Length of tuple does not match assumptions') + msg = 'Length of tuple does not match assumptions' + raise ValueError(msg) if not isinstance(sub_component, (OpenMLFlow, type(None))): - raise ValueError('Second item of tuple does not match assumptions. '\ - 'Expected OpenMLFlow, got %s' % type(sub_component)) + msg = 'Second item of tuple does not match assumptions. '\ + 'Expected OpenMLFlow, got %s' % type(sub_component) + raise ValueError(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 diff --git a/tests/test_flows/test_sklearn.py b/tests/test_flows/test_sklearn.py index b6c7f09f0d..b651c3ab57 100644 --- a/tests/test_flows/test_sklearn.py +++ b/tests/test_flows/test_sklearn.py @@ -1,5 +1,6 @@ import json import os +import pytest import sys import unittest from distutils.version import LooseVersion @@ -26,7 +27,6 @@ import sklearn.preprocessing import sklearn.tree import sklearn.cluster -import pytest if LooseVersion(sklearn.__version__) < "0.20": from sklearn.preprocessing import Imputer @@ -356,14 +356,15 @@ def test_serialize_column_transformer(self): model = sklearn.compose.ColumnTransformer( transformers=[ ('numeric', sklearn.preprocessing.StandardScaler(), [0, 1, 2]), - ('nominal', sklearn.preprocessing.OneHotEncoder(handle_unknown='ignore'), [3, 4, 5])], + ('nominal', sklearn.preprocessing.OneHotEncoder( + handle_unknown='ignore'), [3, 4, 5])], remainder='passthrough') - fixture_name = 'sklearn.compose._column_transformer.ColumnTransformer(' \ - 'numeric=sklearn.preprocessing.data.StandardScaler,' \ - 'nominal=sklearn.preprocessing._encoders.OneHotEncoder)' + 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_name) + self.assertEqual(serialization.name, fixture) self.assertEqual(serialization.description, fixture_description) # del serialization.model new_model = flow_to_sklearn(serialization) @@ -380,15 +381,20 @@ def test_serialize_column_transformer_pipeline(self): inner = sklearn.compose.ColumnTransformer( transformers=[ ('numeric', sklearn.preprocessing.StandardScaler(), [0, 1, 2]), - ('nominal', sklearn.preprocessing.OneHotEncoder(handle_unknown='ignore'), [3, 4, 5])], + ('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)' + 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) @@ -496,8 +502,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), @@ -510,13 +516,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 From 5c7f27f1df23c2bf16e5e52c59a493f09aa229a2 Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Fri, 28 Sep 2018 04:46:25 -0400 Subject: [PATCH 16/18] pep8 --- tests/test_flows/test_sklearn.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/test_flows/test_sklearn.py b/tests/test_flows/test_sklearn.py index b651c3ab57..71a832c98a 100644 --- a/tests/test_flows/test_sklearn.py +++ b/tests/test_flows/test_sklearn.py @@ -386,8 +386,7 @@ def test_serialize_column_transformer_pipeline(self): remainder='passthrough') model = sklearn.pipeline.Pipeline( steps=[('transformer', inner), - ('classifier', sklearn.tree.DecisionTreeClassifier()) - ]) + ('classifier', sklearn.tree.DecisionTreeClassifier())]) fixture_name = \ 'sklearn.pipeline.Pipeline('\ 'transformer=sklearn.compose._column_transformer.'\ From 6082498abd287a3c0269f09d94b3fed09b3702f7 Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Fri, 28 Sep 2018 07:36:10 -0400 Subject: [PATCH 17/18] comments from Matthias F --- openml/flows/sklearn_converter.py | 8 ++++---- openml/runs/run.py | 7 +++++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/openml/flows/sklearn_converter.py b/openml/flows/sklearn_converter.py index 4075f2c345..82b5895fa1 100644 --- a/openml/flows/sklearn_converter.py +++ b/openml/flows/sklearn_converter.py @@ -150,10 +150,10 @@ def flow_to_sklearn(o, components=None, initialize_with_defaults=False): del components[key] if step_name is None: rval = component - elif 'param_1' not in value: + elif 'argument_1' not in value: rval = (step_name, component) else: - rval = (step_name, component, value['param_1']) + rval = (step_name, component, value['argument_1']) elif serialized_type == 'cv_object': rval = _deserialize_cross_validator(value) else: @@ -328,7 +328,7 @@ def _extract_information_from_model(model): 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 ValueError(msg) + raise TypeError(msg) if identifier in reserved_keywords: parent_model_name = model.__module__ + "." + \ @@ -360,7 +360,7 @@ def _extract_information_from_model(model): cr_value['key'] = identifier cr_value['step_name'] = identifier if len(sub_component_tuple) == 3: - cr_value['param_1'] = sub_component_tuple[2] + 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 9c9df6089f..9966d80e7b 100644 --- a/openml/runs/run.py +++ b/openml/runs/run.py @@ -445,10 +445,13 @@ def extract_parameters(_flow, _flow_dict, component_model, for _temp_step in _tmp: step_name = _temp_step[0] step = _temp_step[1] - if isinstance(step_name, openml.flows.OpenMLFlow): + 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 From 04279d59450d71d9dbdb973c5214f3bd4aa0d53b Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Fri, 28 Sep 2018 07:40:02 -0400 Subject: [PATCH 18/18] replaced pytest by unittest --- tests/test_flows/test_sklearn.py | 9 ++++----- tests/test_runs/test_run_functions.py | 6 +++--- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/tests/test_flows/test_sklearn.py b/tests/test_flows/test_sklearn.py index 71a832c98a..b4cf524b7e 100644 --- a/tests/test_flows/test_sklearn.py +++ b/tests/test_flows/test_sklearn.py @@ -1,6 +1,5 @@ import json import os -import pytest import sys import unittest from distutils.version import LooseVersion @@ -348,8 +347,8 @@ def test_serialize_pipeline_clustering(self): self.assertEqual(new_model_params, fu_params) new_model.fit(self.X, self.y) - @pytest.mark.skipif(LooseVersion(sklearn.__version__) < "0.20", - reason="columntransformer introduction in 0.20.0") + @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 @@ -373,8 +372,8 @@ def test_serialize_column_transformer(self): serialization2 = sklearn_to_flow(new_model) assert_flows_equal(serialization, serialization2) - @pytest.mark.skipif(LooseVersion(sklearn.__version__) < "0.20", - reason="columntransformer introduction in 0.20.0") + @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 diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index 2c0b936871..8a5138b22a 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -13,7 +13,7 @@ import openml.exceptions import openml._api_calls import sklearn -import pytest +import unittest from openml.testing import TestBase from openml.runs.functions import _run_task_get_arffcontent, \ @@ -356,8 +356,8 @@ def test_run_and_upload_pipeline_dummy_pipeline(self): ('dummy', DummyClassifier(strategy='prior'))]) self._run_and_upload(pipeline1, '62501') - @pytest.mark.skipif(LooseVersion(sklearn.__version__) < "0.20", - reason="columntransformer introduction in 0.20.0") + @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(