diff --git a/openml/runs/__init__.py b/openml/runs/__init__.py index 628ccf93b9..da1cab7db3 100644 --- a/openml/runs/__init__.py +++ b/openml/runs/__init__.py @@ -1,8 +1,26 @@ 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', + 'get_run_trace', + 'initialize_model_from_run', + 'initialize_model_from_trace' +] diff --git a/openml/runs/functions.py b/openml/runs/functions.py index 3ecec7b5f6..3d42196b0b 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -23,8 +23,7 @@ from ..exceptions import OpenMLCacheException, OpenMLServerException from ..tasks import OpenMLTask from .run import OpenMLRun, _get_version_information -from .trace import OpenMLRunTrace, OpenMLTraceIteration - +from .trace import OpenMLRunTrace # _get_version_info, _get_dict and _create_setup_string are in run.py to avoid # circular imports @@ -128,6 +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, 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 @@ -141,19 +141,23 @@ 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, flow_id=flow.flow_id, dataset_id=dataset.dataset_id, model=flow.model, - tags=tags, flow_name=flow.name, + tags=tags, + trace=trace, + 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 @@ -199,7 +203,7 @@ def get_run_trace(run_id): openml.runs.OpenMLTrace """ 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 @@ -231,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 @@ -242,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 @@ -479,15 +483,19 @@ 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 + trace = None - return arff_datacontent, \ - arff_tracecontent, \ - arff_trace_attributes, \ - user_defined_measures_per_fold, \ - user_defined_measures_per_sample + 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): @@ -679,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 = ("parameter_" + 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 @@ -748,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 @@ -769,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: @@ -877,85 +886,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 598dbeb48b..75b8586d87 100644 --- a/openml/runs/run.py +++ b/openml/runs/run.py @@ -27,7 +27,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): @@ -47,8 +47,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_attributes = trace_attributes - self.trace_content = trace_content + self.trace = trace self.error_message = None self.task = task self.flow = flow @@ -119,10 +118,7 @@ def from_filesystem(cls, folder, expect_model=True): 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'] + run.trace = openml.runs.OpenMLRunTrace._from_filesystem(trace_path) return run @@ -167,10 +163,8 @@ def to_filesystem(self, output_directory, store_model=True): 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. @@ -204,29 +198,6 @@ 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 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, @@ -328,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)} @@ -339,8 +316,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 = 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 b1cc088f1a..e47108a371 100644 --- a/openml/runs/trace.py +++ b/openml/runs/trace.py @@ -1,6 +1,17 @@ import arff import json import os +import xmltodict +from collections import OrderedDict + +PREFIX = 'parameter_' +REQUIRED_ATTRIBUTES = [ + 'repeat', + 'fold', + 'iteration', + 'evaluation', + 'selected', +] class OpenMLRunTrace(object): @@ -9,7 +20,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 @@ -26,13 +37,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 @@ -40,42 +51,306 @@ 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): + """Generates an OpenMLRunTrace. + + Generates the trace object from the attributes and content extracted + while running the underlying flow. + + Parameters + ---------- - @staticmethod - def _from_filesystem(file_path): + 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: + 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.') + elif len(attributes) != len(content[0]): + raise ValueError( + 'Trace_attributes and trace_content not compatible:' + ' %s vs %s' % (attributes, content[0]) + ) + + 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): """ - Logic to deserialize the trace from the filesystem + Logic to deserialize the trace from the filesystem. 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'])): - # iterate over first three entrees of a trace row (fold, repeat, trace_iteration) these should be int + 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 cls.trace_from_arff(trace_arff) + + 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. + """ + + 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): + """Generate the arff dictionary for uploading predictions to the server. + + Uses the trace object to generate an arff dictionary representation. + + Returns + ------- + arff_dict : dict + 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'), + ('iteration', 'NUMERIC'), + ('evaluation', 'NUMERIC'), + ('selected', ['true', 'false']), + ] + trace_attributes.extend([ + (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(): + tmp_list = [] + for attr, _ in trace_attributes: + 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: + tmp_list.append('true') + else: + tmp_list.append('false') + else: + 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 + + @classmethod + 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). + + Parameters + ---------- + arff_obj : dict + LIAC arff obj, dict containing attributes, relation, data. + + Returns + ------- + 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() + 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(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 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 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=repeat, + fold=fold, + iteration=iteration, + setup_string=None, + evaluation=evaluation, + selected=selected, + paramaters=parameters, + ) + 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 the 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. ') + 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']) + 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)) + return '[Run id: %d, %d trace iterations]' % ( + self.run_id, + len(self.trace_iterations), + ) class OpenMLTraceIteration(object): @@ -88,7 +363,7 @@ class OpenMLTraceIteration(object): fold : int fold number (in case of no folds: 0) - + iteration : int iteration number of optimization procedure @@ -96,37 +371,76 @@ 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 + + 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 not isinstance(selected, bool): + raise TypeError(type(selected)) + if setup_string and paramaters: + raise ValueError( + '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 passed as ' + '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): 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): """ - 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, 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/openml/testing.py b/openml/testing.py index ed63c6776c..6d6d352012 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.py b/tests/test_runs/test_run.py index 2e309fc2a9..a5368267dd 100644 --- a/tests/test_runs/test_run.py +++ b/tests/test_runs/test_run.py @@ -93,33 +93,50 @@ def _test_run_obj_equals(self, run, run_prime): 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: + 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: 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:] - # JvR: Python 2.7 requires an almost equal check, rather than an equals check + 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([ @@ -127,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) @@ -150,9 +175,17 @@ 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))) + 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) @@ -165,13 +198,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 1521463b13..f8f4ee83c4 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 @@ -82,8 +83,8 @@ 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(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() @@ -119,12 +120,20 @@ 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) self.assertIsInstance(run.dataset_id, int) + # This is only a smoke check right now + # TODO add a few asserts here + run._create_description_xml() + if run.trace is not None: + # 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) @@ -169,6 +178,13 @@ 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): @@ -254,7 +270,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 @@ -327,15 +343,17 @@ def determine_grid_size(param_grid): for fold in run.fold_evaluations['predictive_accuracy'][rep].keys(): accuracy_scores_provided.append( run.fold_evaluations['predictive_accuracy'][rep][fold]) + self.assertEqual(sum(accuracy_scores_provided), sum(accuracy_scores)) if isinstance(clf, BaseSearchCV): + 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(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) @@ -573,7 +591,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.functions._create_trace_from_arff(run._generate_trace_arff_dict()) + trace = openml.runs.functions._create_trace_from_arff( + run._generate_trace_arff_dict() + ) self.assertEqual( len(trace.trace_iterations), num_iterations * num_folds, @@ -711,6 +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! if att_name.startswith("parameter_"): # add this to the found parameters param_name = att_name[len("parameter_"):] @@ -726,10 +748,30 @@ 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) @@ -811,10 +853,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) @@ -823,12 +873,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, _ = 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) @@ -898,7 +952,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) + OpenMLRunTrace.trace_from_arff(trace_arff) def test_get_run(self): # this run is not available on test @@ -1054,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) @@ -1075,8 +1133,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) diff --git a/tests/test_runs/test_trace.py b/tests/test_runs/test_trace.py new file mode 100644 index 0000000000..3aadcafac6 --- /dev/null +++ b/tests/test_runs/test_trace.py @@ -0,0 +1,88 @@ +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.assertRaisesRegexp( + 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 """ + 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.' + ): + OpenMLRunTrace.generate(attributes='foo', content=[]) + with self.assertRaisesRegexp( + ValueError, + '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)