From fc008e4d5d5c9a75f74de0bc5ed0d2267293c815 Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Tue, 19 Jun 2018 14:12:13 +0200 Subject: [PATCH 01/29] run functions test: compare xml of uploaded and downloaded run --- tests/test_runs/test_run_functions.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index 6cf860b52f..6959e14a2b 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -122,6 +122,9 @@ def _remove_random_state(flow): self.assertEqual(run_, run) self.assertIsInstance(run.dataset_id, int) + run_xml = run._create_description_xml() + run_trace = run._generate_trace_arff_dict() + # check arff output self.assertEqual(len(run.data_content), num_instances) @@ -168,6 +171,12 @@ def _remove_random_state(flow): downloaded = openml.runs.get_run(run_.run_id) assert('openml-python' in downloaded.tags) + # TODO make sure that these attributes are instantiated when downloading a run? + # Or make sure that the trace object is created when running a flow on a task (and not + # only the arff object is created, so that the two objects can actually be compared). + #downloaded_run_trace = downloaded._generate_trace_arff_dict() + #self.assertEqual(run_trace, downloaded_run_trace) + return run def _check_fold_evaluations(self, fold_evaluations, num_repeats, num_folds, max_time_allowed=60000): From ce0694ae183ef30388715fc0dab495c388cf003a Mon Sep 17 00:00:00 2001 From: ArlindKadra Date: Mon, 25 Jun 2018 11:10:59 +0100 Subject: [PATCH 02/29] Initial changes --- openml/runs/run.py | 46 +++++++++++++++++++++++++++++++---- openml/runs/trace.py | 57 +++++++++++++++++++++++++++++++++++++------- 2 files changed, 91 insertions(+), 12 deletions(-) diff --git a/openml/runs/run.py b/openml/runs/run.py index f669b6f58d..a4917c6bb2 100644 --- a/openml/runs/run.py +++ b/openml/runs/run.py @@ -12,6 +12,7 @@ import openml import openml._api_calls +from .trace import OpenMLRunTrace, OpenMLTraceIteration from ..tasks import get_task from ..exceptions import PyOpenMLError @@ -49,6 +50,7 @@ def __init__(self, task_id, flow_id, dataset_id, setup_string=None, self.output_files = output_files self.trace_attributes = trace_attributes self.trace_content = trace_content + self.trace = self._generate_trace() self.error_message = None self.task = task self.flow = flow @@ -112,10 +114,8 @@ def from_filesystem(cls, folder): run.model = pickle.load(fp) 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'] + trace = openml.runs.OpenMLRunTrace._from_filesystem(trace_path) + run.trace = trace return run @@ -156,6 +156,7 @@ def to_filesystem(self, output_directory): if self.trace_content is not None: trace_arff = arff.dumps(self._generate_trace_arff_dict()) + with open(os.path.join(output_directory, 'trace.arff'), 'w') as f: f.write(trace_arff) @@ -214,6 +215,43 @@ def _generate_trace_arff_dict(self): return arff_dict + def _generate_trace(self): + + if self.trace_content is None or len(self.trace_content) == 0: + raise ValueError('No trace content available.') + if len(self.trace_attributes) != len(self.trace_content[0]): + raise ValueError('Trace_attributes and trace_content not compatible') + + trace = OrderedDict() + attribute_idx = {att[0]: idx for idx, att in enumerate(self.trace_attributes)} + for required_attribute in ['repeat', 'fold', 'iteration', 'evaluation', 'selected']: + if required_attribute not in attribute_idx: + raise ValueError('arff misses required attribute: %s' % required_attribute) + + for itt in self.trace_content: + repeat = int(itt[attribute_idx['repeat']]) + fold = int(itt[attribute_idx['fold']]) + iteration = int(itt[attribute_idx['iteration']]) + evaluation = float(itt[attribute_idx['evaluation']]) + selectedValue = itt[attribute_idx['selected']] + if selectedValue == 'true': + selected = True + elif selectedValue == 'false': + selected = False + else: + raise ValueError('expected {"true", "false"} value for selected field, received: %s' % selectedValue) + + # TODO: if someone needs it, he can use the parameter + # fields to revive the setup_string as well + # However, this is usually done by the OpenML server + # and if we are going to duplicate this functionality + # it needs proper testing + + current = OpenMLTraceIteration(repeat, fold, iteration, None, evaluation, selected) + trace[(repeat, fold, iteration)] = current + + return OpenMLRunTrace(None, trace) + def get_metric_fn(self, sklearn_fn, kwargs={}): """Calculates metric scores based on predicted values. Assumes the run has been executed locally (and contains run_data). Furthermore, diff --git a/openml/runs/trace.py b/openml/runs/trace.py index f653cb2c2a..bbd82dad59 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -1,6 +1,8 @@ import arff import json import os +from openml.runs.functions import _create_trace_from_arff +from collections import OrderedDict class OpenMLRunTrace(object): @@ -52,27 +54,66 @@ def _from_filesystem(file_path): Parameters ---------- file_path: str - File path where the trace is stored + File path where the trace arff is stored. Returns ---------- - trace: dict - a dict in the liac-arff style that contains trace information + OpenMLRunTrace """ 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) + trace_arff = 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'])): + for trace_idx in range(len(trace_arff['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 + trace_arff['data'][trace_idx][line_idx] = int(trace_arff['data'][trace_idx][line_idx]) + + return _create_trace_from_arff(trace_arff) + + @staticmethod + def _to_filesystem(self, file_path): + + if self.trace_iterations is not None: + trace_arff = arff.dumps(self._generate_trace_arff_dict()) + with open(os.path.join(output_directory, 'trace.arff'), 'w') as f: + f.write(trace_arff) + + def _generate_trace_arff_dict(self): + """Generates the arff dictionary for uploading predictions to the server. + + Assumes that the run has been executed. + + Returns + ------- + arf_dict : dict + Dictionary representation of the ARFF file that will be uploaded. + Contains information about the optimization trace. + """ + + for trace_iteration in self.trace_iterations.values(): + for attrib, value in vars(trace_iteration).items(): + if attrib is not None: + + + + if self.trace_content is None or len(self.trace_content) == 0: + raise ValueError('No trace content available.') + if len(self.trace_attributes) != len(self.trace_content[0]): + raise ValueError('Trace_attributes and trace_content not compatible') + + 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' + + return arff_dict + + def __str__(self): return '[Run id: %d, %d trace iterations]' % (self.run_id, len(self.trace_iterations)) From 60dc43a16b5b9b5cf18f3118969ab19259e84f04 Mon Sep 17 00:00:00 2001 From: ArlindKadra Date: Mon, 25 Jun 2018 16:27:59 +0200 Subject: [PATCH 03/29] Refactored the run and trace classes. Refactored functions from run/functions as trace methods. --- openml/runs/functions.py | 79 ------------ openml/runs/run.py | 54 +++----- openml/runs/trace.py | 170 +++++++++++++++++++++----- tests/test_runs/test_run_functions.py | 4 +- 4 files changed, 156 insertions(+), 151 deletions(-) diff --git a/openml/runs/functions.py b/openml/runs/functions.py index 8b01061da1..7e7e393e4b 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -23,7 +23,6 @@ from ..exceptions import OpenMLCacheException, OpenMLServerException from ..tasks import OpenMLTask from .run import OpenMLRun, _get_version_information -from .trace import OpenMLRunTrace, OpenMLTraceIteration # _get_version_info, _get_dict and _create_setup_string are in run.py to avoid @@ -845,85 +844,7 @@ def obtain_field(xml_obj, fieldname, from_server, cast=None): tags=tags) -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 = collections.OrderedDict() - - if 'oml:trace_iteration' not in result_dict: - raise ValueError('Run does not contain valid trace. ') - - assert type(result_dict['oml:trace_iteration']) == list, \ - type(result_dict['oml:trace_iteration']) - - for itt in result_dict['oml:trace_iteration']: - repeat = int(itt['oml:repeat']) - fold = int(itt['oml:fold']) - iteration = int(itt['oml:iteration']) - setup_string = json.loads(itt['oml:setup_string']) - evaluation = float(itt['oml:evaluation']) - - selectedValue = itt['oml:selected'] - if selectedValue == 'true': - selected = True - elif selectedValue == 'false': - selected = False - else: - raise ValueError('expected {"true", "false"} value for '\ - 'selected field, received: %s' %selectedValue) - - current = OpenMLTraceIteration(repeat, fold, iteration, - setup_string, evaluation, - selected) - trace[(repeat, fold, iteration)] = current - - return OpenMLRunTrace(run_id, trace) - - -def _create_trace_from_arff(arff_obj): - """ - Creates a trace file from arff obj (for example, generated by a local run) - - Parameters - ---------- - arff_obj : dict - LIAC arff obj, dict containing attributes, relation, data and description - - Returns - ------- - run : OpenMLRunTrace - Object containing None for run id and a dict containing the trace iterations - """ - 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: - raise ValueError('arff misses required attribute: %s' %required_attribute) - - for itt in arff_obj['data']: - repeat = int(itt[attribute_idx['repeat']]) - fold = int(itt[attribute_idx['fold']]) - iteration = int(itt[attribute_idx['iteration']]) - evaluation = float(itt[attribute_idx['evaluation']]) - selectedValue = itt[attribute_idx['selected']] - if selectedValue == 'true': - selected = True - elif selectedValue == 'false': - selected = False - else: - raise ValueError('expected {"true", "false"} value for selected field, received: %s' % selectedValue) - - # TODO: if someone needs it, he can use the parameter - # fields to revive the setup_string as well - # However, this is usually done by the OpenML server - # and if we are going to duplicate this functionality - # it needs proper testing - - current = OpenMLTraceIteration(repeat, fold, iteration, None, evaluation, selected) - trace[(repeat, fold, iteration)] = current - - return OpenMLRunTrace(None, trace) def _get_cached_run(run_id): diff --git a/openml/runs/run.py b/openml/runs/run.py index a4917c6bb2..bcd2df7667 100644 --- a/openml/runs/run.py +++ b/openml/runs/run.py @@ -48,9 +48,10 @@ def __init__(self, task_id, flow_id, dataset_id, setup_string=None, self.sample_evaluations = sample_evaluations self.data_content = data_content self.output_files = output_files - self.trace_attributes = trace_attributes - self.trace_content = trace_content - self.trace = self._generate_trace() + try: + self.trace = self._generate_trace(trace_attributes, trace_content) + except ValueError: + self.trace = None self.error_message = None self.task = task self.flow = flow @@ -114,8 +115,7 @@ def from_filesystem(cls, folder): run.model = pickle.load(fp) if os.path.isfile(trace_path): - trace = openml.runs.OpenMLRunTrace._from_filesystem(trace_path) - run.trace = trace + run.trace = openml.runs.OpenMLRunTrace.from_filesystem(trace_path) return run @@ -154,11 +154,8 @@ def to_filesystem(self, output_directory): with open(os.path.join(output_directory, 'model.pkl'), 'wb') as f: pickle.dump(self.model, f) - if self.trace_content is not None: - trace_arff = arff.dumps(self._generate_trace_arff_dict()) - - with open(os.path.join(output_directory, 'trace.arff'), 'w') as f: - f.write(trace_arff) + if self.trace is not None: + self.trace.to_filesystem(output_directory) def _generate_arff_dict(self): """Generates the arff dictionary for uploading predictions to the server. @@ -192,43 +189,20 @@ def _generate_arff_dict(self): arff_dict['relation'] = 'openml_task_' + str(task.task_id) + '_predictions' return arff_dict - def _generate_trace_arff_dict(self): - """Generates the arff dictionary for uploading predictions to the server. - - Assumes that the run has been executed. - - Returns - ------- - arf_dict : dict - Dictionary representation of the ARFF file that will be uploaded. - Contains information about the optimization trace. - """ - if self.trace_content is None or len(self.trace_content) == 0: - raise ValueError('No trace content available.') - if len(self.trace_attributes) != len(self.trace_content[0]): - raise ValueError('Trace_attributes and trace_content not compatible') - - 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' - - return arff_dict - - def _generate_trace(self): + def _generate_trace(self, trace_attributes, trace_content): - if self.trace_content is None or len(self.trace_content) == 0: + if trace_content is None or len(trace_content) == 0: raise ValueError('No trace content available.') - if len(self.trace_attributes) != len(self.trace_content[0]): + if trace_attributes is None or len(trace_attributes) != len(trace_content[0]): raise ValueError('Trace_attributes and trace_content not compatible') trace = OrderedDict() - attribute_idx = {att[0]: idx for idx, att in enumerate(self.trace_attributes)} + attribute_idx = {att[0]: idx for idx, att in enumerate(trace_attributes)} for required_attribute in ['repeat', 'fold', 'iteration', 'evaluation', 'selected']: if required_attribute not in attribute_idx: raise ValueError('arff misses required attribute: %s' % required_attribute) - for itt in self.trace_content: + for itt in trace_content: repeat = int(itt[attribute_idx['repeat']]) fold = int(itt[attribute_idx['fold']]) iteration = int(itt[attribute_idx['iteration']]) @@ -353,9 +327,9 @@ def publish(self): self : OpenMLRun """ if self.model is None: - raise PyOpenMLError("OpenMLRun obj does not contain a model. (This should never happen.) "); + raise PyOpenMLError("OpenMLRun obj does not contain a model. (This should never happen.) ") if self.flow_id is None: - raise PyOpenMLError("OpenMLRun obj does not contain a flow id. (Should have been added while executing the task.) "); + raise PyOpenMLError("OpenMLRun obj does not contain a flow id. (Should have been added while executing the task.) ") description_xml = self._create_description_xml() file_elements = {'description': ("description.xml", description_xml)} diff --git a/openml/runs/trace.py b/openml/runs/trace.py index bbd82dad59..3857f85c41 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -1,7 +1,7 @@ import arff import json import os -from openml.runs.functions import _create_trace_from_arff +import xmltodict from collections import OrderedDict @@ -11,7 +11,7 @@ class OpenMLRunTrace(object): Parameters ---------- run_id : int - OpenML run id + OpenML run id. trace_iterations : dict Mapping from key ``(repeat, fold, iteration)`` to an object of @@ -46,10 +46,10 @@ def get_selected_iteration(self, fold, repeat): return i raise ValueError('Could not find the selected iteration for rep/fold %d/%d' % (repeat, fold)) - @staticmethod - def _from_filesystem(file_path): + @classmethod + def from_filesystem(cls, file_path): """ - Logic to deserialize the trace from the filesystem + Logic to deserialize the trace from the filesystem. Parameters ---------- @@ -66,54 +66,165 @@ def _from_filesystem(file_path): with open(file_path, 'r') as fp: trace_arff = 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_arff['data'])): # iterate over first three entrees of a trace row (fold, repeat, trace_iteration) these should be int for line_idx in range(3): trace_arff['data'][trace_idx][line_idx] = int(trace_arff['data'][trace_idx][line_idx]) - return _create_trace_from_arff(trace_arff) + return cls.trace_from_arff(trace_arff) - @staticmethod - def _to_filesystem(self, file_path): + def to_filesystem(self, file_path): + """Serialize the trace object to the filesystem. + Serialize the trace object as an arff. + + Parameters + ---------- + file_path: str + File path where the trace arff will be stored. + """ if self.trace_iterations is not None: - trace_arff = arff.dumps(self._generate_trace_arff_dict()) - with open(os.path.join(output_directory, 'trace.arff'), 'w') as f: + trace_arff = arff.dumps(self._trace_to_arff()) + with open(os.path.join(file_path, 'trace.arff'), 'w') as f: f.write(trace_arff) + else: + raise ValueError("trace_iterations missing from the trace object") - def _generate_trace_arff_dict(self): + def _trace_to_arff(self): """Generates the arff dictionary for uploading predictions to the server. - Assumes that the run has been executed. + Uses the trace object to generate an arff dictionary representation. Returns ------- - arf_dict : dict + arff_dict : dict Dictionary representation of the ARFF file that will be uploaded. Contains information about the optimization trace. """ - + # attributes that will be in trace arff + trace_attributes = [('repeat', 'NUMERIC'), + ('fold', 'NUMERIC'), + ('iteration', 'NUMERIC'), + ('evaluation', 'NUMERIC'), + ('selected', ['true', 'false']), + ('setup_string', 'STRING') + ] + arff_dict = OrderedDict() + data = [] for trace_iteration in self.trace_iterations.values(): - for attrib, value in vars(trace_iteration).items(): - if attrib is not None: + tit_list = [] + for attr, attr_type in trace_attributes: + value = getattr(trace_iteration, attr) + if attr == 'selected': + if value: + tit_list.append('true') + else: + tit_list.append('false') + else: + tit_list.append(value) + data.append(tit_list) + + arff_dict['attributes'] = trace_attributes + arff_dict['data'] = data + return arff_dict + @classmethod + def trace_from_arff(cls, arff_obj): + """Generate trace from arff trace. - if self.trace_content is None or len(self.trace_content) == 0: - raise ValueError('No trace content available.') - if len(self.trace_attributes) != len(self.trace_content[0]): - raise ValueError('Trace_attributes and trace_content not compatible') + Creates a trace file from arff object (for example, generated by a local run). - 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' + Parameters + ---------- + arff_obj : dict + LIAC arff obj, dict containing attributes, relation, data. - return arff_dict + Returns + ------- + OpenMLRunTrace + """ + trace = 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: + raise ValueError('arff misses required attribute: %s' % required_attribute) + + for itt in arff_obj['data']: + repeat = int(itt[attribute_idx['repeat']]) + fold = int(itt[attribute_idx['fold']]) + iteration = int(itt[attribute_idx['iteration']]) + evaluation = float(itt[attribute_idx['evaluation']]) + setup_string = str(itt[attribute_idx['setup_string']]) + selected_value = itt[attribute_idx['selected']] + if selected_value == 'true': + selected = True + elif selected_value == 'false': + selected = False + else: + raise ValueError('expected {"true", "false"} value for selected field, received: %s' % selected_value) + + # if someone needs it, he can use the parameter + # fields to revive the setup_string as well + # However, this is usually done by the OpenML server + # and if we are going to duplicate this functionality + # it needs proper testing + + current = OpenMLTraceIteration(repeat, fold, iteration, setup_string, + evaluation, selected) + trace[(repeat, fold, iteration)] = current + + return cls(None, trace) + + @classmethod + def _trace_from_xml(cls, xml): + """Generate trace from xml. + + Creates a trace file from the xml description. + + Parameters + ---------- + xml : string | file-like object + An xml description that can be either a `string` or a file-like object. + + Returns + ------- + run : OpenMLRunTrace + Object containing run id and a dict containing the trace iterations. + """ + result_dict = xmltodict.parse(xml, force_list=('oml:trace_iteration',))['oml:trace'] + + run_id = result_dict['oml:run_id'] + trace = OrderedDict() + + if 'oml:trace_iteration' not in result_dict: + raise ValueError('Run does not contain valid trace. ') + + assert type(result_dict['oml:trace_iteration']) == list, \ + type(result_dict['oml:trace_iteration']) + for itt in result_dict['oml:trace_iteration']: + repeat = int(itt['oml:repeat']) + fold = int(itt['oml:fold']) + iteration = int(itt['oml:iteration']) + setup_string = json.loads(itt['oml:setup_string']) + evaluation = float(itt['oml:evaluation']) + selected_value = itt['oml:selected'] + if selected_value == 'true': + selected = True + elif selected_value == 'false': + selected = False + else: + raise ValueError('expected {"true", "false"} value for ' + 'selected field, received: %s' % selected_value) + + current = OpenMLTraceIteration(repeat, fold, iteration, + setup_string, evaluation, + selected) + trace[(repeat, fold, iteration)] = current + + return cls(run_id, trace) def __str__(self): return '[Run id: %d, %d trace iterations]' % (self.run_id, len(self.trace_iterations)) @@ -168,6 +279,5 @@ 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) - + return '[(%d,%d,%d): %f (%r)]' % (self.repeat, self.fold, self.iteration, + self.evaluation, self.selected) diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index 6959e14a2b..b6b546599e 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -552,7 +552,7 @@ def test_get_run_trace(self): try: # 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()) + trace = openml.runs.trace.trace_from_arff(run._generate_trace_arff_dict()) self.assertEquals( len(trace.trace_iterations), num_iterations * num_folds, @@ -845,7 +845,7 @@ def test__run_model_on_fold(self): def test__create_trace_from_arff(self): with open(self.static_cache_dir + '/misc/trace.arff', 'r') as arff_file: trace_arff = arff.load(arff_file) - trace = openml.runs.functions._create_trace_from_arff(trace_arff) + openml.runs.trace.trace_from_arff(trace_arff) def test_get_run(self): # this run is not available on test From 36f25eaeef546170f6e2263d0a24d25ca1146e49 Mon Sep 17 00:00:00 2001 From: ArlindKadra Date: Mon, 25 Jun 2018 17:04:47 +0200 Subject: [PATCH 04/29] First try at fixing unit tests --- openml/runs/functions.py | 4 ++-- openml/runs/run.py | 4 ++-- openml/runs/trace.py | 13 +++++++------ tests/test_runs/test_run.py | 23 ++++++++++++----------- tests/test_runs/test_run_functions.py | 5 +++-- 5 files changed, 26 insertions(+), 23 deletions(-) diff --git a/openml/runs/functions.py b/openml/runs/functions.py index 7e7e393e4b..2afa361ad1 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -23,7 +23,7 @@ from ..exceptions import OpenMLCacheException, OpenMLServerException from ..tasks import OpenMLTask from .run import OpenMLRun, _get_version_information - +from .trace import OpenMLRunTrace # _get_version_info, _get_dict and _create_setup_string are in run.py to avoid # circular imports @@ -170,7 +170,7 @@ def get_run_trace(run_id): """ trace_xml = openml._api_calls._perform_api_call('run/trace/%d' % run_id) - run_trace = _create_trace_from_description(trace_xml) + run_trace = OpenMLRunTrace._trace_from_xml(trace_xml) return run_trace diff --git a/openml/runs/run.py b/openml/runs/run.py index bcd2df7667..3c1c9f64be 100644 --- a/openml/runs/run.py +++ b/openml/runs/run.py @@ -338,8 +338,8 @@ def publish(self): predictions = arff.dumps(self._generate_arff_dict()) file_elements['predictions'] = ("predictions.arff", predictions) - if self.trace_content is not None: - trace_arff = arff.dumps(self._generate_trace_arff_dict()) + if self.trace is not None: + trace_arff = self.trace._trace_to_arff() file_elements['trace'] = ("trace.arff", trace_arff) return_value = openml._api_calls._perform_api_call("/run/", file_elements=file_elements) diff --git a/openml/runs/trace.py b/openml/runs/trace.py index 3857f85c41..172347c61d 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -83,12 +83,10 @@ def to_filesystem(self, file_path): file_path: str File path where the trace arff will be stored. """ - if self.trace_iterations is not None: - trace_arff = arff.dumps(self._trace_to_arff()) - with open(os.path.join(file_path, 'trace.arff'), 'w') as f: - f.write(trace_arff) - else: - raise ValueError("trace_iterations missing from the trace object") + + trace_arff = arff.dumps(self._trace_to_arff()) + with open(os.path.join(file_path, 'trace.arff'), 'w') as f: + f.write(trace_arff) def _trace_to_arff(self): """Generates the arff dictionary for uploading predictions to the server. @@ -101,6 +99,8 @@ def _trace_to_arff(self): Dictionary representation of the ARFF file that will be uploaded. Contains information about the optimization trace. """ + if self.trace_iterations is None: + raise ValueError("trace_iterations missing from the trace object") # attributes that will be in trace arff trace_attributes = [('repeat', 'NUMERIC'), ('fold', 'NUMERIC'), @@ -126,6 +126,7 @@ def _trace_to_arff(self): arff_dict['attributes'] = trace_attributes arff_dict['data'] = data + arff_dict['relation'] = "Trace" return arff_dict diff --git a/tests/test_runs/test_run.py b/tests/test_runs/test_run.py index dcbb43fe08..34e1d85ced 100644 --- a/tests/test_runs/test_run.py +++ b/tests/test_runs/test_run.py @@ -91,34 +91,35 @@ def _test_run_obj_equals(self, run, run_prime): # 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_equal(string_part, string_part_prime) - - if run.trace_content is not None: + run_trace_content = run.trace.__trace_to_arff()['data'] + run_prime_trace_content = run_prime.trace.__trace_to_arff()['data'] + if run_trace_content is not None: 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] + 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] + 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] + 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:] + 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(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) + self.assertIsNone(run_prime_trace_content) def test_to_from_filesystem_vanilla(self): model = Pipeline([ diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index b6b546599e..f1bdcee387 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -18,6 +18,7 @@ _get_seeded_model, _run_exists, _extract_arfftrace, \ _extract_arfftrace_attributes, _prediction_to_row, _check_n_jobs from openml.flows.sklearn_converter import sklearn_to_flow +from openml.runs.trace import OpenMLRunTrace from sklearn.naive_bayes import GaussianNB from sklearn.model_selection._search import BaseSearchCV @@ -123,7 +124,7 @@ def _remove_random_state(flow): self.assertIsInstance(run.dataset_id, int) run_xml = run._create_description_xml() - run_trace = run._generate_trace_arff_dict() + run_trace = run.trace._trace_to_arff() # check arff output self.assertEqual(len(run.data_content), num_instances) @@ -845,7 +846,7 @@ def test__run_model_on_fold(self): def test__create_trace_from_arff(self): with open(self.static_cache_dir + '/misc/trace.arff', 'r') as arff_file: trace_arff = arff.load(arff_file) - openml.runs.trace.trace_from_arff(trace_arff) + OpenMLRunTrace.trace_from_arff(trace_arff) def test_get_run(self): # this run is not available on test From 949be6db1d1f286d5e857d6c1bb150a92f5d5789 Mon Sep 17 00:00:00 2001 From: ArlindKadra Date: Mon, 25 Jun 2018 17:35:14 +0200 Subject: [PATCH 05/29] Fixing unit tests --- openml/runs/trace.py | 9 ++++++++- tests/test_runs/test_run.py | 13 +++++++++++-- tests/test_runs/test_run_functions.py | 3 ++- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/openml/runs/trace.py b/openml/runs/trace.py index 172347c61d..72460f6f89 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -146,17 +146,24 @@ def trace_from_arff(cls, arff_obj): OpenMLRunTrace """ trace = OrderedDict() + # flag if setup string is in attributes + flag_ss = False 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: raise ValueError('arff misses required attribute: %s' % required_attribute) + if 'setup_string' in attribute_idx: + flag_ss = True for itt in arff_obj['data']: repeat = int(itt[attribute_idx['repeat']]) fold = int(itt[attribute_idx['fold']]) iteration = int(itt[attribute_idx['iteration']]) evaluation = float(itt[attribute_idx['evaluation']]) - setup_string = str(itt[attribute_idx['setup_string']]) + if flag_ss: + setup_string = str(itt[attribute_idx['setup_string']]) + else: + setup_string = None selected_value = itt[attribute_idx['selected']] if selected_value == 'true': selected = True diff --git a/tests/test_runs/test_run.py b/tests/test_runs/test_run.py index 34e1d85ced..0cfab341d0 100644 --- a/tests/test_runs/test_run.py +++ b/tests/test_runs/test_run.py @@ -91,8 +91,17 @@ def _test_run_obj_equals(self, run, run_prime): # 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_equal(string_part, string_part_prime) - run_trace_content = run.trace.__trace_to_arff()['data'] - run_prime_trace_content = run_prime.trace.__trace_to_arff()['data'] + + if run.trace is not None: + run_trace_content = run.trace._trace_to_arff()['data'] + else: + run_trace_content = None + + if run_prime.trace is not None: + run_prime_trace_content = run_prime.trace._trace_to_arff()['data'] + else: + run_prime_trace_content = None + if run_trace_content is not None: def _check_array(array, type_): for line in array: diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index f1bdcee387..499ddb561f 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -124,7 +124,8 @@ def _remove_random_state(flow): self.assertIsInstance(run.dataset_id, int) run_xml = run._create_description_xml() - run_trace = run.trace._trace_to_arff() + if run.trace is not None: + run_trace = run.trace._trace_to_arff() # check arff output self.assertEqual(len(run.data_content), num_instances) From fce97c3c7d2f73de8126f60ce9afb2145c8e24ad Mon Sep 17 00:00:00 2001 From: ArlindKadra Date: Tue, 26 Jun 2018 14:34:29 +0200 Subject: [PATCH 06/29] Fixing failing unit tests because of the run refactoring --- openml/runs/functions.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/openml/runs/functions.py b/openml/runs/functions.py index 2afa361ad1..34ddc30edf 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -122,11 +122,14 @@ def run_flow_on_task(flow, task, avoid_duplicate_runs=True, flow_tags=None, if not isinstance(flow.flow_id, int) or flow_id == False: _publish_flow_if_necessary(flow) + data_content, trace_content, trace_attributes, fold_evaluations, sample_evaluations = res + run = OpenMLRun(task_id=task.task_id, flow_id=flow.flow_id, - dataset_id=dataset.dataset_id, model=flow.model, tags=tags) + dataset_id=dataset.dataset_id, model=flow.model, tags=tags, + trace_content=trace_content, trace_attributes=trace_attributes, + data_content=data_content) run.parameter_settings = OpenMLRun._parse_parameters(flow) - run.data_content, run.trace_content, run.trace_attributes, fold_evaluations, sample_evaluations = res # now we need to attach the detailed evaluations if task.task_type_id == 3: run.sample_evaluations = sample_evaluations From a25036a3f655b25f2e35799f2b7a876ddb9c2b7f Mon Sep 17 00:00:00 2001 From: ArlindKadra Date: Tue, 26 Jun 2018 14:54:00 +0200 Subject: [PATCH 07/29] Arff byte object expected fix --- openml/runs/run.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openml/runs/run.py b/openml/runs/run.py index 3c1c9f64be..1f601dbbd9 100644 --- a/openml/runs/run.py +++ b/openml/runs/run.py @@ -339,7 +339,7 @@ def publish(self): file_elements['predictions'] = ("predictions.arff", predictions) if self.trace is not None: - trace_arff = self.trace._trace_to_arff() + trace_arff = arff.dumps(self.trace._trace_to_arff()) file_elements['trace'] = ("trace.arff", trace_arff) return_value = openml._api_calls._perform_api_call("/run/", file_elements=file_elements) From 76eb2c988cce2c9057dac6ce3f14e130f36f7f28 Mon Sep 17 00:00:00 2001 From: ArlindKadra Date: Tue, 26 Jun 2018 17:03:45 +0200 Subject: [PATCH 08/29] Fixing OpenMLRun does not have attribute trace_content --- tests/test_runs/test_run_functions.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index 499ddb561f..b28f39092c 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -325,16 +325,16 @@ def _run_and_upload(self, clf, rsv): accuracy_scores_provided.append( run.fold_evaluations['predictive_accuracy'][rep][fold]) self.assertEquals(sum(accuracy_scores_provided), sum(accuracy_scores)) - + trace_content = run.trace._trace_to_arff()['data'] if isinstance(clf, BaseSearchCV): if isinstance(clf, GridSearchCV): grid_iterations = 1 for param in clf.param_grid: grid_iterations *= len(clf.param_grid[param]) - self.assertEqual(len(run.trace_content), + self.assertEqual(len(trace_content), grid_iterations * num_folds) else: - self.assertEqual(len(run.trace_content), + self.assertEqual(len(trace_content), num_iterations * num_folds) check_res = self._check_serialized_optimized_run(run.run_id) self.assertTrue(check_res) From 31b8563258fa4de1f48dd027b6f62264c270a74c Mon Sep 17 00:00:00 2001 From: ArlindKadra Date: Wed, 27 Jun 2018 13:28:40 +0200 Subject: [PATCH 09/29] Fix NoneType has no attribute ... --- 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 b28f39092c..6fb6cf07fd 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -325,8 +325,8 @@ def _run_and_upload(self, clf, rsv): accuracy_scores_provided.append( run.fold_evaluations['predictive_accuracy'][rep][fold]) self.assertEquals(sum(accuracy_scores_provided), sum(accuracy_scores)) - trace_content = run.trace._trace_to_arff()['data'] if isinstance(clf, BaseSearchCV): + trace_content = run.trace._trace_to_arff()['data'] if isinstance(clf, GridSearchCV): grid_iterations = 1 for param in clf.param_grid: From 3e184f4b12a5348a72dfaf45456c82815b8642b9 Mon Sep 17 00:00:00 2001 From: ArlindKadra Date: Wed, 27 Jun 2018 14:50:05 +0200 Subject: [PATCH 10/29] Fixing the addition of setup_string in trace --- openml/runs/trace.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/openml/runs/trace.py b/openml/runs/trace.py index 72460f6f89..d1717a8017 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -161,7 +161,8 @@ def trace_from_arff(cls, arff_obj): iteration = int(itt[attribute_idx['iteration']]) evaluation = float(itt[attribute_idx['evaluation']]) if flag_ss: - setup_string = str(itt[attribute_idx['setup_string']]) + if setup_string != 'None': + setup_string = str(itt[attribute_idx['setup_string']]) else: setup_string = None selected_value = itt[attribute_idx['selected']] From 43b6b626bbf134e126fb20c8ee2c41ac9ba8e321 Mon Sep 17 00:00:00 2001 From: ArlindKadra Date: Wed, 27 Jun 2018 15:38:15 +0200 Subject: [PATCH 11/29] Fixing bug --- openml/runs/trace.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/openml/runs/trace.py b/openml/runs/trace.py index d1717a8017..c82c6b0b33 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -160,11 +160,10 @@ def trace_from_arff(cls, arff_obj): fold = int(itt[attribute_idx['fold']]) iteration = int(itt[attribute_idx['iteration']]) evaluation = float(itt[attribute_idx['evaluation']]) + setup_string = None if flag_ss: - if setup_string != 'None': + if itt[attribute_idx['setup_string']] != None: setup_string = str(itt[attribute_idx['setup_string']]) - else: - setup_string = None selected_value = itt[attribute_idx['selected']] if selected_value == 'true': selected = True From fc2ec97047762f5d4fd67fae04cf2da19f93083a Mon Sep 17 00:00:00 2001 From: ArlindKadra Date: Wed, 18 Jul 2018 19:25:02 +0100 Subject: [PATCH 12/29] Refactoring code --- openml/runs/functions.py | 14 ++++-- openml/runs/run.py | 55 ++++++++++++--------- openml/runs/trace.py | 101 +++++++++++++++++++++------------------ 3 files changed, 97 insertions(+), 73 deletions(-) diff --git a/openml/runs/functions.py b/openml/runs/functions.py index 34ddc30edf..e13da9a961 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -124,10 +124,16 @@ def run_flow_on_task(flow, task, avoid_duplicate_runs=True, flow_tags=None, data_content, trace_content, trace_attributes, fold_evaluations, sample_evaluations = res - run = OpenMLRun(task_id=task.task_id, flow_id=flow.flow_id, - dataset_id=dataset.dataset_id, model=flow.model, tags=tags, - trace_content=trace_content, trace_attributes=trace_attributes, - data_content=data_content) + run = OpenMLRun( + task_id=task.task_id, + flow_id=flow.flow_id, + dataset_id=dataset.dataset_id, + model=flow.model, + tags=tags, + trace_content=trace_content, + trace_attributes=trace_attributes, + data_content=data_content, + ) run.parameter_settings = OpenMLRun._parse_parameters(flow) # now we need to attach the detailed evaluations diff --git a/openml/runs/run.py b/openml/runs/run.py index 1f601dbbd9..d93795c1fc 100644 --- a/openml/runs/run.py +++ b/openml/runs/run.py @@ -48,10 +48,7 @@ def __init__(self, task_id, flow_id, dataset_id, setup_string=None, self.sample_evaluations = sample_evaluations self.data_content = data_content self.output_files = output_files - try: - self.trace = self._generate_trace(trace_attributes, trace_content) - except ValueError: - self.trace = None + self.trace = self._generate_trace(trace_attributes, trace_content) self.error_message = None self.task = task self.flow = flow @@ -189,39 +186,53 @@ def _generate_arff_dict(self): arff_dict['relation'] = 'openml_task_' + str(task.task_id) + '_predictions' return arff_dict - def _generate_trace(self, trace_attributes, trace_content): + def _generate_trace(self, attributes, content): + """Generates an OpenMLRunTrace. + + Generates the trace object from the attributes and content. + + Returns + ------- + OpenMLRunTrace + """ - if trace_content is None or len(trace_content) == 0: - raise ValueError('No trace content available.') - if trace_attributes is None or len(trace_attributes) != len(trace_content[0]): - raise ValueError('Trace_attributes and trace_content not compatible') + if content is None: + if attributes is None: + return None + else: + raise ValueError('Trace content not available.') + if len(content) == 0: + raise ValueError('Trace content is empty.') + if attributes is not None: + if len(attributes) != len(content[0]): + raise ValueError('Trace_attributes and trace_content not compatible') + else: + raise ValueError('No trace attributes available') trace = OrderedDict() - attribute_idx = {att[0]: idx for idx, att in enumerate(trace_attributes)} + attribute_idx = {att[0]: idx for idx, att in enumerate(attributes)} for required_attribute in ['repeat', 'fold', 'iteration', 'evaluation', 'selected']: if required_attribute not in attribute_idx: raise ValueError('arff misses required attribute: %s' % required_attribute) - for itt in trace_content: + for itt in content: repeat = int(itt[attribute_idx['repeat']]) fold = int(itt[attribute_idx['fold']]) iteration = int(itt[attribute_idx['iteration']]) evaluation = float(itt[attribute_idx['evaluation']]) - selectedValue = itt[attribute_idx['selected']] - if selectedValue == 'true': + selected_value = itt[attribute_idx['selected']] + if 'setup_string' in attribute_idx: + setup_string = json.dumps(itt[attribute_idx['setup_string']]) + else: + setup_string = None + if selected_value == 'true': selected = True - elif selectedValue == 'false': + elif selected_value == 'false': selected = False else: - raise ValueError('expected {"true", "false"} value for selected field, received: %s' % selectedValue) - - # TODO: if someone needs it, he can use the parameter - # fields to revive the setup_string as well - # However, this is usually done by the OpenML server - # and if we are going to duplicate this functionality - # it needs proper testing + raise ValueError('expected {"true", "false"} value for selected field, received: %s' % selected_value) - current = OpenMLTraceIteration(repeat, fold, iteration, None, evaluation, selected) + current = OpenMLTraceIteration(repeat, fold, iteration, setup_string, evaluation, selected) trace[(repeat, fold, iteration)] = current return OpenMLRunTrace(None, trace) diff --git a/openml/runs/trace.py b/openml/runs/trace.py index c82c6b0b33..07b7d10a66 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -101,14 +101,16 @@ def _trace_to_arff(self): """ if self.trace_iterations is None: raise ValueError("trace_iterations missing from the trace object") + # attributes that will be in trace arff - trace_attributes = [('repeat', 'NUMERIC'), - ('fold', 'NUMERIC'), - ('iteration', 'NUMERIC'), - ('evaluation', 'NUMERIC'), - ('selected', ['true', 'false']), - ('setup_string', 'STRING') - ] + trace_attributes = [ + ('repeat', 'NUMERIC'), + ('fold', 'NUMERIC'), + ('iteration', 'NUMERIC'), + ('evaluation', 'NUMERIC'), + ('selected', ['true', 'false']), + ('setup_string', 'STRING'), + ] arff_dict = OrderedDict() data = [] for trace_iteration in self.trace_iterations.values(): @@ -145,47 +147,21 @@ def trace_from_arff(cls, arff_obj): ------- OpenMLRunTrace """ - trace = OrderedDict() # flag if setup string is in attributes - flag_ss = False + flag_ss = True 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: raise ValueError('arff misses required attribute: %s' % required_attribute) - if 'setup_string' in attribute_idx: - flag_ss = True - - for itt in arff_obj['data']: - repeat = int(itt[attribute_idx['repeat']]) - fold = int(itt[attribute_idx['fold']]) - iteration = int(itt[attribute_idx['iteration']]) - evaluation = float(itt[attribute_idx['evaluation']]) - setup_string = None - if flag_ss: - if itt[attribute_idx['setup_string']] != None: - setup_string = str(itt[attribute_idx['setup_string']]) - selected_value = itt[attribute_idx['selected']] - if selected_value == 'true': - selected = True - elif selected_value == 'false': - selected = False - else: - raise ValueError('expected {"true", "false"} value for selected field, received: %s' % selected_value) + if 'setup_string' not in attribute_idx: + flag_ss = False - # if someone needs it, he can use the parameter - # fields to revive the setup_string as well - # However, this is usually done by the OpenML server - # and if we are going to duplicate this functionality - # it needs proper testing - - current = OpenMLTraceIteration(repeat, fold, iteration, setup_string, - evaluation, selected) - trace[(repeat, fold, iteration)] = current + trace = cls._trace_from_iterations_dict(arff_obj['data'], flag_ss) return cls(None, trace) @classmethod - def _trace_from_xml(cls, xml): + def trace_from_xml(cls, xml): """Generate trace from xml. Creates a trace file from the xml description. @@ -203,7 +179,7 @@ def _trace_from_xml(cls, xml): result_dict = xmltodict.parse(xml, force_list=('oml:trace_iteration',))['oml:trace'] run_id = result_dict['oml:run_id'] - trace = OrderedDict() + if 'oml:trace_iteration' not in result_dict: raise ValueError('Run does not contain valid trace. ') @@ -211,14 +187,39 @@ def _trace_from_xml(cls, xml): assert type(result_dict['oml:trace_iteration']) == list, \ type(result_dict['oml:trace_iteration']) - for itt in result_dict['oml:trace_iteration']: + trace = cls._trace_from_iterations_dict(result_dict['oml:trace_iteration']) + + return cls(run_id, trace) + + @staticmethod + def _trace_from_iterations_dict(trace_iterations, setup_flag=True): + """Creates a trace dictionary. + + Create a dictionary that includes multiple trace iterations. + + Parameters + ---------- + trace_iterations : list + List of dicts containing trace_iteration information. + + Returns + ------- + trace : OrderedDict + Mapping from key ``(repeat, fold, iteration)`` to an object of + OpenMLTraceIteration. + """ + trace = OrderedDict() + + for itt in trace_iterations: + repeat = int(itt['oml:repeat']) fold = int(itt['oml:fold']) iteration = int(itt['oml:iteration']) - setup_string = json.loads(itt['oml:setup_string']) + if setup_flag: + setup_string = json.loads(itt['oml:setup_string']) evaluation = float(itt['oml:evaluation']) - selected_value = itt['oml:selected'] + if selected_value == 'true': selected = True elif selected_value == 'false': @@ -227,12 +228,18 @@ def _trace_from_xml(cls, xml): raise ValueError('expected {"true", "false"} value for ' 'selected field, received: %s' % selected_value) - current = OpenMLTraceIteration(repeat, fold, iteration, - setup_string, evaluation, - selected) - trace[(repeat, fold, iteration)] = current + trace_iteration = OpenMLTraceIteration( + repeat, + fold, + iteration, + setup_string, + evaluation, + selected, + ) - return cls(run_id, trace) + trace[(repeat, fold, iteration)] = trace_iteration + + return trace def __str__(self): return '[Run id: %d, %d trace iterations]' % (self.run_id, len(self.trace_iterations)) From c2bf97372cc627e0cba12716004c3aa37fea24a2 Mon Sep 17 00:00:00 2001 From: ArlindKadra Date: Wed, 18 Jul 2018 20:07:49 +0100 Subject: [PATCH 13/29] Reverting changes to trace and fixing bugs --- openml/runs/functions.py | 2 +- openml/runs/trace.py | 79 +++++++++++++++++++++------------------- 2 files changed, 43 insertions(+), 38 deletions(-) diff --git a/openml/runs/functions.py b/openml/runs/functions.py index e13da9a961..29d43d8089 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -179,7 +179,7 @@ def get_run_trace(run_id): """ trace_xml = openml._api_calls._perform_api_call('run/trace/%d' % run_id) - run_trace = OpenMLRunTrace._trace_from_xml(trace_xml) + run_trace = OpenMLRunTrace.trace_from_xml(trace_xml) return run_trace diff --git a/openml/runs/trace.py b/openml/runs/trace.py index 07b7d10a66..674fc33f68 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -147,16 +147,48 @@ def trace_from_arff(cls, arff_obj): ------- OpenMLRunTrace """ + trace = OrderedDict() # flag if setup string is in attributes - flag_ss = True + flag_ss = False 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: raise ValueError('arff misses required attribute: %s' % required_attribute) - if 'setup_string' not in attribute_idx: - flag_ss = False + if 'setup_string' in attribute_idx: + flag_ss = True + + for itt in arff_obj['data']: + repeat = int(itt[attribute_idx['repeat']]) + fold = int(itt[attribute_idx['fold']]) + iteration = int(itt[attribute_idx['iteration']]) + evaluation = float(itt[attribute_idx['evaluation']]) + setup_string = None + if flag_ss: + if itt[attribute_idx['setup_string']] != None: + setup_string = json.loads(itt[attribute_idx['setup_string']]) + selected_value = itt[attribute_idx['selected']] + if selected_value == 'true': + selected = True + elif selected_value == 'false': + selected = False + else: + raise ValueError('expected {"true", "false"} value for selected field, received: %s' % selected_value) - trace = cls._trace_from_iterations_dict(arff_obj['data'], flag_ss) + # if someone needs it, he can use the parameter + # fields to revive the setup_string as well + # However, this is usually done by the OpenML server + # and if we are going to duplicate this functionality + # it needs proper testing + + current = OpenMLTraceIteration( + repeat, + fold, + iteration, + setup_string, + evaluation, + selected, + ) + trace[(repeat, fold, iteration)] = current return cls(None, trace) @@ -179,7 +211,7 @@ def trace_from_xml(cls, xml): result_dict = xmltodict.parse(xml, force_list=('oml:trace_iteration',))['oml:trace'] run_id = result_dict['oml:run_id'] - + trace = OrderedDict() if 'oml:trace_iteration' not in result_dict: raise ValueError('Run does not contain valid trace. ') @@ -187,39 +219,13 @@ def trace_from_xml(cls, xml): assert type(result_dict['oml:trace_iteration']) == list, \ type(result_dict['oml:trace_iteration']) - trace = cls._trace_from_iterations_dict(result_dict['oml:trace_iteration']) - - return cls(run_id, trace) - - @staticmethod - def _trace_from_iterations_dict(trace_iterations, setup_flag=True): - """Creates a trace dictionary. - - Create a dictionary that includes multiple trace iterations. - - Parameters - ---------- - trace_iterations : list - List of dicts containing trace_iteration information. - - Returns - ------- - trace : OrderedDict - Mapping from key ``(repeat, fold, iteration)`` to an object of - OpenMLTraceIteration. - """ - trace = OrderedDict() - - for itt in trace_iterations: - + for itt in result_dict['oml:trace_iteration']: repeat = int(itt['oml:repeat']) fold = int(itt['oml:fold']) iteration = int(itt['oml:iteration']) - if setup_flag: - setup_string = json.loads(itt['oml:setup_string']) + setup_string = json.loads(itt['oml:setup_string']) evaluation = float(itt['oml:evaluation']) selected_value = itt['oml:selected'] - if selected_value == 'true': selected = True elif selected_value == 'false': @@ -228,7 +234,7 @@ def _trace_from_iterations_dict(trace_iterations, setup_flag=True): raise ValueError('expected {"true", "false"} value for ' 'selected field, received: %s' % selected_value) - trace_iteration = OpenMLTraceIteration( + current = OpenMLTraceIteration( repeat, fold, iteration, @@ -236,10 +242,9 @@ def _trace_from_iterations_dict(trace_iterations, setup_flag=True): evaluation, selected, ) + trace[(repeat, fold, iteration)] = current - trace[(repeat, fold, iteration)] = trace_iteration - - return trace + return cls(run_id, trace) def __str__(self): return '[Run id: %d, %d trace iterations]' % (self.run_id, len(self.trace_iterations)) From a150e27e287c7af679060e3caabf4dc6d5aec067 Mon Sep 17 00:00:00 2001 From: janvanrijn Date: Wed, 12 Sep 2018 17:42:39 -0400 Subject: [PATCH 14/29] sklearn converter first attempt --- openml/flows/sklearn_converter.py | 14 +++++++--- tests/test_flows/test_sklearn.py | 43 ++++++++++++++++++++++++++----- 2 files changed, 48 insertions(+), 9 deletions(-) diff --git a/openml/flows/sklearn_converter.py b/openml/flows/sklearn_converter.py index 60f07a1247..9f12f90999 100644 --- a/openml/flows/sklearn_converter.py +++ b/openml/flows/sklearn_converter.py @@ -305,15 +305,21 @@ 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 is 2 for {VotingClassifier.estimators, Pipeline.steps, FeatureUnion.transformer_list} + 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 +348,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 +428,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 2fb03e69e4..94939d14da 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 @@ -101,7 +102,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() @@ -141,7 +141,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()) @@ -189,8 +188,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,' \ @@ -244,11 +243,43 @@ def test_serialize_pipeline(self): self.assertEqual(new_model_params, fu_params) new_model.fit(self.X, self.y) + def test_serialize_column_transformer(self): + # electricity does not have missing values, but does have nominal and numeric values + # task id 168 and dataset id 28 + task = openml.tasks.get_task(168) + nominal_indices = task.get_dataset().get_features_by_type('nominal', [task.target_name]) + numeric_indices = task.get_dataset().get_features_by_type('numeric', [task.target_name]) + + model = sklearn.compose.ColumnTransformer( + transformers=[ + ('numeric', sklearn.preprocessing.StandardScaler(), numeric_indices), + ('nominal', sklearn.preprocessing.OneHotEncoder(handle_unknown='ignore'), nominal_indices)], + 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_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,' \ From 92cba02a8ecd77012dc7c85f8bdf17b5d96562ed Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Thu, 13 Sep 2018 09:28:47 +0200 Subject: [PATCH 15/29] Revert "sklearn converter first attempt" This reverts commit a150e27e287c7af679060e3caabf4dc6d5aec067. --- openml/flows/sklearn_converter.py | 14 +++------- tests/test_flows/test_sklearn.py | 43 +++++-------------------------- 2 files changed, 9 insertions(+), 48 deletions(-) diff --git a/openml/flows/sklearn_converter.py b/openml/flows/sklearn_converter.py index 9f12f90999..60f07a1247 100644 --- a/openml/flows/sklearn_converter.py +++ b/openml/flows/sklearn_converter.py @@ -305,21 +305,15 @@ 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))])): + [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_tuple[0] - sub_component = sub_component_tuple[1] + identifier, sub_component = sub_component_tuple sub_component_type = type(sub_component_tuple) - if not 2 <= len(sub_component_tuple) <= 3: - # length is 2 for {VotingClassifier.estimators, Pipeline.steps, FeatureUnion.transformer_list} - 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__ + "." + \ @@ -348,8 +342,6 @@ 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) @@ -428,7 +420,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 94939d14da..2fb03e69e4 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 @@ -102,6 +101,7 @@ 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() @@ -141,6 +141,7 @@ 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()) @@ -188,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,' \ @@ -243,43 +244,11 @@ def test_serialize_pipeline(self): self.assertEqual(new_model_params, fu_params) new_model.fit(self.X, self.y) - def test_serialize_column_transformer(self): - # electricity does not have missing values, but does have nominal and numeric values - # task id 168 and dataset id 28 - task = openml.tasks.get_task(168) - nominal_indices = task.get_dataset().get_features_by_type('nominal', [task.target_name]) - numeric_indices = task.get_dataset().get_features_by_type('numeric', [task.target_name]) - - model = sklearn.compose.ColumnTransformer( - transformers=[ - ('numeric', sklearn.preprocessing.StandardScaler(), numeric_indices), - ('nominal', sklearn.preprocessing.OneHotEncoder(handle_unknown='ignore'), nominal_indices)], - 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_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,' \ From f5dfda5c93682a502be0b8bf6fbd7ddf06d47c69 Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Thu, 13 Sep 2018 11:20:26 +0200 Subject: [PATCH 16/29] one step further to make this refactoring work --- openml/runs/functions.py | 2 +- openml/runs/run.py | 36 +++++++++++++++----- openml/runs/trace.py | 47 +++++++++++++++++++++++---- openml/testing.py | 2 +- tests/test_runs/test_run_functions.py | 28 +++++++++++++--- 5 files changed, 93 insertions(+), 22 deletions(-) diff --git a/openml/runs/functions.py b/openml/runs/functions.py index 333743c834..9a31815697 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -678,7 +678,7 @@ def _extract_arfftrace_attributes(model): # we renamed the attribute param to parameter, as this is a required # OpenML convention - attribute = ("parameter_" + key[6:], type) + attribute = (key[6:], type) trace_attributes.append(attribute) return trace_attributes diff --git a/openml/runs/run.py b/openml/runs/run.py index 56c621cc13..4f76791479 100644 --- a/openml/runs/run.py +++ b/openml/runs/run.py @@ -202,7 +202,8 @@ def _generate_arff_dict(self): def _generate_trace(self, attributes, content): """Generates an OpenMLRunTrace. - Generates the trace object from the attributes and content. + Generates the trace object from the attributes and content extracted + while running the underlying flow. Returns ------- @@ -224,9 +225,15 @@ def _generate_trace(self, attributes, content): trace = OrderedDict() attribute_idx = {att[0]: idx for idx, att in enumerate(attributes)} - for required_attribute in ['repeat', 'fold', 'iteration', 'evaluation', 'selected']: + + required_attributes = ['repeat', 'fold', 'iteration', 'evaluation', 'selected'] + for required_attribute in required_attributes: if required_attribute not in attribute_idx: raise ValueError('arff misses required attribute: %s' % required_attribute) + parameter_attributes = [] + for attribute in attribute_idx: + if attribute not in required_attributes and attribute != 'setup_string': + parameter_attributes.append(attribute) for itt in content: repeat = int(itt[attribute_idx['repeat']]) @@ -235,17 +242,30 @@ def _generate_trace(self, attributes, content): evaluation = float(itt[attribute_idx['evaluation']]) selected_value = itt[attribute_idx['selected']] if 'setup_string' in attribute_idx: - setup_string = json.dumps(itt[attribute_idx['setup_string']]) - else: - setup_string = None + raise ValueError( + 'setup_string not allowed when constructing a trace object' + ' run results.' + ) + setup_string = None if selected_value == 'true': selected = True elif selected_value == 'false': selected = False else: raise ValueError('expected {"true", "false"} value for selected field, received: %s' % selected_value) - - current = OpenMLTraceIteration(repeat, fold, iteration, setup_string, evaluation, selected) + parameters = OrderedDict() + for attribute in parameter_attributes: + parameters[attribute] = itt[attribute_idx[attribute]] + + current = OpenMLTraceIteration( + repeat, + fold, + iteration, + setup_string, + evaluation, + selected, + paramaters=parameters + ) trace[(repeat, fold, iteration)] = current return OpenMLRunTrace(None, trace) @@ -363,7 +383,7 @@ def publish(self): file_elements['predictions'] = ("predictions.arff", predictions) if self.trace is not None: - trace_arff = arff.dumps(self.trace._trace_to_arff()) + trace_arff = arff.dumps(self.trace.trace_to_arff()) file_elements['trace'] = ("trace.arff", trace_arff) return_value = openml._api_calls._perform_api_call("/run/", file_elements=file_elements) diff --git a/openml/runs/trace.py b/openml/runs/trace.py index 674fc33f68..993ca11688 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -84,11 +84,11 @@ def to_filesystem(self, file_path): File path where the trace arff will be stored. """ - trace_arff = arff.dumps(self._trace_to_arff()) + trace_arff = arff.dumps(self.trace_to_arff()) with open(os.path.join(file_path, 'trace.arff'), 'w') as f: f.write(trace_arff) - def _trace_to_arff(self): + def trace_to_arff(self): """Generates the arff dictionary for uploading predictions to the server. Uses the trace object to generate an arff dictionary representation. @@ -109,14 +109,20 @@ def _trace_to_arff(self): ('iteration', 'NUMERIC'), ('evaluation', 'NUMERIC'), ('selected', ['true', 'false']), - ('setup_string', 'STRING'), ] + for parameter in next(iter(self.trace_iterations.values())).get_parameters(): + trace_attributes.append(('parameter_' + parameter, 'STRING')) + arff_dict = OrderedDict() data = [] for trace_iteration in self.trace_iterations.values(): tit_list = [] for attr, attr_type in trace_attributes: - value = getattr(trace_iteration, attr) + if attr.startswith('parameter_'): + attr = attr[len('parameter_'):] + value = trace_iteration.get_parameters()[attr] + else: + value = getattr(trace_iteration, attr) if attr == 'selected': if value: tit_list.append('true') @@ -129,7 +135,6 @@ def _trace_to_arff(self): arff_dict['attributes'] = trace_attributes arff_dict['data'] = data arff_dict['relation'] = "Trace" - return arff_dict @classmethod @@ -155,6 +160,7 @@ def trace_from_arff(cls, arff_obj): if required_attribute not in attribute_idx: raise ValueError('arff misses required attribute: %s' % required_attribute) if 'setup_string' in attribute_idx: + raise ValueError('setup_string not supported for arff serialization') flag_ss = True for itt in arff_obj['data']: @@ -164,7 +170,7 @@ def trace_from_arff(cls, arff_obj): evaluation = float(itt[attribute_idx['evaluation']]) setup_string = None if flag_ss: - if itt[attribute_idx['setup_string']] != None: + if itt[attribute_idx['setup_string']] is not None: setup_string = json.loads(itt[attribute_idx['setup_string']]) selected_value = itt[attribute_idx['selected']] if selected_value == 'true': @@ -275,17 +281,44 @@ class OpenMLTraceIteration(object): Whether this was the best of all iterations, and hence selected for making predictions. Per fold/repeat there should be only one iteration selected + + parameters : OrderedDict """ - def __init__(self, repeat, fold, iteration, setup_string, evaluation, selected): + def __init__( + self, + repeat, + fold, + iteration, + setup_string, + evaluation, + selected, + paramaters=None, + ): + + if setup_string and paramaters: + raise ValueError( + 'Can only be instantiated with either ' + 'setup_string or parameters argument.' + ) + if paramaters is not None and not isinstance(paramaters, OrderedDict): + raise TypeError( + 'argument parameters is not an instance of OrderedDict, but %s' + % str(type(paramaters)) + ) + self.repeat = repeat self.fold = fold self.iteration = iteration self.setup_string = setup_string self.evaluation = evaluation self.selected = selected + self.parameters = paramaters def get_parameters(self): + if self.parameters: + return self.parameters + result = {} # parameters have prefix 'parameter_' prefix = 'parameter_' diff --git a/openml/testing.py b/openml/testing.py index b4aee20b5d..b461029d6b 100644 --- a/openml/testing.py +++ b/openml/testing.py @@ -49,7 +49,7 @@ def setUp(self): self.cached = True # amueller's read/write key that he will throw away later openml.config.apikey = "610344db6388d9ba34f6db45a3cf71de" - self.production_server = openml.config.server + self.production_server = "https://openml.org/api/v1/xml" self.test_server = "https://test.openml.org/api/v1/xml" openml.config.cache_directory = None diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index 405568e4f2..2f78da29ad 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -125,7 +125,7 @@ def _remove_random_state(flow): run_xml = run._create_description_xml() if run.trace is not None: - run_trace = run.trace._trace_to_arff() + run_trace = run.trace.trace_to_arff() # check arff output self.assertEqual(len(run.data_content), num_instances) @@ -326,7 +326,7 @@ def _run_and_upload(self, clf, rsv): run.fold_evaluations['predictive_accuracy'][rep][fold]) self.assertEquals(sum(accuracy_scores_provided), sum(accuracy_scores)) if isinstance(clf, BaseSearchCV): - trace_content = run.trace._trace_to_arff()['data'] + trace_content = run.trace.trace_to_arff()['data'] if isinstance(clf, GridSearchCV): grid_iterations = 1 for param in clf.param_grid: @@ -554,7 +554,9 @@ def test_get_run_trace(self): try: # in case the run did not exists yet run = openml.runs.run_model_on_task(task, clf, avoid_duplicate_runs=True) - trace = openml.runs.trace.trace_from_arff(run._generate_trace_arff_dict()) + trace = openml.runs.trace.OpenMLRunTrace.trace_from_arff( + run.trace.trace_to_arff() + ) self.assertEquals( len(trace.trace_iterations), num_iterations * num_folds, @@ -692,6 +694,7 @@ def test__extract_arfftrace(self): for att_idx in range(len(trace_attribute_list)): att_type = trace_attribute_list[att_idx][1] att_name = trace_attribute_list[att_idx][0] + # They no longer start with parameter_ if they come from extract_arff_trace! if att_name.startswith("parameter_"): # add this to the found parameters param_name = att_name[len("parameter_"):] @@ -707,10 +710,25 @@ def test__extract_arfftrace(self): val = trace_list[line_idx][att_idx] if isinstance(att_type, list): self.assertIn(val, att_type) + elif att_name in ['hidden_layer_sizes', 'activation', 'learning_rate_init', 'max_iter']: + self.assertIsInstance( + trace_list[line_idx][att_idx], + str, + msg=att_name + ) + optimized_params.add(att_name) elif att_name in ['repeat', 'fold', 'iteration']: - self.assertIsInstance(trace_list[line_idx][att_idx], int) + self.assertIsInstance( + trace_list[line_idx][att_idx], + int, + msg=att_name + ) else: # att_type = real - self.assertIsInstance(trace_list[line_idx][att_idx], float) + self.assertIsInstance( + trace_list[line_idx][att_idx], + float, + msg=att_name + ) self.assertEqual(set(param_grid.keys()), optimized_params) From 2993d10d1f4abc217255291c4aa072306e965a3e Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Thu, 13 Sep 2018 12:04:16 +0200 Subject: [PATCH 17/29] MAINT fix non-refactored function calls --- openml/runs/functions.py | 5 ++++- tests/test_runs/test_run.py | 4 ++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/openml/runs/functions.py b/openml/runs/functions.py index 9a31815697..c722d7d3b1 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -141,7 +141,10 @@ def run_flow_on_task(flow, task, avoid_duplicate_runs=True, flow_tags=None, # through "run_model_on_task" if flow.flow_id != flow_id: # This should never happen, unless user made a flow-creation fault - raise ValueError('Result flow_exists and flow.flow_id are not same. ') + raise ValueError( + "Result from API call flow_exists and flow.flow_id are not " + "same: '%s' vs '%s'" % (str(flow.flow_id), str(flow_id)) + ) run = OpenMLRun( task_id=task.task_id, diff --git a/tests/test_runs/test_run.py b/tests/test_runs/test_run.py index 5b435296af..c0427e3a46 100644 --- a/tests/test_runs/test_run.py +++ b/tests/test_runs/test_run.py @@ -94,12 +94,12 @@ def _test_run_obj_equals(self, run, run_prime): np.testing.assert_array_equal(string_part, string_part_prime) if run.trace is not None: - run_trace_content = run.trace._trace_to_arff()['data'] + run_trace_content = run.trace.trace_to_arff()['data'] else: run_trace_content = None if run_prime.trace is not None: - run_prime_trace_content = run_prime.trace._trace_to_arff()['data'] + run_prime_trace_content = run_prime.trace.trace_to_arff()['data'] else: run_prime_trace_content = None From 630ef849653690f121234e5b55b8fd60fe8661e5 Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Thu, 20 Sep 2018 09:54:29 +0200 Subject: [PATCH 18/29] fix a few unit tests --- openml/runs/trace.py | 45 +++++++++++++++------------ tests/test_runs/test_run_functions.py | 16 +++++++--- 2 files changed, 37 insertions(+), 24 deletions(-) diff --git a/openml/runs/trace.py b/openml/runs/trace.py index 993ca11688..c163db1fdd 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -4,6 +4,8 @@ import xmltodict from collections import OrderedDict +PREFIX = 'parameter_' + class OpenMLRunTrace(object): """OpenML Run Trace: parsed output from Run Trace call @@ -154,24 +156,19 @@ def trace_from_arff(cls, arff_obj): """ trace = OrderedDict() # flag if setup string is in attributes - flag_ss = False attribute_idx = {att[0]: idx for idx, att in enumerate(arff_obj['attributes'])} - for required_attribute in ['repeat', 'fold', 'iteration', 'evaluation', 'selected']: + required_attributes = ['repeat', 'fold', 'iteration', 'evaluation', 'selected'] + for required_attribute in required_attributes: if required_attribute not in attribute_idx: raise ValueError('arff misses required attribute: %s' % required_attribute) if 'setup_string' in attribute_idx: raise ValueError('setup_string not supported for arff serialization') - flag_ss = True for itt in arff_obj['data']: repeat = int(itt[attribute_idx['repeat']]) fold = int(itt[attribute_idx['fold']]) iteration = int(itt[attribute_idx['iteration']]) evaluation = float(itt[attribute_idx['evaluation']]) - setup_string = None - if flag_ss: - if itt[attribute_idx['setup_string']] is not None: - setup_string = json.loads(itt[attribute_idx['setup_string']]) selected_value = itt[attribute_idx['selected']] if selected_value == 'true': selected = True @@ -180,19 +177,22 @@ def trace_from_arff(cls, arff_obj): else: raise ValueError('expected {"true", "false"} value for selected field, received: %s' % selected_value) - # if someone needs it, he can use the parameter - # fields to revive the setup_string as well - # However, this is usually done by the OpenML server - # and if we are going to duplicate this functionality - # it needs proper testing + parameters = OrderedDict() + for attribute_name, idx in attribute_idx.items(): + if attribute_name in required_attributes: + continue + if attribute_name.startswith(PREFIX): + parameters[attribute_name] = itt[idx] + current = OpenMLTraceIteration( - repeat, - fold, - iteration, - setup_string, - evaluation, - selected, + repeat=repeat, + fold=fold, + iteration=iteration, + setup_string=None, + evaluation=evaluation, + selected=selected, + paramaters=parameters, ) trace[(repeat, fold, iteration)] = current @@ -301,6 +301,11 @@ def __init__( 'Can only be instantiated with either ' 'setup_string or parameters argument.' ) + elif not setup_string and not paramaters: + raise ValueError( + 'Either setup_string or parameters needs to be paased as ' + 'argument.' + ) if paramaters is not None and not isinstance(paramaters, OrderedDict): raise TypeError( 'argument parameters is not an instance of OrderedDict, but %s' @@ -321,10 +326,10 @@ def get_parameters(self): result = {} # parameters have prefix 'parameter_' - prefix = 'parameter_' + PREFIX = 'parameter_' for param in self.setup_string: - key = param[len(prefix):] + key = param[len(PREFIX):] result[key] = json.loads(self.setup_string[param]) return result diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index 2f78da29ad..8b8f35eb39 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -810,10 +810,18 @@ def test_run_with_illegal_flow_id_1(self): flow_new = sklearn_to_flow(clf) flow_new.flow_id = -1 - expected_message_regex = "Result flow_exists and flow.flow_id are not same." - self.assertRaisesRegexp(ValueError, expected_message_regex, - openml.runs.run_flow_on_task, task=task, flow=flow_new, - avoid_duplicate_runs=False) + expected_message_regex = ( + "Result from API call flow_exists and flow.flow_id are not same: " + "'-1' vs '[0-9]+'" + ) + self.assertRaisesRegexp( + ValueError, + expected_message_regex, + openml.runs.run_flow_on_task, + task=task, + flow=flow_new, + avoid_duplicate_runs=False, + ) def test__run_task_get_arffcontent(self): task = openml.tasks.get_task(7) From 22d2f7b6b9c4326cc358cd704d173a66e78096b1 Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Thu, 20 Sep 2018 10:10:51 +0200 Subject: [PATCH 19/29] MAINT please the style checker --- openml/runs/run.py | 3 ++- openml/runs/trace.py | 7 +++---- tests/test_runs/test_run_functions.py | 8 ++++++-- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/openml/runs/run.py b/openml/runs/run.py index 4f76791479..29bf851152 100644 --- a/openml/runs/run.py +++ b/openml/runs/run.py @@ -199,7 +199,8 @@ def _generate_arff_dict(self): arff_dict['relation'] = 'openml_task_' + str(task.task_id) + '_predictions' return arff_dict - def _generate_trace(self, attributes, content): + @staticmethod + def _generate_trace(attributes, content): """Generates an OpenMLRunTrace. Generates the trace object from the attributes and content extracted diff --git a/openml/runs/trace.py b/openml/runs/trace.py index c163db1fdd..e5828620a6 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -119,7 +119,7 @@ def trace_to_arff(self): data = [] for trace_iteration in self.trace_iterations.values(): tit_list = [] - for attr, attr_type in trace_attributes: + for attr, _ in trace_attributes: if attr.startswith('parameter_'): attr = attr[len('parameter_'):] value = trace_iteration.get_parameters()[attr] @@ -221,9 +221,8 @@ def trace_from_xml(cls, xml): if 'oml:trace_iteration' not in result_dict: raise ValueError('Run does not contain valid trace. ') - - assert type(result_dict['oml:trace_iteration']) == list, \ - type(result_dict['oml:trace_iteration']) + if not isinstance(result_dict['oml:trace_iteration'], list): + raise TypeError(type(result_dict['oml:trace_iteration'])) for itt in result_dict['oml:trace_iteration']: repeat = int(itt['oml:repeat']) diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index 8b8f35eb39..04a4e9e7ae 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -123,9 +123,13 @@ def _remove_random_state(flow): self.assertEqual(run_, run) self.assertIsInstance(run.dataset_id, int) - run_xml = run._create_description_xml() + # This is only a smoke check right now + # TODO add a few asserts here + run._create_description_xml() if run.trace is not None: - run_trace = run.trace.trace_to_arff() + # This is only a smoke check right now + # TODO add a few asserts here + run.trace.trace_to_arff() # check arff output self.assertEqual(len(run.data_content), num_instances) From bb4e25b3284622fbe69e99bc129247d5bd46e8cd Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Thu, 20 Sep 2018 10:39:59 +0200 Subject: [PATCH 20/29] fix merge error --- 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 82c848f93b..7ba80ec754 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -349,7 +349,7 @@ def determine_grid_size(param_grid): trace_content = run.trace.trace_to_arff()['data'] if isinstance(clf, GridSearchCV): grid_iterations = determine_grid_size(clf.param_grid) - self.assertEqual(len(run.trace_content), + self.assertEqual(len(trace_content), grid_iterations * num_folds) else: self.assertEqual(len(trace_content), From d7a94b93b91ccb5615b7825194e2e488192768fa Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Thu, 20 Sep 2018 17:26:10 +0200 Subject: [PATCH 21/29] MAINT move trace generation function into trace --- openml/runs/functions.py | 22 ++++---- openml/runs/run.py | 78 +------------------------- openml/runs/trace.py | 79 +++++++++++++++++++++++++++ tests/test_runs/test_run_functions.py | 28 +++++++--- 4 files changed, 113 insertions(+), 94 deletions(-) diff --git a/openml/runs/functions.py b/openml/runs/functions.py index 3883cc5f8a..13c4291982 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -127,7 +127,7 @@ def run_flow_on_task(flow, task, avoid_duplicate_runs=True, flow_tags=None, 'exist on the server according to flow_exists') _publish_flow_if_necessary(flow) - data_content, trace_content, trace_attributes, fold_evaluations, sample_evaluations = res + data_content, trace, fold_evaluations, sample_evaluations = res if not isinstance(flow.flow_id, int): # This is the usual behaviour, where the flow object was initiated off # line and requires some additional information (flow_id, input_id for @@ -153,8 +153,7 @@ def run_flow_on_task(flow, task, avoid_duplicate_runs=True, flow_tags=None, model=flow.model, flow_name=flow.name, tags=tags, - trace_content=trace_content, - trace_attributes=trace_attributes, + trace=trace, data_content=data_content, ) run.parameter_settings = OpenMLRun._parse_parameters(flow) @@ -484,15 +483,16 @@ def _prediction_to_probabilities(y, model_classes): if isinstance(model_fold, sklearn.model_selection._search.BaseSearchCV): # arff_tracecontent is already set arff_trace_attributes = _extract_arfftrace_attributes(model_fold) + trace = OpenMLRunTrace.generate(arff_trace_attributes, arff_tracecontent) else: - arff_tracecontent = None - arff_trace_attributes = None - - return arff_datacontent, \ - arff_tracecontent, \ - arff_trace_attributes, \ - user_defined_measures_per_fold, \ - user_defined_measures_per_sample + trace = None + + return ( + arff_datacontent, + trace, + user_defined_measures_per_fold, + user_defined_measures_per_sample, + ) def _run_model_on_fold(model, task, rep_no, fold_no, sample_no, can_measure_runtime, add_local_measures): diff --git a/openml/runs/run.py b/openml/runs/run.py index 29bf851152..148ddc160d 100644 --- a/openml/runs/run.py +++ b/openml/runs/run.py @@ -12,7 +12,7 @@ import openml import openml._api_calls -from .trace import OpenMLRunTrace, OpenMLTraceIteration +from .trace import OpenMLRunTrace from ..tasks import get_task from ..exceptions import PyOpenMLError @@ -28,7 +28,7 @@ class OpenMLRun(object): def __init__(self, task_id, flow_id, dataset_id, setup_string=None, output_files=None, setup_id=None, tags=None, uploader=None, uploader_name=None, evaluations=None, fold_evaluations=None, sample_evaluations=None, - data_content=None, trace_attributes=None, trace_content=None, + data_content=None, trace=None, model=None, task_type=None, task_evaluation_measure=None, flow_name=None, parameter_settings=None, predictions_url=None, task=None, flow=None, run_id=None): @@ -48,7 +48,7 @@ def __init__(self, task_id, flow_id, dataset_id, setup_string=None, self.sample_evaluations = sample_evaluations self.data_content = data_content self.output_files = output_files - self.trace = self._generate_trace(trace_attributes, trace_content) + self.trace = trace self.error_message = None self.task = task self.flow = flow @@ -199,78 +199,6 @@ def _generate_arff_dict(self): arff_dict['relation'] = 'openml_task_' + str(task.task_id) + '_predictions' return arff_dict - @staticmethod - def _generate_trace(attributes, content): - """Generates an OpenMLRunTrace. - - Generates the trace object from the attributes and content extracted - while running the underlying flow. - - Returns - ------- - OpenMLRunTrace - """ - - if content is None: - if attributes is None: - return None - else: - raise ValueError('Trace content not available.') - if len(content) == 0: - raise ValueError('Trace content is empty.') - if attributes is not None: - if len(attributes) != len(content[0]): - raise ValueError('Trace_attributes and trace_content not compatible') - else: - raise ValueError('No trace attributes available') - - trace = OrderedDict() - attribute_idx = {att[0]: idx for idx, att in enumerate(attributes)} - - required_attributes = ['repeat', 'fold', 'iteration', 'evaluation', 'selected'] - for required_attribute in required_attributes: - if required_attribute not in attribute_idx: - raise ValueError('arff misses required attribute: %s' % required_attribute) - parameter_attributes = [] - for attribute in attribute_idx: - if attribute not in required_attributes and attribute != 'setup_string': - parameter_attributes.append(attribute) - - for itt in content: - repeat = int(itt[attribute_idx['repeat']]) - fold = int(itt[attribute_idx['fold']]) - iteration = int(itt[attribute_idx['iteration']]) - evaluation = float(itt[attribute_idx['evaluation']]) - selected_value = itt[attribute_idx['selected']] - if 'setup_string' in attribute_idx: - raise ValueError( - 'setup_string not allowed when constructing a trace object' - ' run results.' - ) - setup_string = None - if selected_value == 'true': - selected = True - elif selected_value == 'false': - selected = False - else: - raise ValueError('expected {"true", "false"} value for selected field, received: %s' % selected_value) - parameters = OrderedDict() - for attribute in parameter_attributes: - parameters[attribute] = itt[attribute_idx[attribute]] - - current = OpenMLTraceIteration( - repeat, - fold, - iteration, - setup_string, - evaluation, - selected, - paramaters=parameters - ) - trace[(repeat, fold, iteration)] = current - - return OpenMLRunTrace(None, trace) - def get_metric_fn(self, sklearn_fn, kwargs={}): """Calculates metric scores based on predicted values. Assumes the run has been executed locally (and contains run_data). Furthermore, diff --git a/openml/runs/trace.py b/openml/runs/trace.py index ab2bb6630c..6334754289 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -48,6 +48,85 @@ def get_selected_iteration(self, fold, repeat): return i raise ValueError('Could not find the selected iteration for rep/fold %d/%d' % (repeat, fold)) + @classmethod + def generate(cls, attributes, content): + """Generates an OpenMLRunTrace. + + Generates the trace object from the attributes and content extracted + while running the underlying flow. + + Returns + ------- + OpenMLRunTrace + """ + + if content is None: + if attributes is None: + return None + else: + raise ValueError('Trace content not available.') + if len(content) == 0: + raise ValueError('Trace content is empty.') + if attributes is not None: + if len(attributes) != len(content[0]): + print(attributes) + print(content[0]) + raise ValueError( + 'Trace_attributes and trace_content not compatible' + ) + else: + raise ValueError('No trace attributes available') + + trace = OrderedDict() + attribute_idx = {att[0]: idx for idx, att in enumerate(attributes)} + + required_attributes = ['repeat', 'fold', 'iteration', 'evaluation', + 'selected'] + for required_attribute in required_attributes: + if required_attribute not in attribute_idx: + raise ValueError( + 'arff misses required attribute: %s' % required_attribute) + parameter_attributes = [] + for attribute in attribute_idx: + if attribute not in required_attributes and attribute != 'setup_string': + parameter_attributes.append(attribute) + + for itt in content: + repeat = int(itt[attribute_idx['repeat']]) + fold = int(itt[attribute_idx['fold']]) + iteration = int(itt[attribute_idx['iteration']]) + evaluation = float(itt[attribute_idx['evaluation']]) + selected_value = itt[attribute_idx['selected']] + if 'setup_string' in attribute_idx: + raise ValueError( + 'setup_string not allowed when constructing a trace object' + ' run results.' + ) + setup_string = None + if selected_value == 'true': + selected = True + elif selected_value == 'false': + selected = False + else: + raise ValueError( + 'expected {"true", "false"} value for selected field, received: %s' % selected_value) + parameters = OrderedDict() + for attribute in parameter_attributes: + parameters[attribute] = itt[attribute_idx[attribute]] + + current = OpenMLTraceIteration( + repeat, + fold, + iteration, + setup_string, + evaluation, + selected, + paramaters=parameters + ) + trace[(repeat, fold, iteration)] = current + + return cls(None, trace) + @classmethod def from_filesystem(cls, file_path): """ diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index 7ba80ec754..f24318ee5c 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -84,7 +84,7 @@ def _check_serialized_optimized_run(self, run_id): e.additional = str(e.additional) + '; run_id: ' + str(run_id) raise e - run_prime = openml.runs.run_model_on_task(task, model_prime, + run_prime = openml.runs.run_model_on_task(model_prime, task, avoid_duplicate_runs=False, seed=1) predictions_prime = run_prime._generate_arff_dict() @@ -269,7 +269,7 @@ def test_run_regression_on_classif_task(self): clf = LinearRegression() task = openml.tasks.get_task(task_id) self.assertRaises(AttributeError, openml.runs.run_model_on_task, - task=task, model=clf, avoid_duplicate_runs=False) + model=clf, task=task, avoid_duplicate_runs=False) def test_check_erronous_sklearn_flow_fails(self): task_id = 115 @@ -866,12 +866,16 @@ def test__run_task_get_arffcontent(self): num_repeats = 1 clf = SGDClassifier(loss='log', random_state=1) - res = openml.runs.functions._run_task_get_arffcontent(clf, task, add_local_measures=True) - arff_datacontent, arff_tracecontent, _, fold_evaluations, sample_evaluations = res + res = openml.runs.functions._run_task_get_arffcontent( + clf, + task, + add_local_measures=True, + ) + arff_datacontent, trace, fold_evaluations, sample_evaluations = res # predictions self.assertIsInstance(arff_datacontent, list) # trace. SGD does not produce any - self.assertIsInstance(arff_tracecontent, type(None)) + self.assertIsInstance(trace, type(None)) self._check_fold_evaluations(fold_evaluations, num_repeats, num_folds) @@ -1097,7 +1101,7 @@ def test_run_on_dataset_with_missing_labels(self): model = Pipeline(steps=[('Imputer', Imputer(strategy='median')), ('Estimator', DecisionTreeClassifier())]) - data_content, _, _, _, _ = _run_task_get_arffcontent(model, task, add_local_measures=True) + data_content, _, _, _ = _run_task_get_arffcontent(model, task, add_local_measures=True) # 2 folds, 5 repeats; keep in mind that this task comes from the test # server, the task on the live server is different self.assertEqual(len(data_content), 4490) @@ -1118,8 +1122,16 @@ def test_predict_proba_hardclassifier(self): ('imputer', sklearn.preprocessing.Imputer()), ('estimator', HardNaiveBayes()) ]) - arff_content1, arff_header1, _, _, _ = _run_task_get_arffcontent(clf1, task, add_local_measures=True) - arff_content2, arff_header2, _, _, _ = _run_task_get_arffcontent(clf2, task, add_local_measures=True) + arff_content1, _, _, _ = _run_task_get_arffcontent( + clf1, + task, + add_local_measures=True, + ) + arff_content2, _, _, _ = _run_task_get_arffcontent( + clf2, + task, + add_local_measures=True, + ) # verifies last two arff indices (predict and correct) # TODO: programmatically check wether these are indeed features (predict, correct) From 4c8bf88d47d0d072d7db3f7adccb4b41f4f242fe Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Thu, 20 Sep 2018 18:05:27 +0200 Subject: [PATCH 22/29] MAINT please style checker --- openml/runs/run.py | 1 - tests/test_runs/test_run_functions.py | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/openml/runs/run.py b/openml/runs/run.py index 148ddc160d..c323846f62 100644 --- a/openml/runs/run.py +++ b/openml/runs/run.py @@ -12,7 +12,6 @@ import openml import openml._api_calls -from .trace import OpenMLRunTrace from ..tasks import get_task from ..exceptions import PyOpenMLError diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index f24318ee5c..8943e5527a 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -871,7 +871,7 @@ def test__run_task_get_arffcontent(self): task, add_local_measures=True, ) - arff_datacontent, trace, fold_evaluations, sample_evaluations = res + arff_datacontent, trace, fold_evaluations, _ = res # predictions self.assertIsInstance(arff_datacontent, list) # trace. SGD does not produce any From 4903e86fdb8c0b74c6893b07b05fcf54be9ab587 Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Fri, 21 Sep 2018 12:30:40 +0200 Subject: [PATCH 23/29] improve code style --- openml/runs/functions.py | 5 +- openml/runs/run.py | 10 +++- openml/runs/trace.py | 84 ++++++++++++++++++++------- tests/test_runs/test_run.py | 26 +++++++-- tests/test_runs/test_run_functions.py | 27 ++++++--- 5 files changed, 113 insertions(+), 39 deletions(-) diff --git a/openml/runs/functions.py b/openml/runs/functions.py index 13c4291982..7f7c9eae9f 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -483,7 +483,10 @@ def _prediction_to_probabilities(y, model_classes): if isinstance(model_fold, sklearn.model_selection._search.BaseSearchCV): # arff_tracecontent is already set arff_trace_attributes = _extract_arfftrace_attributes(model_fold) - trace = OpenMLRunTrace.generate(arff_trace_attributes, arff_tracecontent) + trace = OpenMLRunTrace.generate( + arff_trace_attributes, + arff_tracecontent, + ) else: trace = None diff --git a/openml/runs/run.py b/openml/runs/run.py index c323846f62..598635e632 100644 --- a/openml/runs/run.py +++ b/openml/runs/run.py @@ -299,9 +299,15 @@ def publish(self): self : OpenMLRun """ if self.model is None: - raise PyOpenMLError("OpenMLRun obj does not contain a model. (This should never happen.) ") + raise PyOpenMLError( + "OpenMLRun obj does not contain a model. " + "(This should never happen.) " + ) if self.flow_id is None: - raise PyOpenMLError("OpenMLRun obj does not contain a flow id. (Should have been added while executing the task.) ") + raise PyOpenMLError( + "OpenMLRun obj does not contain a flow id. " + "(Should have been added while executing the task.) " + ) description_xml = self._create_description_xml() file_elements = {'description': ("description.xml", description_xml)} diff --git a/openml/runs/trace.py b/openml/runs/trace.py index 6334754289..018c5f06c5 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -69,10 +69,9 @@ def generate(cls, attributes, content): raise ValueError('Trace content is empty.') if attributes is not None: if len(attributes) != len(content[0]): - print(attributes) - print(content[0]) raise ValueError( - 'Trace_attributes and trace_content not compatible' + 'Trace_attributes and trace_content not compatible:' + ' %s vs %s' % (attributes, content[0]) ) else: raise ValueError('No trace attributes available') @@ -88,7 +87,10 @@ def generate(cls, attributes, content): 'arff misses required attribute: %s' % required_attribute) parameter_attributes = [] for attribute in attribute_idx: - if attribute not in required_attributes and attribute != 'setup_string': + if ( + attribute not in required_attributes + and attribute != 'setup_string' + ): parameter_attributes.append(attribute) for itt in content: @@ -109,7 +111,9 @@ def generate(cls, attributes, content): selected = False else: raise ValueError( - 'expected {"true", "false"} value for selected field, received: %s' % selected_value) + 'expected {"true", "false"} value for selected field, ' + 'received: %s' % selected_value + ) parameters = OrderedDict() for attribute in parameter_attributes: parameters[attribute] = itt[attribute_idx[attribute]] @@ -148,9 +152,12 @@ def from_filesystem(cls, file_path): trace_arff = arff.load(fp) for trace_idx in range(len(trace_arff['data'])): - # iterate over first three entrees of a trace row (fold, repeat, trace_iteration) these should be int + # iterate over first three entrees of a trace row + # (fold, repeat, trace_iteration) these should be int for line_idx in range(3): - trace_arff['data'][trace_idx][line_idx] = int(trace_arff['data'][trace_idx][line_idx]) + trace_arff['data'][trace_idx][line_idx] = int( + trace_arff['data'][trace_idx][line_idx] + ) return cls.trace_from_arff(trace_arff) @@ -170,7 +177,7 @@ def to_filesystem(self, file_path): f.write(trace_arff) def trace_to_arff(self): - """Generates the arff dictionary for uploading predictions to the server. + """Generate the arff dictionary for uploading predictions to the server. Uses the trace object to generate an arff dictionary representation. @@ -191,7 +198,9 @@ def trace_to_arff(self): ('evaluation', 'NUMERIC'), ('selected', ['true', 'false']), ] - for parameter in next(iter(self.trace_iterations.values())).get_parameters(): + for parameter in next( + iter(self.trace_iterations.values()) + ).get_parameters(): trace_attributes.append(('parameter_' + parameter, 'STRING')) arff_dict = OrderedDict() @@ -222,7 +231,8 @@ def trace_to_arff(self): def trace_from_arff(cls, arff_obj): """Generate trace from arff trace. - Creates a trace file from arff object (for example, generated by a local run). + Creates a trace file from arff object (for example, generated by a + local run). Parameters ---------- @@ -235,13 +245,25 @@ def trace_from_arff(cls, arff_obj): """ trace = OrderedDict() # flag if setup string is in attributes - attribute_idx = {att[0]: idx for idx, att in enumerate(arff_obj['attributes'])} - required_attributes = ['repeat', 'fold', 'iteration', 'evaluation', 'selected'] + attribute_idx = { + att[0]: idx for idx, att in enumerate(arff_obj['attributes']) + } + required_attributes = [ + 'repeat', + 'fold', + 'iteration', + 'evaluation', + 'selected', + ] for required_attribute in required_attributes: if required_attribute not in attribute_idx: - raise ValueError('arff misses required attribute: %s' % required_attribute) + raise ValueError( + 'arff misses required attribute: %s' % required_attribute + ) if 'setup_string' in attribute_idx: - raise ValueError('setup_string not supported for arff serialization') + raise ValueError( + 'setup_string not supported for arff serialization' + ) for itt in arff_obj['data']: repeat = int(itt[attribute_idx['repeat']]) @@ -254,7 +276,10 @@ def trace_from_arff(cls, arff_obj): elif selected_value == 'false': selected = False else: - raise ValueError('expected {"true", "false"} value for selected field, received: %s' % selected_value) + raise ValueError( + 'expected {"true", "false"} value for selected field, ' + 'received: %s' % selected_value + ) parameters = OrderedDict() for attribute_name, idx in attribute_idx.items(): @@ -286,14 +311,17 @@ def trace_from_xml(cls, xml): Parameters ---------- xml : string | file-like object - An xml description that can be either a `string` or a file-like object. + An xml description that can be either a `string` or a file-like + object. Returns ------- run : OpenMLRunTrace Object containing run id and a dict containing the trace iterations. """ - result_dict = xmltodict.parse(xml, force_list=('oml:trace_iteration',))['oml:trace'] + result_dict = xmltodict.parse( + xml, force_list=('oml:trace_iteration',) + )['oml:trace'] run_id = result_dict['oml:run_id'] trace = OrderedDict() @@ -315,8 +343,10 @@ def trace_from_xml(cls, xml): elif selected_value == 'false': selected = False else: - raise ValueError('expected {"true", "false"} value for ' - 'selected field, received: %s' % selected_value) + raise ValueError( + 'expected {"true", "false"} value for ' + 'selected field, received: %s' % selected_value + ) current = OpenMLTraceIteration( repeat, @@ -331,7 +361,10 @@ def trace_from_xml(cls, xml): return cls(run_id, trace) 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): @@ -374,6 +407,8 @@ def __init__( paramaters=None, ): + if not isinstance(selected, bool): + raise TypeError(type(selected)) if setup_string and paramaters: raise ValueError( 'Can only be instantiated with either ' @@ -416,5 +451,10 @@ 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) + return '[(%d,%d,%d): %f (%r)]' % ( + self.repeat, + self.fold, + self.iteration, + self.evaluation, + self.selected, + ) diff --git a/tests/test_runs/test_run.py b/tests/test_runs/test_run.py index c0427e3a46..d591e191d9 100644 --- a/tests/test_runs/test_run.py +++ b/tests/test_runs/test_run.py @@ -114,8 +114,14 @@ def _check_array(array, type_): 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) + 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): @@ -123,7 +129,8 @@ def _check_array(array, type_): 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 + # JvR: Python 2.7 requires an almost equal check, rather than an + # equals check 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) @@ -175,13 +182,20 @@ def test_to_from_filesystem_no_model(self): ('classifier', DummyClassifier()), ]) task = openml.tasks.get_task(119) - run = openml.runs.run_model_on_task(task, model, add_local_measures=False) + run = openml.runs.run_model_on_task( + task, + model, + add_local_measures=False, + ) - cache_path = os.path.join(self.workdir, 'runs', str(random.getrandbits(128))) + cache_path = os.path.join( + self.workdir, + 'runs', + str(random.getrandbits(128)), + ) run.to_filesystem(cache_path, store_model=False) # obtain run from filesystem openml.runs.OpenMLRun.from_filesystem(cache_path, expect_model=False) # assert default behaviour is throwing an error with self.assertRaises(ValueError, msg='Could not find model.pkl'): openml.runs.OpenMLRun.from_filesystem(cache_path) - diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index 8943e5527a..be42a2606a 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -178,11 +178,12 @@ def _remove_random_state(flow): downloaded = openml.runs.get_run(run_.run_id) assert('openml-python' in downloaded.tags) - # TODO make sure that these attributes are instantiated when downloading a run? - # Or make sure that the trace object is created when running a flow on a task (and not - # only the arff object is created, so that the two objects can actually be compared). - #downloaded_run_trace = downloaded._generate_trace_arff_dict() - #self.assertEqual(run_trace, downloaded_run_trace) + # TODO make sure that these attributes are instantiated when + # downloading a run? Or make sure that the trace object is created when + # running a flow on a task (and not only the arff object is created, + # so that the two objects can actually be compared): + # downloaded_run_trace = downloaded._generate_trace_arff_dict() + # self.assertEqual(run_trace, downloaded_run_trace) return run @@ -730,7 +731,8 @@ def test__extract_arfftrace(self): for att_idx in range(len(trace_attribute_list)): att_type = trace_attribute_list[att_idx][1] att_name = trace_attribute_list[att_idx][0] - # They no longer start with parameter_ if they come from extract_arff_trace! + # They no longer start with parameter_ if they come from + # extract_arff_trace! if att_name.startswith("parameter_"): # add this to the found parameters param_name = att_name[len("parameter_"):] @@ -746,7 +748,12 @@ def test__extract_arfftrace(self): val = trace_list[line_idx][att_idx] if isinstance(att_type, list): self.assertIn(val, att_type) - elif att_name in ['hidden_layer_sizes', 'activation', 'learning_rate_init', 'max_iter']: + elif att_name in [ + 'hidden_layer_sizes', + 'activation', + 'learning_rate_init', + 'max_iter', + ]: self.assertIsInstance( trace_list[line_idx][att_idx], str, @@ -1101,7 +1108,11 @@ def test_run_on_dataset_with_missing_labels(self): model = Pipeline(steps=[('Imputer', Imputer(strategy='median')), ('Estimator', DecisionTreeClassifier())]) - data_content, _, _, _ = _run_task_get_arffcontent(model, task, add_local_measures=True) + data_content, _, _, _ = _run_task_get_arffcontent( + model, + task, + add_local_measures=True, + ) # 2 folds, 5 repeats; keep in mind that this task comes from the test # server, the task on the live server is different self.assertEqual(len(data_content), 4490) From 879dc3e70260cd4ba0001f00d4337685a449cc6b Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Fri, 21 Sep 2018 12:41:39 +0200 Subject: [PATCH 24/29] work on arlind's suggestions --- openml/runs/trace.py | 46 +++++++++++++++++++++++++------------------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/openml/runs/trace.py b/openml/runs/trace.py index 018c5f06c5..9920f85aea 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -44,9 +44,16 @@ def get_selected_iteration(self, fold, repeat): 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: + 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) + ) @classmethod def generate(cls, attributes, content): @@ -85,13 +92,11 @@ def generate(cls, attributes, content): if required_attribute not in attribute_idx: raise ValueError( 'arff misses required attribute: %s' % required_attribute) - parameter_attributes = [] - for attribute in attribute_idx: - if ( - attribute not in required_attributes - and attribute != 'setup_string' - ): - parameter_attributes.append(attribute) + parameter_attributes = [ + attribute for attribute in attribute_idx + if attribute not in required_attributes + and attribute != 'setup_string' + ] for itt in content: repeat = int(itt[attribute_idx['repeat']]) @@ -114,9 +119,10 @@ def generate(cls, attributes, content): 'expected {"true", "false"} value for selected field, ' 'received: %s' % selected_value ) - parameters = OrderedDict() - for attribute in parameter_attributes: - parameters[attribute] = itt[attribute_idx[attribute]] + parameters = OrderedDict([ + (attribute, attribute_idx[attribute]) + for attribute in parameter_attributes + ]) current = OpenMLTraceIteration( repeat, @@ -198,10 +204,10 @@ def trace_to_arff(self): ('evaluation', 'NUMERIC'), ('selected', ['true', 'false']), ] - for parameter in next( - iter(self.trace_iterations.values()) - ).get_parameters(): - trace_attributes.append(('parameter_' + parameter, 'STRING')) + trace_attributes.extend([ + ('parameter_' + parameter, 'STRING') + for parameter in self.trace_iterations.values() + ]) arff_dict = OrderedDict() data = [] @@ -283,12 +289,12 @@ def trace_from_arff(cls, arff_obj): parameters = OrderedDict() for attribute_name, idx in attribute_idx.items(): - if attribute_name in required_attributes: - continue - if attribute_name.startswith(PREFIX): + if ( + attribute_name not in required_attributes + and attribute_name.startswith(PREFIX) + ): parameters[attribute_name] = itt[idx] - current = OpenMLTraceIteration( repeat=repeat, fold=fold, From dcfbc48adc1ee6a10726ccdde773687c352fa95c Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Fri, 21 Sep 2018 19:20:17 +0200 Subject: [PATCH 25/29] FIX type error and add missing file --- openml/runs/trace.py | 18 ++++++------- tests/test_runs/test_trace.py | 51 +++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 9 deletions(-) create mode 100644 tests/test_runs/test_trace.py diff --git a/openml/runs/trace.py b/openml/runs/trace.py index 9920f85aea..f7b34c1cef 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -30,13 +30,13 @@ 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 @@ -205,8 +205,8 @@ def trace_to_arff(self): ('selected', ['true', 'false']), ] trace_attributes.extend([ - ('parameter_' + parameter, 'STRING') - for parameter in self.trace_iterations.values() + ('parameter_' + parameter, 'STRING') for parameter in + next(iter(self.trace_iterations.values())).get_parameters() ]) arff_dict = OrderedDict() @@ -383,7 +383,7 @@ class OpenMLTraceIteration(object): fold : int fold number (in case of no folds: 0) - + iteration : int iteration number of optimization procedure @@ -391,11 +391,11 @@ class OpenMLTraceIteration(object): json string representing the parameters evaluation : double - The evaluation that was awarded to this trace iteration. + The evaluation that was awarded to this trace iteration. Measure is defined by the task selected : bool - Whether this was the best of all iterations, and hence + Whether this was the best of all iterations, and hence selected for making predictions. Per fold/repeat there should be only one iteration selected @@ -455,7 +455,7 @@ def get_parameters(self): def __str__(self): """ - tmp string representation, will be changed in the near future + tmp string representation, will be changed in the near future """ return '[(%d,%d,%d): %f (%r)]' % ( self.repeat, diff --git a/tests/test_runs/test_trace.py b/tests/test_runs/test_trace.py new file mode 100644 index 0000000000..c48bf12559 --- /dev/null +++ b/tests/test_runs/test_trace.py @@ -0,0 +1,51 @@ +import unittest + +from openml.runs import OpenMLRunTrace, OpenMLTraceIteration + + +class TestTrace(unittest.TestCase): + def test_get_selected_iteration(self): + trace_iterations = {} + for i in range(5): + for j in range(5): + for k in range(5): + t = OpenMLTraceIteration( + repeat=i, + fold=j, + iteration=5, + setup_string='parameter_%d%d%d' % (i, j, k), + evaluation=1.0 * i + 0.1 * j + 0.01 * k, + selected=(i == j and i == k and i == 2), + paramaters=None, + ) + trace_iterations[(i, j, k)] = t + + trace = OpenMLRunTrace(-1, trace_iterations=trace_iterations) + # This next one should simply not fail + self.assertEqual(trace.get_selected_iteration(2, 2), 2) + with self.assertRaisesRegex( + ValueError, + 'Could not find the selected iteration for rep/fold 3/3', + ): + + trace.get_selected_iteration(3, 3) + + def test_initialization(self): + """Check all different ways to fail the initialization """ + rval = OpenMLRunTrace.generate(None, None) + self.assertIsNone(rval) + with self.assertRaisesRegex( + ValueError, + 'Trace content not available.', + ): + OpenMLRunTrace.generate(attributes='foo', content=None) + with self.assertRaisesRegex( + ValueError, + 'Trace content is empty.' + ): + OpenMLRunTrace.generate(attributes='foo', content=[]) + with self.assertRaisesRegex( + ValueError, + 'Trace_attributes and trace_content not compatible:' + ): + OpenMLRunTrace.generate(attributes=['abc'], content=[[1, 2]]) \ No newline at end of file From 6f03812bd438477ba16b9c54831ca9cb325fab5b Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Fri, 21 Sep 2018 20:46:56 +0200 Subject: [PATCH 26/29] MAINT improve style --- openml/runs/__init__.py | 25 ++++++++++++++++++++----- openml/runs/trace.py | 3 ++- tests/test_runs/test_run.py | 6 +++++- tests/test_runs/test_trace.py | 2 +- 4 files changed, 28 insertions(+), 8 deletions(-) diff --git a/openml/runs/__init__.py b/openml/runs/__init__.py index 628ccf93b9..236c83fed4 100644 --- a/openml/runs/__init__.py +++ b/openml/runs/__init__.py @@ -1,8 +1,23 @@ from .run import OpenMLRun from .trace import OpenMLRunTrace, OpenMLTraceIteration -from .functions import (run_model_on_task, run_flow_on_task, get_run, list_runs, - get_runs, get_run_trace, initialize_model_from_run, - initialize_model_from_trace) +from .functions import ( + run_model_on_task, + run_flow_on_task, + get_run, + list_runs, + get_runs, + get_run_trace, + initialize_model_from_run, + initialize_model_from_trace, +) -__all__ = ['OpenMLRun', 'run_model_on_task', 'run_flow_on_task', 'get_run', - 'list_runs', 'get_runs'] +__all__ = [ + 'OpenMLRun', + 'OpenMLRunTrace', + 'OpenMLTraceIteration', + 'run_model_on_task', + 'run_flow_on_task', + 'get_run', + 'list_runs', + 'get_runs', +] diff --git a/openml/runs/trace.py b/openml/runs/trace.py index f7b34c1cef..d3495f3717 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -323,7 +323,8 @@ def trace_from_xml(cls, xml): Returns ------- run : OpenMLRunTrace - Object containing run id and a dict containing the trace iterations. + Object containing the run id and a dict containing the trace + iterations. """ result_dict = xmltodict.parse( xml, force_list=('oml:trace_iteration',) diff --git a/tests/test_runs/test_run.py b/tests/test_runs/test_run.py index d591e191d9..47ccab5660 100644 --- a/tests/test_runs/test_run.py +++ b/tests/test_runs/test_run.py @@ -167,7 +167,11 @@ def test_to_from_filesystem_search(self): ) task = openml.tasks.get_task(119) - run = openml.runs.run_model_on_task(task, model, add_local_measures=False) + run = openml.runs.run_model_on_task( + model, + task, + add_local_measures=False, + ) cache_path = os.path.join(self.workdir, 'runs', str(random.getrandbits(128))) run.to_filesystem(cache_path) diff --git a/tests/test_runs/test_trace.py b/tests/test_runs/test_trace.py index c48bf12559..d1facaab16 100644 --- a/tests/test_runs/test_trace.py +++ b/tests/test_runs/test_trace.py @@ -48,4 +48,4 @@ def test_initialization(self): ValueError, 'Trace_attributes and trace_content not compatible:' ): - OpenMLRunTrace.generate(attributes=['abc'], content=[[1, 2]]) \ No newline at end of file + OpenMLRunTrace.generate(attributes=['abc'], content=[[1, 2]]) From 41e78d507cb8ba96a2b92ce1a1ce34361905e8a2 Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Thu, 27 Sep 2018 10:03:37 +0200 Subject: [PATCH 27/29] CI fix unittests --- openml/runs/trace.py | 2 +- tests/test_runs/test_run_functions.py | 4 ++-- tests/test_runs/test_trace.py | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/openml/runs/trace.py b/openml/runs/trace.py index d3495f3717..7a844bdd0d 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -120,7 +120,7 @@ def generate(cls, attributes, content): 'received: %s' % selected_value ) parameters = OrderedDict([ - (attribute, attribute_idx[attribute]) + (attribute, itt[attribute_idx[attribute]]) for attribute in parameter_attributes ]) diff --git a/tests/test_runs/test_run_functions.py b/tests/test_runs/test_run_functions.py index be42a2606a..f8f4ee83c4 100644 --- a/tests/test_runs/test_run_functions.py +++ b/tests/test_runs/test_run_functions.py @@ -83,7 +83,7 @@ def _check_serialized_optimized_run(self, run_id): except openml.exceptions.OpenMLServerException as e: e.additional = str(e.additional) + '; run_id: ' + str(run_id) raise e - + run_prime = openml.runs.run_model_on_task(model_prime, task, avoid_duplicate_runs=False, seed=1) @@ -120,7 +120,7 @@ def _remove_random_state(flow): flow.publish() task = openml.tasks.get_task(task_id) - run = openml.runs.run_flow_on_task(task, flow, seed=1, + run = openml.runs.run_flow_on_task(flow, task, seed=1, avoid_duplicate_runs=openml.config.avoid_duplicate_runs) run_ = run.publish() self.assertEqual(run_, run) diff --git a/tests/test_runs/test_trace.py b/tests/test_runs/test_trace.py index d1facaab16..765d42d0cf 100644 --- a/tests/test_runs/test_trace.py +++ b/tests/test_runs/test_trace.py @@ -23,7 +23,7 @@ def test_get_selected_iteration(self): trace = OpenMLRunTrace(-1, trace_iterations=trace_iterations) # This next one should simply not fail self.assertEqual(trace.get_selected_iteration(2, 2), 2) - with self.assertRaisesRegex( + with self.assertRaisesRegexp( ValueError, 'Could not find the selected iteration for rep/fold 3/3', ): @@ -34,17 +34,17 @@ def test_initialization(self): """Check all different ways to fail the initialization """ rval = OpenMLRunTrace.generate(None, None) self.assertIsNone(rval) - with self.assertRaisesRegex( + with self.assertRaisesRegexp( ValueError, 'Trace content not available.', ): OpenMLRunTrace.generate(attributes='foo', content=None) - with self.assertRaisesRegex( + with self.assertRaisesRegexp( ValueError, 'Trace content is empty.' ): OpenMLRunTrace.generate(attributes='foo', content=[]) - with self.assertRaisesRegex( + with self.assertRaisesRegexp( ValueError, 'Trace_attributes and trace_content not compatible:' ): From 4444341548fc242de696fa09e4cdc707b4273987 Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Thu, 27 Sep 2018 11:12:15 +0200 Subject: [PATCH 28/29] MAINT work on Jan's comments --- openml/runs/functions.py | 13 +-- openml/runs/run.py | 4 +- openml/runs/trace.py | 195 +++++++++++++++------------------- tests/test_runs/test_run.py | 18 +++- tests/test_runs/test_trace.py | 41 ++++++- 5 files changed, 151 insertions(+), 120 deletions(-) diff --git a/openml/runs/functions.py b/openml/runs/functions.py index 7f7c9eae9f..3d42196b0b 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -235,7 +235,7 @@ def initialize_model_from_trace(run_id, repeat, fold, iteration=None): Parameters ---------- run_id : int - The Openml run_id. Should contain a trace file, + The Openml run_id. Should contain a trace file, otherwise a OpenMLServerException is raised repeat: int @@ -246,7 +246,7 @@ def initialize_model_from_trace(run_id, repeat, fold, iteration=None): iteration: int The iteration nr (column in trace file). If None, the - best (selected) iteration will be searched (slow), + best (selected) iteration will be searched (slow), according to the selection criteria implemented in OpenMLRunTrace.get_selected_iteration @@ -687,8 +687,9 @@ def _extract_arfftrace_attributes(model): raise TypeError('Unsupported param type in param grid: %s' %key) # we renamed the attribute param to parameter, as this is a required - # OpenML convention - attribute = (key[6:], type) + # OpenML convention - this also guards against name collisions + # with the required trace attributes + attribute = (openml.runs.trace.PREFIX + key[6:], type) trace_attributes.append(attribute) return trace_attributes @@ -756,7 +757,7 @@ def _create_run_from_xml(xml, from_server=True): run : OpenMLRun New run object representing run_xml. """ - + def obtain_field(xml_obj, fieldname, from_server, cast=None): # this function can be used to check whether a field is present in an object. # if it is not present, either returns None or throws an error (this is @@ -777,7 +778,7 @@ def obtain_field(xml_obj, fieldname, from_server, cast=None): task_id = int(run['oml:task_id']) task_type = obtain_field(run, 'oml:task_type', from_server) - # even with the server requirement this field may be empty. + # even with the server requirement this field may be empty. if 'oml:task_evaluation_measure' in run: task_evaluation_measure = run['oml:task_evaluation_measure'] else: diff --git a/openml/runs/run.py b/openml/runs/run.py index 598635e632..75b8586d87 100644 --- a/openml/runs/run.py +++ b/openml/runs/run.py @@ -118,7 +118,7 @@ def from_filesystem(cls, folder, expect_model=True): run.model = pickle.load(fp) if os.path.isfile(trace_path): - run.trace = openml.runs.OpenMLRunTrace.from_filesystem(trace_path) + run.trace = openml.runs.OpenMLRunTrace._from_filesystem(trace_path) return run @@ -164,7 +164,7 @@ def to_filesystem(self, output_directory, store_model=True): pickle.dump(self.model, f) if self.trace is not None: - self.trace.to_filesystem(output_directory) + self.trace._to_filesystem(output_directory) def _generate_arff_dict(self): """Generates the arff dictionary for uploading predictions to the server. diff --git a/openml/runs/trace.py b/openml/runs/trace.py index 7a844bdd0d..6b98f28101 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -5,6 +5,13 @@ from collections import OrderedDict PREFIX = 'parameter_' +REQUIRED_ATTRIBUTES = [ + 'repeat', + 'fold', + 'iteration', + 'evaluation', + 'selected', +] class OpenMLRunTrace(object): @@ -62,83 +69,42 @@ def generate(cls, attributes, content): Generates the trace object from the attributes and content extracted while running the underlying flow. + Parameters + ---------- + + attributes : list + List of tuples describing the arff attributes. + + content : list + List of lists containing information about the individual tuning + runs. + Returns ------- OpenMLRunTrace """ if content is None: - if attributes is None: - return None - else: - raise ValueError('Trace content not available.') - if len(content) == 0: + raise ValueError('Trace content not available.') + elif attributes is None: + raise ValueError('Trace attributes not available.') + elif len(content) == 0: raise ValueError('Trace content is empty.') - if attributes is not None: - if len(attributes) != len(content[0]): - raise ValueError( - 'Trace_attributes and trace_content not compatible:' - ' %s vs %s' % (attributes, content[0]) - ) - else: - raise ValueError('No trace attributes available') - - trace = OrderedDict() - attribute_idx = {att[0]: idx for idx, att in enumerate(attributes)} - - required_attributes = ['repeat', 'fold', 'iteration', 'evaluation', - 'selected'] - for required_attribute in required_attributes: - if required_attribute not in attribute_idx: - raise ValueError( - 'arff misses required attribute: %s' % required_attribute) - parameter_attributes = [ - attribute for attribute in attribute_idx - if attribute not in required_attributes - and attribute != 'setup_string' - ] - - for itt in content: - repeat = int(itt[attribute_idx['repeat']]) - fold = int(itt[attribute_idx['fold']]) - iteration = int(itt[attribute_idx['iteration']]) - evaluation = float(itt[attribute_idx['evaluation']]) - selected_value = itt[attribute_idx['selected']] - if 'setup_string' in attribute_idx: - raise ValueError( - 'setup_string not allowed when constructing a trace object' - ' run results.' - ) - setup_string = None - if selected_value == 'true': - selected = True - elif selected_value == 'false': - selected = False - else: - raise ValueError( - 'expected {"true", "false"} value for selected field, ' - 'received: %s' % selected_value - ) - parameters = OrderedDict([ - (attribute, itt[attribute_idx[attribute]]) - for attribute in parameter_attributes - ]) - - current = OpenMLTraceIteration( - repeat, - fold, - iteration, - setup_string, - evaluation, - selected, - paramaters=parameters + elif len(attributes) != len(content[0]): + raise ValueError( + 'Trace_attributes and trace_content not compatible:' + ' %s vs %s' % (attributes, content[0]) ) - trace[(repeat, fold, iteration)] = current - return cls(None, trace) + return cls._trace_from_arff_struct( + attributes=attributes, + content=content, + error_message='setup_string not allowed when constructing a ' + 'trace object from run results.' + ) @classmethod - def from_filesystem(cls, file_path): + def _from_filesystem(cls, file_path): """ Logic to deserialize the trace from the filesystem. @@ -167,7 +133,7 @@ def from_filesystem(cls, file_path): return cls.trace_from_arff(trace_arff) - def to_filesystem(self, file_path): + def _to_filesystem(self, file_path): """Serialize the trace object to the filesystem. Serialize the trace object as an arff. @@ -205,31 +171,32 @@ def trace_to_arff(self): ('selected', ['true', 'false']), ] trace_attributes.extend([ - ('parameter_' + parameter, 'STRING') for parameter in + (PREFIX + parameter, 'STRING') for parameter in next(iter(self.trace_iterations.values())).get_parameters() ]) arff_dict = OrderedDict() data = [] for trace_iteration in self.trace_iterations.values(): - tit_list = [] + tmp_list = [] for attr, _ in trace_attributes: - if attr.startswith('parameter_'): - attr = attr[len('parameter_'):] + if attr.startswith(PREFIX): + attr = attr[len(PREFIX):] value = trace_iteration.get_parameters()[attr] else: value = getattr(trace_iteration, attr) if attr == 'selected': if value: - tit_list.append('true') + tmp_list.append('true') else: - tit_list.append('false') + tmp_list.append('false') else: - tit_list.append(value) - data.append(tit_list) + tmp_list.append(value) + data.append(tmp_list) arff_dict['attributes'] = trace_attributes arff_dict['data'] = data + # TODO allow to pass a trace description when running a flow arff_dict['relation'] = "Trace" return arff_dict @@ -249,29 +216,46 @@ def trace_from_arff(cls, arff_obj): ------- OpenMLRunTrace """ + attributes = arff_obj['attributes'] + content = arff_obj['data'] + return cls._trace_from_arff_struct( + attributes=attributes, + content=content, + error_message= + 'setup_string not supported for arff serialization' + + ) + + @classmethod + def _trace_from_arff_struct(cls, attributes, content, error_message): trace = OrderedDict() - # flag if setup string is in attributes - attribute_idx = { - att[0]: idx for idx, att in enumerate(arff_obj['attributes']) - } - required_attributes = [ - 'repeat', - 'fold', - 'iteration', - 'evaluation', - 'selected', - ] - for required_attribute in required_attributes: + attribute_idx = {att[0]: idx for idx, att in enumerate(attributes)} + + for required_attribute in REQUIRED_ATTRIBUTES: if required_attribute not in attribute_idx: raise ValueError( 'arff misses required attribute: %s' % required_attribute ) if 'setup_string' in attribute_idx: - raise ValueError( - 'setup_string not supported for arff serialization' - ) + raise ValueError(error_message) + + # note that the required attributes can not be duplicated because + # they are not parameters + parameter_attributes = [] + for attribute in attribute_idx: + if attribute in REQUIRED_ATTRIBUTES: + continue + elif attribute == 'setup_string': + continue + elif not attribute.startswith(PREFIX): + raise ValueError( + 'Encountered unknown attribute %s that does not start ' + 'with prefix %s' % (attribute, PREFIX) + ) + else: + parameter_attributes.append(attribute) - for itt in arff_obj['data']: + for itt in content: repeat = int(itt[attribute_idx['repeat']]) fold = int(itt[attribute_idx['fold']]) iteration = int(itt[attribute_idx['iteration']]) @@ -287,13 +271,10 @@ def trace_from_arff(cls, arff_obj): 'received: %s' % selected_value ) - parameters = OrderedDict() - for attribute_name, idx in attribute_idx.items(): - if ( - attribute_name not in required_attributes - and attribute_name.startswith(PREFIX) - ): - parameters[attribute_name] = itt[idx] + parameters = OrderedDict([ + (attribute, itt[attribute_idx[attribute]]) + for attribute in parameter_attributes + ]) current = OpenMLTraceIteration( repeat=repeat, @@ -423,7 +404,7 @@ def __init__( ) elif not setup_string and not paramaters: raise ValueError( - 'Either setup_string or parameters needs to be paased as ' + 'Either setup_string or parameters needs to be passed as ' 'argument.' ) if paramaters is not None and not isinstance(paramaters, OrderedDict): @@ -441,17 +422,17 @@ def __init__( self.parameters = paramaters def get_parameters(self): - if self.parameters: - return self.parameters - result = {} # parameters have prefix 'parameter_' - prefix = 'parameter_' - for param in self.setup_string: - key = param[len(prefix):] - value = self.setup_string[param] - result[key] = json.loads(value) + if self.setup_string: + for param in self.setup_string: + key = param[len(PREFIX):] + value = self.setup_string[param] + result[key] = json.loads(value) + else: + for param, value in self.parameters.items(): + result[param[len(PREFIX):]] = value return result def __str__(self): diff --git a/tests/test_runs/test_run.py b/tests/test_runs/test_run.py index 47ccab5660..a5368267dd 100644 --- a/tests/test_runs/test_run.py +++ b/tests/test_runs/test_run.py @@ -144,9 +144,17 @@ def test_to_from_filesystem_vanilla(self): ('classifier', DecisionTreeClassifier(max_depth=1)), ]) task = openml.tasks.get_task(119) - run = openml.runs.run_model_on_task(task, model, add_local_measures=False) + run = openml.runs.run_model_on_task( + model=model, + task=task, + add_local_measures=False, + ) - cache_path = os.path.join(self.workdir, 'runs', str(random.getrandbits(128))) + cache_path = os.path.join( + self.workdir, + 'runs', + str(random.getrandbits(128)), + ) run.to_filesystem(cache_path) run_prime = openml.runs.OpenMLRun.from_filesystem(cache_path) @@ -173,7 +181,11 @@ def test_to_from_filesystem_search(self): add_local_measures=False, ) - cache_path = os.path.join(self.workdir, 'runs', str(random.getrandbits(128))) + cache_path = os.path.join( + self.workdir, + 'runs', + str(random.getrandbits(128)), + ) run.to_filesystem(cache_path) run_prime = openml.runs.OpenMLRun.from_filesystem(cache_path) diff --git a/tests/test_runs/test_trace.py b/tests/test_runs/test_trace.py index 765d42d0cf..3aadcafac6 100644 --- a/tests/test_runs/test_trace.py +++ b/tests/test_runs/test_trace.py @@ -32,13 +32,16 @@ def test_get_selected_iteration(self): def test_initialization(self): """Check all different ways to fail the initialization """ - rval = OpenMLRunTrace.generate(None, None) - self.assertIsNone(rval) with self.assertRaisesRegexp( ValueError, 'Trace content not available.', ): OpenMLRunTrace.generate(attributes='foo', content=None) + with self.assertRaisesRegexp( + ValueError, + 'Trace attributes not available.', + ): + OpenMLRunTrace.generate(attributes=None, content='foo') with self.assertRaisesRegexp( ValueError, 'Trace content is empty.' @@ -49,3 +52,37 @@ def test_initialization(self): 'Trace_attributes and trace_content not compatible:' ): OpenMLRunTrace.generate(attributes=['abc'], content=[[1, 2]]) + + def test_duplicate_name(self): + # Test that the user does not pass a parameter which has the same name + # as one of the required trace attributes + trace_attributes = [ + ('repeat', 'NUMERICAL'), + ('fold', 'NUMERICAL'), + ('iteration', 'NUMERICAL'), + ('evaluation', 'NUMERICAL'), + ('selected', ['true', 'false']), + ('repeat', 'NUMERICAL'), + ] + trace_content = [[0, 0, 0, 0.5, 'true', 1], [0, 0, 0, 0.9, 'false', 2]] + with self.assertRaisesRegexp( + ValueError, + 'Either setup_string or parameters needs to be passed as argument.' + ): + OpenMLRunTrace.generate(trace_attributes, trace_content) + + trace_attributes = [ + ('repeat', 'NUMERICAL'), + ('fold', 'NUMERICAL'), + ('iteration', 'NUMERICAL'), + ('evaluation', 'NUMERICAL'), + ('selected', ['true', 'false']), + ('sunshine', 'NUMERICAL'), + ] + trace_content = [[0, 0, 0, 0.5, 'true', 1], [0, 0, 0, 0.9, 'false', 2]] + with self.assertRaisesRegexp( + ValueError, + 'Encountered unknown attribute sunshine that does not start with ' + 'prefix parameter_' + ): + OpenMLRunTrace.generate(trace_attributes, trace_content) From 79887b8a1b65994e4db46887f1d5be9c2b763c12 Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Thu, 27 Sep 2018 12:27:37 +0200 Subject: [PATCH 29/29] MAINT improve style to please flake8 --- openml/runs/__init__.py | 3 +++ openml/runs/trace.py | 6 ++---- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/openml/runs/__init__.py b/openml/runs/__init__.py index 236c83fed4..da1cab7db3 100644 --- a/openml/runs/__init__.py +++ b/openml/runs/__init__.py @@ -20,4 +20,7 @@ 'get_run', 'list_runs', 'get_runs', + 'get_run_trace', + 'initialize_model_from_run', + 'initialize_model_from_trace' ] diff --git a/openml/runs/trace.py b/openml/runs/trace.py index 6b98f28101..e47108a371 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -100,7 +100,7 @@ def generate(cls, attributes, content): attributes=attributes, content=content, error_message='setup_string not allowed when constructing a ' - 'trace object from run results.' + 'trace object from run results.' ) @classmethod @@ -221,9 +221,7 @@ def trace_from_arff(cls, arff_obj): return cls._trace_from_arff_struct( attributes=attributes, content=content, - error_message= - 'setup_string not supported for arff serialization' - + error_message='setup_string not supported for arff serialization' ) @classmethod