From d9c673e8a0fbfada5dbf4533acca825c957f44e8 Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Tue, 19 Jun 2018 13:21:41 +0200 Subject: [PATCH 1/6] ADD unit test for issue #422 --- openml/runs/functions.py | 54 ++++++++++++++++++++++++------------- openml/runs/run.py | 28 ++++++++++++------- tests/test_runs/test_run.py | 46 ++++++++++++++++++++++++++----- 3 files changed, 92 insertions(+), 36 deletions(-) diff --git a/openml/runs/functions.py b/openml/runs/functions.py index a7f51ea4ce..ad5314e994 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -2,7 +2,6 @@ import io import json import os -import shutil import sys import time import warnings @@ -16,7 +15,7 @@ import openml import openml.utils import openml._api_calls -from ..exceptions import PyOpenMLError, OpenMLServerNoResult +from ..exceptions import PyOpenMLError from .. import config from ..flows import sklearn_to_flow, get_flow, flow_exists, _check_n_jobs, \ _copy_server_fields, OpenMLFlow @@ -405,11 +404,11 @@ def _prediction_to_probabilities(y, model_classes): # this information is multiple times overwritten, but due to the ordering # of tne loops, eventually it contains the information based on the full # dataset size - user_defined_measures_per_fold = collections.defaultdict(lambda: collections.defaultdict(dict)) + user_defined_measures_per_fold = collections.OrderedDict() # stores sample-based evaluation measures (sublevel of fold-based) # will also be filled on a non sample-based task, but the information # is the same as the fold-based measures, and disregarded in that case - user_defined_measures_per_sample = collections.defaultdict(lambda: collections.defaultdict(lambda: collections.defaultdict(dict))) + user_defined_measures_per_sample = collections.OrderedDict() # sys.version_info returns a tuple, the following line compares the entry of tuples # https://docs.python.org/3.6/reference/expressions.html#value-comparisons @@ -431,6 +430,16 @@ def _prediction_to_probabilities(y, model_classes): arff_tracecontent.extend(arff_tracecontent_fold) for measure in user_defined_measures_fold: + if measure not in user_defined_measures_per_fold: + user_defined_measures_per_fold[measure] = collections.OrderedDict() + if rep_no not in user_defined_measures_per_fold: + user_defined_measures_per_fold[measure][rep_no] = collections.OrderedDict() + if measure not in user_defined_measures_per_sample: + user_defined_measures_per_sample[measure] = collections.OrderedDict() + if rep_no not in user_defined_measures_per_sample: + user_defined_measures_per_sample[measure][rep_no] = collections.OrderedDict() + if fold_no not in user_defined_measures_per_sample: + user_defined_measures_per_sample[measure][rep_no][fold_no] = collections.OrderedDict() user_defined_measures_per_fold[measure][rep_no][fold_no] = user_defined_measures_fold[measure] user_defined_measures_per_sample[measure][rep_no][fold_no][sample_no] = user_defined_measures_fold[measure] @@ -515,7 +524,7 @@ def _prediction_to_probabilities(y, model_classes): trainY = Y[train_indices] testX = X[test_indices] testY = Y[test_indices] - user_defined_measures = dict() + user_defined_measures = collections.OrderedDict() try: # for measuring runtime. Only available since Python 3.3 @@ -752,10 +761,10 @@ def obtain_field(xml_obj, fieldname, from_server, cast=None): elif not from_server: dataset_id = None - files = dict() - evaluations = dict() - fold_evaluations = collections.defaultdict(lambda: collections.defaultdict(dict)) - sample_evaluations = collections.defaultdict(lambda: collections.defaultdict(lambda: collections.defaultdict(dict))) + files = collections.OrderedDict() + evaluations = collections.OrderedDict() + fold_evaluations = collections.OrderedDict() + sample_evaluations = collections.OrderedDict() if 'oml:output_data' not in run: if from_server: raise ValueError('Run does not contain output_data (OpenML server error?)') @@ -781,16 +790,23 @@ def obtain_field(xml_obj, fieldname, from_server, cast=None): repeat = int(evaluation_dict['@repeat']) fold = int(evaluation_dict['@fold']) sample = int(evaluation_dict['@sample']) - repeat_dict = sample_evaluations[key] - fold_dict = repeat_dict[repeat] - sample_dict = fold_dict[fold] - sample_dict[sample] = value + if key not in sample_evaluations: + sample_evaluations[key] = collections.OrderedDict() + if repeat not in sample_evaluations[key]: + sample_evaluations[key][repeat] = collections.OrderedDict() + if fold not in sample_evaluations[key][repeat]: + sample_evaluations[key][repeat][fold] = collections.OrderedDict() + sample_evaluations[key][repeat][fold][sample] = value elif '@repeat' in evaluation_dict and '@fold' in evaluation_dict: repeat = int(evaluation_dict['@repeat']) fold = int(evaluation_dict['@fold']) - repeat_dict = fold_evaluations[key] - fold_dict = repeat_dict[repeat] - fold_dict[fold] = value + if key not in fold_evaluations: + fold_evaluations[key] = collections.OrderedDict() + if repeat not in fold_evaluations[key]: + fold_evaluations[key][repeat] = collections.OrderedDict() + if fold not in fold_evaluations[key][repeat]: + fold_evaluations[key][repeat][fold] = collections.OrderedDict() + fold_evaluations[key][repeat][fold] = value else: evaluations[key] = value @@ -832,7 +848,7 @@ def _create_trace_from_description(xml): result_dict = xmltodict.parse(xml, force_list=('oml:trace_iteration',))['oml:trace'] run_id = result_dict['oml:run_id'] - trace = dict() + trace = collections.OrderedDict() if 'oml:trace_iteration' not in result_dict: raise ValueError('Run does not contain valid trace. ') @@ -878,7 +894,7 @@ def _create_trace_from_arff(arff_obj): run : OpenMLRunTrace Object containing None for run id and a dict containing the trace iterations """ - trace = dict() + trace = collections.OrderedDict() attribute_idx = {att[0]: idx for idx, att in enumerate(arff_obj['attributes'])} for required_attribute in ['repeat', 'fold', 'iteration', 'evaluation', 'selected']: if required_attribute not in attribute_idx: @@ -1045,7 +1061,7 @@ def __list_runs(api_call): assert type(runs_dict['oml:runs']['oml:run']) == list, \ type(runs_dict['oml:runs']) - runs = dict() + runs = collections.OrderedDict() for run_ in runs_dict['oml:runs']['oml:run']: run_id = int(run_['oml:run_id']) run = {'run_id': run_id, diff --git a/openml/runs/run.py b/openml/runs/run.py index 4097bd45b7..12b3802bfd 100644 --- a/openml/runs/run.py +++ b/openml/runs/run.py @@ -101,7 +101,8 @@ def from_filesystem(cls, folder): raise ValueError('Could not find model.pkl') with open(description_path, 'r') as fp: - run = openml.runs.functions._create_run_from_xml(fp.read(), from_server=False) + xml_string = fp.read() + run = openml.runs.functions._create_run_from_xml(xml_string, from_server=False) with open(predictions_path, 'r') as fp: predictions = arff.load(fp) @@ -114,7 +115,14 @@ def from_filesystem(cls, folder): with open(trace_path, 'r') as fp: trace = arff.load(fp) run.trace_attributes = trace['attributes'] - run.trace_content = trace['data'] + data_tmp = trace['data'] + # TODO move this functionality to trace.py and serialize/deserialize the trace + # via the according class! + for line in data_tmp: + for i in range(3): + line[i] = int(line[i]) + line[3] = float(line[3]) + run.trace_content = data_tmp return run @@ -177,7 +185,7 @@ def _generate_arff_dict(self): task = get_task(self.task_id) class_labels = task.class_labels - arff_dict = {} + arff_dict = OrderedDict() arff_dict['attributes'] = [('repeat', 'NUMERIC'), # lowercase 'numeric' gives an error ('fold', 'NUMERIC'), ('sample', 'NUMERIC'), @@ -206,7 +214,7 @@ def _generate_trace_arff_dict(self): if len(self.trace_attributes) != len(self.trace_content[0]): raise ValueError('Trace_attributes and trace_content not compatible') - arff_dict = dict() + arff_dict = OrderedDict() arff_dict['attributes'] = self.trace_attributes arff_dict['data'] = self.trace_content arff_dict['relation'] = 'openml_task_' + str(self.task_id) + '_predictions' @@ -252,7 +260,7 @@ def _attribute_list_to_dict(attribute_list): # convenience function: Creates a mapping to map from the name of attributes # present in the arff prediction file to their index. This is necessary # because the number of classes can be different for different tasks. - res = dict() + res = OrderedDict() for idx in range(len(attribute_list)): res[attribute_list[idx][0]] = idx return res @@ -282,11 +290,11 @@ def _attribute_list_to_dict(attribute_list): prediction = predictions_arff['attributes'][predicted_idx][1].index(line[predicted_idx]) correct = predictions_arff['attributes'][predicted_idx][1].index(line[correct_idx]) if rep not in values_predict: - values_predict[rep] = dict() - values_correct[rep] = dict() + values_predict[rep] = OrderedDict() + values_correct[rep] = OrderedDict() if fold not in values_predict[rep]: - values_predict[rep][fold] = dict() - values_correct[rep][fold] = dict() + values_predict[rep][fold] = OrderedDict() + values_correct[rep][fold] = OrderedDict() if samp not in values_predict[rep][fold]: values_predict[rep][fold][samp] = [] values_correct[rep][fold][samp] = [] @@ -542,7 +550,7 @@ def _to_dict(taskid, flow_id, setup_string, error_message, parameter_settings, description['oml:run']['oml:tag'] = tags # Tags describing the run if (fold_evaluations is not None and len(fold_evaluations) > 0) or \ (sample_evaluations is not None and len(sample_evaluations) > 0): - description['oml:run']['oml:output_data'] = dict() + description['oml:run']['oml:output_data'] = OrderedDict() description['oml:run']['oml:output_data']['oml:evaluation'] = list() if fold_evaluations is not None: for measure in fold_evaluations: diff --git a/tests/test_runs/test_run.py b/tests/test_runs/test_run.py index 4a298ba98d..dcbb43fe08 100644 --- a/tests/test_runs/test_run.py +++ b/tests/test_runs/test_run.py @@ -7,6 +7,8 @@ from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier from sklearn.linear_model import LogisticRegression from sklearn.model_selection import GridSearchCV, RandomizedSearchCV, StratifiedKFold +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import Imputer from openml.testing import TestBase from openml.flows.sklearn_converter import sklearn_to_flow @@ -91,18 +93,38 @@ def _test_run_obj_equals(self, run, run_prime): np.testing.assert_array_equal(string_part, string_part_prime) if run.trace_content is not None: - numeric_part = np.array(np.array(run.trace_content)[:, 0:-2], dtype=float) - numeric_part_prime = np.array(np.array(run_prime.trace_content)[:, 0:-2], dtype=float) - string_part = np.array(run.trace_content)[:, -2:] - string_part_prime = np.array(run_prime.trace_content)[:, -2:] + def _check_array(array, type_): + for line in array: + for entry in line: + self.assertIsInstance(entry, type_) + + int_part = [line[:3] for line in run.trace_content] + _check_array(int_part, int) + int_part_prime = [line[:3] for line in run_prime.trace_content] + _check_array(int_part_prime, int) + + float_part = np.array(np.array(run.trace_content)[:, 3:4], dtype=float) + float_part_prime = np.array(np.array(run_prime.trace_content)[:, 3:4], dtype=float) + bool_part = [line[4] for line in run.trace_content] + bool_part_prime = [line[4] for line in run_prime.trace_content] + for bp, bpp in zip(bool_part, bool_part_prime): + self.assertIn(bp, ['true', 'false']) + self.assertIn(bpp, ['true', 'false']) + string_part = np.array(run.trace_content)[:, 5:] + string_part_prime = np.array(run_prime.trace_content)[:, 5:] # JvR: Python 2.7 requires an almost equal check, rather than an equals check - np.testing.assert_array_almost_equal(numeric_part, numeric_part_prime) + np.testing.assert_array_almost_equal(int_part, int_part_prime) + np.testing.assert_array_almost_equal(float_part, float_part_prime) + self.assertEqual(bool_part, bool_part_prime) np.testing.assert_array_equal(string_part, string_part_prime) else: self.assertIsNone(run_prime.trace_content) def test_to_from_filesystem_vanilla(self): - model = DecisionTreeClassifier(max_depth=1) + model = Pipeline([ + ('imputer', Imputer(strategy='mean')), + ('classifier', DecisionTreeClassifier(max_depth=1)), + ]) task = openml.tasks.get_task(119) run = openml.runs.run_model_on_task(task, model, add_local_measures=False) @@ -114,7 +136,17 @@ def test_to_from_filesystem_vanilla(self): run_prime.publish() def test_to_from_filesystem_search(self): - model = GridSearchCV(estimator=DecisionTreeClassifier(), param_grid={"max_depth": [1, 2, 3, 4, 5]}) + model = Pipeline([ + ('imputer', Imputer(strategy='mean')), + ('classifier', DecisionTreeClassifier(max_depth=1)), + ]) + model = GridSearchCV( + estimator=model, + param_grid={ + "classifier__max_depth": [1, 2, 3, 4, 5], + "imputer__strategy": ['mean', 'median'], + } + ) task = openml.tasks.get_task(119) run = openml.runs.run_model_on_task(task, model, add_local_measures=False) From 8d8e3d45c7c5afa8b318f31de9f8e3e6898babe5 Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Tue, 19 Jun 2018 13:52:48 +0200 Subject: [PATCH 2/6] Update liac-arff dependency to 2.2.2 --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index a0cfb6e664..13de76a360 100644 --- a/setup.py +++ b/setup.py @@ -37,7 +37,7 @@ 'mock', 'numpy>=1.6.2', 'scipy>=0.13.3', - 'liac-arff>=2.2.1', + 'liac-arff>=2.2.2', 'xmltodict', 'nose', 'requests', From 33d6bb3cca43cb229ae5cd8ae8105af1cb7cb541 Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Tue, 19 Jun 2018 14:30:29 +0200 Subject: [PATCH 3/6] FIX assignment bug --- openml/runs/functions.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/openml/runs/functions.py b/openml/runs/functions.py index ad5314e994..8b01061da1 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -430,16 +430,19 @@ def _prediction_to_probabilities(y, model_classes): arff_tracecontent.extend(arff_tracecontent_fold) for measure in user_defined_measures_fold: + if measure not in user_defined_measures_per_fold: user_defined_measures_per_fold[measure] = collections.OrderedDict() - if rep_no not in user_defined_measures_per_fold: + if rep_no not in user_defined_measures_per_fold[measure]: user_defined_measures_per_fold[measure][rep_no] = collections.OrderedDict() + if measure not in user_defined_measures_per_sample: user_defined_measures_per_sample[measure] = collections.OrderedDict() - if rep_no not in user_defined_measures_per_sample: + if rep_no not in user_defined_measures_per_sample[measure]: user_defined_measures_per_sample[measure][rep_no] = collections.OrderedDict() - if fold_no not in user_defined_measures_per_sample: + if fold_no not in user_defined_measures_per_sample[measure][rep_no]: user_defined_measures_per_sample[measure][rep_no][fold_no] = collections.OrderedDict() + user_defined_measures_per_fold[measure][rep_no][fold_no] = user_defined_measures_fold[measure] user_defined_measures_per_sample[measure][rep_no][fold_no][sample_no] = user_defined_measures_fold[measure] @@ -804,8 +807,6 @@ def obtain_field(xml_obj, fieldname, from_server, cast=None): fold_evaluations[key] = collections.OrderedDict() if repeat not in fold_evaluations[key]: fold_evaluations[key][repeat] = collections.OrderedDict() - if fold not in fold_evaluations[key][repeat]: - fold_evaluations[key][repeat][fold] = collections.OrderedDict() fold_evaluations[key][repeat][fold] = value else: evaluations[key] = value From 73c7336fbaae37467dc6a18977114c948052616b Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Wed, 20 Jun 2018 11:21:04 -0400 Subject: [PATCH 4/6] cosmetic updates requested by PyCharm for trace --- openml/runs/trace.py | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/openml/runs/trace.py b/openml/runs/trace.py index a32b797748..37fb650969 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -1,5 +1,6 @@ import json + class OpenMLRunTrace(object): """OpenML Run Trace: parsed output from Run Trace call @@ -19,18 +20,30 @@ def __init__(self, run_id, trace_iterations): self.trace_iterations = trace_iterations def get_selected_iteration(self, fold, repeat): - ''' + """ Returns the trace iteration that was marked as selected. In case multiple are marked as selected (should not happen) the first of these is returned - ''' + + Parameters + ---------- + fold: int + + repeat: int + + Returns + ---------- + OpenMLTraceIteration + The trace iteration from the given fold and repeat that was + selected as the best iteration by the search procedure + """ for (r, f, i) in self.trace_iterations: if r == repeat and f == fold and self.trace_iterations[(r, f, i)].selected is True: return i raise ValueError('Could not find the selected iteration for rep/fold %d/%d' %(repeat,fold)) def __str__(self): - return '[Run id: %d, %d trace iterations]' %(self.run_id, len(self.trace_iterations)) + return '[Run id: %d, %d trace iterations]' % (self.run_id, len(self.trace_iterations)) class OpenMLTraceIteration(object): From 56bc1dd28e00a69874a0c5bc8ac6691eee7a2502 Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Wed, 20 Jun 2018 17:54:51 -0400 Subject: [PATCH 5/6] moved trace load logic to trace file --- openml/runs/run.py | 16 ++++------------ openml/runs/trace.py | 40 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 40 insertions(+), 16 deletions(-) diff --git a/openml/runs/run.py b/openml/runs/run.py index 12b3802bfd..2eace334df 100644 --- a/openml/runs/run.py +++ b/openml/runs/run.py @@ -111,18 +111,10 @@ def from_filesystem(cls, folder): with open(model_path, 'rb') as fp: run.model = pickle.load(fp) - if os.path.isfile(trace_path): - with open(trace_path, 'r') as fp: - trace = arff.load(fp) - run.trace_attributes = trace['attributes'] - data_tmp = trace['data'] - # TODO move this functionality to trace.py and serialize/deserialize the trace - # via the according class! - for line in data_tmp: - for i in range(3): - line[i] = int(line[i]) - line[3] = float(line[3]) - run.trace_content = data_tmp + trace_arff = openml.runs.OpenMLRunTrace._from_filesystem(trace_path) + + run.trace_attributes = trace_arff['attributes'] + run.trace_content = trace_arff['data'] return run diff --git a/openml/runs/trace.py b/openml/runs/trace.py index 37fb650969..f653cb2c2a 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -1,4 +1,6 @@ +import arff import json +import os class OpenMLRunTrace(object): @@ -40,7 +42,37 @@ def get_selected_iteration(self, fold, repeat): for (r, f, i) in self.trace_iterations: if r == repeat and f == fold and self.trace_iterations[(r, f, i)].selected is True: return i - raise ValueError('Could not find the selected iteration for rep/fold %d/%d' %(repeat,fold)) + raise ValueError('Could not find the selected iteration for rep/fold %d/%d' % (repeat, fold)) + + @staticmethod + def _from_filesystem(file_path): + """ + Logic to deserialize the trace from the filesystem + + Parameters + ---------- + file_path: str + File path where the trace is stored + + Returns + ---------- + trace: dict + a dict in the liac-arff style that contains trace information + """ + if not os.path.isfile(file_path): + raise ValueError('Trace file doesn\'t exist') + + with open(file_path, 'r') as fp: + trace = arff.load(fp) + + # TODO probably we want to integrate the trace object with the run object, rather than the current + # situation (which stores the arff) + for trace_idx in range(len(trace['data'])): + # iterate over first three entrees of a trace row (fold, repeat, trace_iteration) these should be int + for line_idx in range(3): + value = trace['data'][trace_idx][line_idx] + trace['data'][trace_idx][line_idx] = int(trace['data'][trace_idx][line_idx]) + return trace def __str__(self): return '[Run id: %d, %d trace iterations]' % (self.run_id, len(self.trace_iterations)) @@ -92,9 +124,9 @@ def get_parameters(self): return result def __str__(self): - ''' + """ tmp string representation, will be changed in the near future - ''' + """ return '[(%d,%d,%d): %f (%r)]' %(self.repeat, self.fold, self.iteration, - self.evaluation, self.selected) + self.evaluation, self.selected) From 0f13c97d3de7ff3c69978d61d4a56bfe3eb0120c Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Wed, 20 Jun 2018 18:02:33 -0400 Subject: [PATCH 6/6] fix unit test --- openml/runs/run.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/openml/runs/run.py b/openml/runs/run.py index 2eace334df..f669b6f58d 100644 --- a/openml/runs/run.py +++ b/openml/runs/run.py @@ -111,10 +111,11 @@ def from_filesystem(cls, folder): with open(model_path, 'rb') as fp: run.model = pickle.load(fp) - trace_arff = openml.runs.OpenMLRunTrace._from_filesystem(trace_path) + if os.path.isfile(trace_path): + trace_arff = openml.runs.OpenMLRunTrace._from_filesystem(trace_path) - run.trace_attributes = trace_arff['attributes'] - run.trace_content = trace_arff['data'] + run.trace_attributes = trace_arff['attributes'] + run.trace_content = trace_arff['data'] return run