From 6d13a757294a99688d6c441fc9c3ecb7303b6d01 Mon Sep 17 00:00:00 2001 From: Jan van Rijn Date: Fri, 21 Apr 2017 15:37:01 +0200 Subject: [PATCH 1/5] model is paralizable --- openml/flows/__init__.py | 4 ++-- openml/flows/sklearn_converter.py | 27 +++++++++++++++++++++++++++ openml/runs/functions.py | 11 ++++++----- tests/test_flows/test_sklearn.py | 18 +++++++++++++++++- 4 files changed, 52 insertions(+), 8 deletions(-) diff --git a/openml/flows/__init__.py b/openml/flows/__init__.py index 42bd667c33..66d7e15a53 100644 --- a/openml/flows/__init__.py +++ b/openml/flows/__init__.py @@ -1,6 +1,6 @@ from .flow import OpenMLFlow -from .sklearn_converter import sklearn_to_flow, flow_to_sklearn +from .sklearn_converter import sklearn_to_flow, flow_to_sklearn, model_is_paralizable from .functions import get_flow, list_flows, flow_exists __all__ = ['OpenMLFlow', 'create_flow_from_model', 'get_flow', 'list_flows', - 'sklearn_to_flow', 'flow_to_sklearn', 'flow_exists'] + 'sklearn_to_flow', 'flow_to_sklearn', 'flow_exists', 'model_is_paralizable'] diff --git a/openml/flows/sklearn_converter.py b/openml/flows/sklearn_converter.py index 8f39370492..6f2e9a8f65 100644 --- a/openml/flows/sklearn_converter.py +++ b/openml/flows/sklearn_converter.py @@ -536,6 +536,33 @@ def _serialize_cross_validator(o): return ret +def model_is_paralizable(model): + def check(param_dict): + for param, value in param_dict.items(): + # n_jobs is scikitlearn parameter for paralizing jobs + if 'n_jobs' in param.split('__')[-1]: + # 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: + return False + return True + + if not (isinstance(model, sklearn.base.BaseEstimator) or + isinstance(model, sklearn.model_selection._search.BaseSearchCV)): + raise ValueError('model should be BaseEstimator or BaseSearchCV') + + # check the parameters for n_jobs + if check(model.get_params()) == False: + return False + + # check if the njobs is not in the optimization trace + # this would be error by the user, so we can throw it as a courtesy + if isinstance(model, sklearn.model_selection._search.BaseSearchCV): + if check(model.get_params()) == False: + raise PyOpenMLError('openml-python should not be used to ' + 'optimize the n_jobs parameter.') + return True def _deserialize_cross_validator(value, **kwargs): model_name = value['name'] diff --git a/openml/runs/functions.py b/openml/runs/functions.py index 9cb08d7e54..5ebd70633b 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -10,7 +10,7 @@ from ..exceptions import PyOpenMLError from .. import config -from ..flows import sklearn_to_flow, get_flow, flow_exists +from ..flows import sklearn_to_flow, get_flow, flow_exists, model_is_paralizable from ..setups import setup_exists from ..exceptions import OpenMLCacheException, OpenMLServerException from ..util import URLError, version_complies @@ -160,6 +160,7 @@ def _run_task_get_arffcontent(model, task, class_labels): user_defined_measures = defaultdict(lambda: defaultdict(dict)) rep_no = 0 + can_measure_runtime = version_complies(3, 3) and model_is_paralizable(model) # TODO use different iterator to only provide a single iterator (less # methods, less maintenance, less confusion) for rep in task.iterate_repeats(): @@ -174,11 +175,11 @@ def _run_task_get_arffcontent(model, task, class_labels): try: # for measuring runtime. Only available since Python 3.3 - if version_complies(3, 3): + if can_measure_runtime: modelfit_starttime = time.process_time() model_fold.fit(trainX, trainY) - if version_complies(3, 3): + if can_measure_runtime: modelfit_duration = (time.process_time() - modelfit_starttime) * 1000 user_defined_measures['usercpu_time_millis_training'][rep_no][fold_no] = modelfit_duration except AttributeError as e: @@ -192,12 +193,12 @@ def _run_task_get_arffcontent(model, task, class_labels): else: model_classes = model_fold.classes_ - if version_complies(3, 3): + if can_measure_runtime: modelpredict_starttime = time.process_time() ProbaY = model_fold.predict_proba(testX) PredY = model_fold.predict(testX) - if version_complies(3, 3): + if can_measure_runtime: modelpredict_duration = (time.process_time() - modelpredict_starttime) * 1000 user_defined_measures['usercpu_time_millis_testing'][rep_no][fold_no] = modelpredict_duration user_defined_measures['usercpu_time_millis'][rep_no][fold_no] = modelfit_duration + modelpredict_duration diff --git a/tests/test_flows/test_sklearn.py b/tests/test_flows/test_sklearn.py index 39f8eff4b9..324f83a42b 100644 --- a/tests/test_flows/test_sklearn.py +++ b/tests/test_flows/test_sklearn.py @@ -25,7 +25,8 @@ import sklearn.tree from openml.flows import OpenMLFlow, sklearn_to_flow, flow_to_sklearn -from openml.flows.sklearn_converter import _format_external_version, _check_dependencies +from openml.flows.sklearn_converter import _format_external_version, \ + _check_dependencies, model_is_paralizable from openml.exceptions import PyOpenMLError this_directory = os.path.dirname(os.path.abspath(__file__)) @@ -555,3 +556,18 @@ def test_illegal_parameter_names_featureunion(self): ('OneHotEncoder', sklearn.preprocessing.OneHotEncoder(sparse=False, handle_unknown='ignore')) ] self.assertRaises(ValueError, sklearn.pipeline.FeatureUnion, transformer_list=transformer_list) + + def test_paralizable_check(self): + models = [ + 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))]) + ] + + answers = [True, False, False, True, False, False] + + for i in range(len(models)): + assert(model_is_paralizable(models[i]) == answers[i]) \ No newline at end of file From 2ab8b2b2089e073a62073c2559d91b87a0017aa4 Mon Sep 17 00:00:00 2001 From: Jan van Rijn Date: Fri, 21 Apr 2017 15:42:34 +0200 Subject: [PATCH 2/5] changed name of function --- openml/flows/__init__.py | 2 +- openml/flows/sklearn_converter.py | 6 +++++- openml/runs/functions.py | 4 ++-- tests/test_flows/test_sklearn.py | 4 ++-- 4 files changed, 10 insertions(+), 6 deletions(-) diff --git a/openml/flows/__init__.py b/openml/flows/__init__.py index 66d7e15a53..4066458f75 100644 --- a/openml/flows/__init__.py +++ b/openml/flows/__init__.py @@ -1,5 +1,5 @@ from .flow import OpenMLFlow -from .sklearn_converter import sklearn_to_flow, flow_to_sklearn, model_is_paralizable +from .sklearn_converter import sklearn_to_flow, flow_to_sklearn, model_single_core from .functions import get_flow, list_flows, flow_exists __all__ = ['OpenMLFlow', 'create_flow_from_model', 'get_flow', 'list_flows', diff --git a/openml/flows/sklearn_converter.py b/openml/flows/sklearn_converter.py index 6f2e9a8f65..5c6ec54d2a 100644 --- a/openml/flows/sklearn_converter.py +++ b/openml/flows/sklearn_converter.py @@ -536,7 +536,11 @@ def _serialize_cross_validator(o): return ret -def model_is_paralizable(model): +def model_single_core(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): for param, value in param_dict.items(): # n_jobs is scikitlearn parameter for paralizing jobs diff --git a/openml/runs/functions.py b/openml/runs/functions.py index 5ebd70633b..51cf34c1fd 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -10,7 +10,7 @@ from ..exceptions import PyOpenMLError from .. import config -from ..flows import sklearn_to_flow, get_flow, flow_exists, model_is_paralizable +from ..flows import sklearn_to_flow, get_flow, flow_exists, model_single_core from ..setups import setup_exists from ..exceptions import OpenMLCacheException, OpenMLServerException from ..util import URLError, version_complies @@ -160,7 +160,7 @@ def _run_task_get_arffcontent(model, task, class_labels): user_defined_measures = defaultdict(lambda: defaultdict(dict)) rep_no = 0 - can_measure_runtime = version_complies(3, 3) and model_is_paralizable(model) + can_measure_runtime = version_complies(3, 3) and model_single_core(model) # TODO use different iterator to only provide a single iterator (less # methods, less maintenance, less confusion) for rep in task.iterate_repeats(): diff --git a/tests/test_flows/test_sklearn.py b/tests/test_flows/test_sklearn.py index 324f83a42b..9b7dc2d6b3 100644 --- a/tests/test_flows/test_sklearn.py +++ b/tests/test_flows/test_sklearn.py @@ -26,7 +26,7 @@ from openml.flows import OpenMLFlow, sklearn_to_flow, flow_to_sklearn from openml.flows.sklearn_converter import _format_external_version, \ - _check_dependencies, model_is_paralizable + _check_dependencies, model_single_core from openml.exceptions import PyOpenMLError this_directory = os.path.dirname(os.path.abspath(__file__)) @@ -570,4 +570,4 @@ def test_paralizable_check(self): answers = [True, False, False, True, False, False] for i in range(len(models)): - assert(model_is_paralizable(models[i]) == answers[i]) \ No newline at end of file + assert(model_single_core(models[i]) == answers[i]) \ No newline at end of file From 55be0a8728bad16b6c3008ec7f2590d93198514f Mon Sep 17 00:00:00 2001 From: Jan van Rijn Date: Fri, 21 Apr 2017 16:10:49 +0200 Subject: [PATCH 3/5] coverage increase --- openml/flows/sklearn_converter.py | 17 +++++++++-------- tests/test_flows/test_sklearn.py | 24 +++++++++++++++++++----- 2 files changed, 28 insertions(+), 13 deletions(-) diff --git a/openml/flows/sklearn_converter.py b/openml/flows/sklearn_converter.py index 5c6ec54d2a..5ab11969a5 100644 --- a/openml/flows/sklearn_converter.py +++ b/openml/flows/sklearn_converter.py @@ -541,14 +541,14 @@ def model_single_core(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): + def check(param_dict, disallow_parameter=False): for param, value in param_dict.items(): # n_jobs is scikitlearn parameter for paralizing jobs - if 'n_jobs' in param.split('__')[-1]: + 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: + if value != 1 or disallow_parameter: return False return True @@ -556,16 +556,17 @@ def check(param_dict): isinstance(model, sklearn.model_selection._search.BaseSearchCV)): raise ValueError('model should be BaseEstimator or BaseSearchCV') - # check the parameters for n_jobs - if check(model.get_params()) == False: - return False - # check if the njobs is not in the optimization trace # this would be error by the user, so we can throw it as a courtesy if isinstance(model, sklearn.model_selection._search.BaseSearchCV): - if check(model.get_params()) == False: + if not check( model.param_grid, True): raise PyOpenMLError('openml-python should not be used to ' 'optimize the n_jobs parameter.') + + # check the parameters for n_jobs + if check(model.get_params(), False) == False: + return False + return True def _deserialize_cross_validator(value, **kwargs): diff --git a/tests/test_flows/test_sklearn.py b/tests/test_flows/test_sklearn.py index 9b7dc2d6b3..0c978aaee0 100644 --- a/tests/test_flows/test_sklearn.py +++ b/tests/test_flows/test_sklearn.py @@ -558,16 +558,30 @@ def test_illegal_parameter_names_featureunion(self): self.assertRaises(ValueError, sklearn.pipeline.FeatureUnion, transformer_list=transformer_list) def test_paralizable_check(self): - models = [ + singlecore_bagging = sklearn.ensemble.BaggingClassifier() + multicore_bagging = sklearn.ensemble.BaggingClassifier(n_jobs=5) + illegal_param_dist = {"base__n_jobs": [-1, 0, 1] } + legal_param_dist = {"base__max_depth": [2, 3, 4]} + + legal_models = [ 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.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) ] - answers = [True, False, False, True, False, False] + answers = [True, False, False, True, False, False, True, False] + + for i in range(len(legal_models)): + self.assertTrue(model_single_core(legal_models[i]) == answers[i]) - for i in range(len(models)): - assert(model_single_core(models[i]) == answers[i]) \ No newline at end of file + for i in range(len(illegal_models)): + self.assertRaises(PyOpenMLError, model_single_core, illegal_models[i]) \ No newline at end of file From 989055565420cd0be3c191d81847c7080512ef70 Mon Sep 17 00:00:00 2001 From: Jan van Rijn Date: Fri, 21 Apr 2017 16:58:53 +0200 Subject: [PATCH 4/5] param distributions --- openml/flows/sklearn_converter.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/openml/flows/sklearn_converter.py b/openml/flows/sklearn_converter.py index 5ab11969a5..5a7c8b71f1 100644 --- a/openml/flows/sklearn_converter.py +++ b/openml/flows/sklearn_converter.py @@ -559,7 +559,18 @@ def check(param_dict, disallow_parameter=False): # check if the njobs is not in the optimization trace # this would be error by the user, so we can throw it as a courtesy if isinstance(model, sklearn.model_selection._search.BaseSearchCV): - if not check( model.param_grid, True): + param_distributions = None + if isinstance(model, sklearn.model_selection.GridSearchCV): + param_distributions = model.param_grid + elif isinstance(model, sklearn.model_selection.RandomizedSearchCV): + param_distributions = model.param_distributions + else: + print('Warning! Using subclass BaseSearchCV other than ' \ + '{GridSearchCV, RandomizedSearchCV}. Should implement param check. ') + pass + + + if not check(param_distributions, True): raise PyOpenMLError('openml-python should not be used to ' 'optimize the n_jobs parameter.') From 7d8fa4d2c252d02cc9d08651ff15231ae927b660 Mon Sep 17 00:00:00 2001 From: Jan van Rijn Date: Tue, 25 Apr 2017 16:10:13 +0200 Subject: [PATCH 5/5] changes requested my @mfeurer --- openml/flows/__init__.py | 4 ++-- openml/flows/sklearn_converter.py | 11 +++-------- openml/runs/functions.py | 4 ++-- tests/test_flows/test_sklearn.py | 10 +++++++--- 4 files changed, 14 insertions(+), 15 deletions(-) diff --git a/openml/flows/__init__.py b/openml/flows/__init__.py index 4066458f75..3b36fdef40 100644 --- a/openml/flows/__init__.py +++ b/openml/flows/__init__.py @@ -1,6 +1,6 @@ from .flow import OpenMLFlow -from .sklearn_converter import sklearn_to_flow, flow_to_sklearn, model_single_core +from .sklearn_converter import sklearn_to_flow, flow_to_sklearn, _check_n_jobs from .functions import get_flow, list_flows, flow_exists __all__ = ['OpenMLFlow', 'create_flow_from_model', 'get_flow', 'list_flows', - 'sklearn_to_flow', 'flow_to_sklearn', 'flow_exists', 'model_is_paralizable'] + 'sklearn_to_flow', 'flow_to_sklearn', 'flow_exists'] diff --git a/openml/flows/sklearn_converter.py b/openml/flows/sklearn_converter.py index 5a7c8b71f1..05b40949f7 100644 --- a/openml/flows/sklearn_converter.py +++ b/openml/flows/sklearn_converter.py @@ -536,7 +536,7 @@ def _serialize_cross_validator(o): return ret -def model_single_core(model): +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) @@ -556,8 +556,7 @@ def check(param_dict, disallow_parameter=False): isinstance(model, sklearn.model_selection._search.BaseSearchCV)): raise ValueError('model should be BaseEstimator or BaseSearchCV') - # check if the njobs is not in the optimization trace - # this would be error by the user, so we can throw it as a courtesy + # 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): @@ -569,16 +568,12 @@ def check(param_dict, disallow_parameter=False): '{GridSearchCV, RandomizedSearchCV}. Should implement param check. ') pass - if not check(param_distributions, True): raise PyOpenMLError('openml-python should not be used to ' 'optimize the n_jobs parameter.') # check the parameters for n_jobs - if check(model.get_params(), False) == False: - return False - - return True + return check(model.get_params(), False) def _deserialize_cross_validator(value, **kwargs): model_name = value['name'] diff --git a/openml/runs/functions.py b/openml/runs/functions.py index 51cf34c1fd..e2d26107c8 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -10,7 +10,7 @@ from ..exceptions import PyOpenMLError from .. import config -from ..flows import sklearn_to_flow, get_flow, flow_exists, model_single_core +from ..flows import sklearn_to_flow, get_flow, flow_exists, _check_n_jobs from ..setups import setup_exists from ..exceptions import OpenMLCacheException, OpenMLServerException from ..util import URLError, version_complies @@ -160,7 +160,7 @@ def _run_task_get_arffcontent(model, task, class_labels): user_defined_measures = defaultdict(lambda: defaultdict(dict)) rep_no = 0 - can_measure_runtime = version_complies(3, 3) and model_single_core(model) + can_measure_runtime = version_complies(3, 3) and _check_n_jobs(model) # TODO use different iterator to only provide a single iterator (less # methods, less maintenance, less confusion) for rep in task.iterate_repeats(): diff --git a/tests/test_flows/test_sklearn.py b/tests/test_flows/test_sklearn.py index 0c978aaee0..125b359b12 100644 --- a/tests/test_flows/test_sklearn.py +++ b/tests/test_flows/test_sklearn.py @@ -26,7 +26,7 @@ from openml.flows import OpenMLFlow, sklearn_to_flow, flow_to_sklearn from openml.flows.sklearn_converter import _format_external_version, \ - _check_dependencies, model_single_core + _check_dependencies, _check_n_jobs from openml.exceptions import PyOpenMLError this_directory = os.path.dirname(os.path.abspath(__file__)) @@ -558,9 +558,13 @@ def test_illegal_parameter_names_featureunion(self): 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) 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] } + # using this param distribution should not raise an exception legal_param_dist = {"base__max_depth": [2, 3, 4]} legal_models = [ @@ -581,7 +585,7 @@ def test_paralizable_check(self): answers = [True, False, False, True, False, False, True, False] for i in range(len(legal_models)): - self.assertTrue(model_single_core(legal_models[i]) == answers[i]) + self.assertTrue(_check_n_jobs(legal_models[i]) == answers[i]) for i in range(len(illegal_models)): - self.assertRaises(PyOpenMLError, model_single_core, illegal_models[i]) \ No newline at end of file + self.assertRaises(PyOpenMLError, _check_n_jobs, illegal_models[i]) \ No newline at end of file