From cfe45f5d7cf50da4c5643d1819c30bd2442d67e2 Mon Sep 17 00:00:00 2001 From: JoaquinVanschoren Date: Thu, 20 Sep 2018 12:18:44 +0200 Subject: [PATCH 01/14] more tasks --- openml/tasks/functions.py | 193 +++++++++++++++++++++++--------------- openml/tasks/task.py | 119 +++++++++++++---------- 2 files changed, 188 insertions(+), 124 deletions(-) diff --git a/openml/tasks/functions.py b/openml/tasks/functions.py index 23283d3647..cce005be03 100644 --- a/openml/tasks/functions.py +++ b/openml/tasks/functions.py @@ -2,34 +2,28 @@ import io import re import os +import shutil from oslo_concurrency import lockutils import xmltodict from ..exceptions import OpenMLCacheException from ..datasets import get_dataset -from .task import OpenMLTask +from .task import ClassificationTask, RegressionTask, ClusteringTask +from .. import config +from .._api_calls import _perform_api_call +from ..utils import _create_cache_directory_for_id import openml.utils -import openml._api_calls - -TASKS_CACHE_DIR_NAME = 'tasks' def _get_cached_tasks(): - """Return a dict of all the tasks which are cached locally. - - Returns - ------- - tasks : OrderedDict - A dict of all the cached tasks. Each task is an instance of - OpenMLTask. - """ - tasks = OrderedDict() + cache_dir = config.get_cache_directory() - task_cache_dir = openml.utils._create_cache_directory(TASKS_CACHE_DIR_NAME) + task_cache_dir = os.path.join(cache_dir, "tasks") directory_content = os.listdir(task_cache_dir) directory_content.sort() + # Find all dataset ids for which we have downloaded the dataset # description @@ -44,27 +38,15 @@ def _get_cached_tasks(): def _get_cached_task(tid): - """Return a cached task based on the given id. - - Parameters - ---------- - tid : int - Id of the task. - - Returns - ------- - OpenMLTask - """ - tid_cache_dir = openml.utils._create_cache_directory_for_id( - TASKS_CACHE_DIR_NAME, - tid - ) + cache_dir = config.get_cache_directory() + task_cache_dir = os.path.join(cache_dir, "tasks") + task_file = os.path.join(task_cache_dir, str(tid), "task.xml") try: - with io.open(os.path.join(tid_cache_dir, "task.xml"), encoding='utf8') as fh: - return _create_task_from_xml(fh.read()) + with io.open(task_file, encoding='utf8') as fh: + task = _create_task_from_xml(xml=fh.read()) + return task except (OSError, IOError): - openml.utils._remove_cache_dir_for_id(TASKS_CACHE_DIR_NAME, tid_cache_dir) raise OpenMLCacheException("Task file for tid %d not " "cached" % tid) @@ -80,7 +62,7 @@ def _get_estimation_procedure_list(): name, type, repeats, folds, stratified. """ - xml_string = openml._api_calls._perform_api_call("estimationprocedure/list") + xml_string = _perform_api_call("estimationprocedure/list") procs_dict = xmltodict.parse(xml_string) # Minimalistic check if the XML is useful if 'oml:estimationprocedures' not in procs_dict: @@ -98,14 +80,12 @@ def _get_estimation_procedure_list(): procs = [] for proc_ in procs_dict['oml:estimationprocedures']['oml:estimationprocedure']: - procs.append( - { - 'id': int(proc_['oml:id']), + proc = {'id': int(proc_['oml:id']), 'task_type_id': int(proc_['oml:ttid']), 'name': proc_['oml:name'], - 'type': proc_['oml:type'], - } - ) + 'type': proc_['oml:type']} + + procs.append(proc) return procs @@ -151,7 +131,7 @@ def list_tasks(task_type_id=None, offset=None, size=None, tag=None, **kwargs): task id, dataset id, task_type and status. If qualities are calculated for the associated dataset, some of these are also returned. """ - return openml.utils._list_all(_list_tasks, task_type_id=task_type_id, offset=offset, size=size, tag=tag, **kwargs) + return openml.utils.list_all(_list_tasks, task_type_id=task_type_id, offset=offset, size=size, tag=tag, **kwargs) def _list_tasks(task_type_id=None, **kwargs): @@ -197,29 +177,27 @@ def _list_tasks(task_type_id=None, **kwargs): def __list_tasks(api_call): - xml_string = openml._api_calls._perform_api_call(api_call) + xml_string = _perform_api_call(api_call) tasks_dict = xmltodict.parse(xml_string, force_list=('oml:task', 'oml:input')) # Minimalistic check if the XML is useful if 'oml:tasks' not in tasks_dict: raise ValueError('Error in return XML, does not contain "oml:runs": %s' % str(tasks_dict)) elif '@xmlns:oml' not in tasks_dict['oml:tasks']: - raise ValueError('Error in return XML, does not contain ' + raise ValueError('Error in return XML, does not contain ' '"oml:runs"/@xmlns:oml: %s' % str(tasks_dict)) elif tasks_dict['oml:tasks']['@xmlns:oml'] != 'http://openml.org/openml': - raise ValueError('Error in return XML, value of ' - '"oml:runs"/@xmlns:oml is not ' + raise ValueError('Error in return XML, value of ' + '"oml:runs"/@xmlns:oml is not ' '"http://openml.org/openml": %s' % str(tasks_dict)) - assert type(tasks_dict['oml:tasks']['oml:task']) == list, \ type(tasks_dict['oml:tasks']) tasks = dict() procs = _get_estimation_procedure_list() proc_dict = dict((x['id'], x) for x in procs) - for task_ in tasks_dict['oml:tasks']['oml:task']: tid = None try: @@ -230,7 +208,6 @@ def __list_tasks(api_call): 'name': task_['oml:name'], 'task_type': task_['oml:task_type'], 'status': task_['oml:status']} - # Other task inputs for input in task_.get('oml:input', list()): if input['@name'] == 'estimation_procedure': @@ -238,7 +215,6 @@ def __list_tasks(api_call): else: value = input.get('#text') task[input['@name']] = value - # The number of qualities can range from 0 to infinity for quality in task_.get('oml:quality', list()): if '#text' not in quality: @@ -259,7 +235,6 @@ def __list_tasks(api_call): ) else: raise KeyError('Could not find key %s in %s!' % (e, task_)) - return tasks @@ -291,14 +266,17 @@ def get_task(task_id): task_id : int The OpenML task id. """ - task_id = int(task_id) - tid_cache_dir = openml.utils._create_cache_directory_for_id( - TASKS_CACHE_DIR_NAME, task_id, - ) + try: + task_id = int(task_id) + except: + raise ValueError("Task ID is neither an Integer nor can be " + "cast to an Integer.") + + tid_cache_dir = _create_task_cache_dir(task_id) with lockutils.external_lock( name='task.functions.get_task:%d' % task_id, - lock_path=openml.utils._create_lockfiles_dir(), + lock_path=os.path.join(config.get_cache_directory(), 'locks'), ): try: task = _get_task_description(task_id) @@ -306,8 +284,9 @@ def get_task(task_id): class_labels = dataset.retrieve_class_labels(task.target_name) task.class_labels = class_labels task.download_split() + except Exception as e: - openml.utils._remove_cache_dir_for_id(TASKS_CACHE_DIR_NAME, tid_cache_dir) + _remove_task_cache_dir(tid_cache_dir) raise e return task @@ -318,29 +297,64 @@ def _get_task_description(task_id): try: return _get_cached_task(task_id) except OpenMLCacheException: - xml_file = os.path.join( - openml.utils._create_cache_directory_for_id(TASKS_CACHE_DIR_NAME, task_id), - "task.xml", - ) - task_xml = openml._api_calls._perform_api_call("task/%d" % task_id) + xml_file = os.path.join(_create_task_cache_dir(task_id), "task.xml") + task_xml = _perform_api_call("task/%d" % task_id) with io.open(xml_file, "w", encoding='utf8') as fh: fh.write(task_xml) - return _create_task_from_xml(task_xml) + task = _create_task_from_xml(task_xml) + + return task -def _create_task_from_xml(xml): - """Create a task given a xml string. +def _create_task_cache_directory(task_id): + """Create a task cache directory + + In order to have a clearer cache structure and because every task + is cached in several files (description, split), there + is a directory for each task witch the task ID being the directory + name. This function creates this cache directory. + + This function is NOT thread/multiprocessing safe. Parameters ---------- - xml : string - Task xml representation. + task_id : int + Task ID Returns ------- - OpenMLTask + str + Path of the created dataset cache directory. + """ + task_cache_dir = os.path.join( + config.get_cache_directory(), "tasks", str(task_id) + ) + if os.path.exists(task_cache_dir) and os.path.isdir(task_cache_dir): + pass + elif os.path.exists(task_cache_dir) and not os.path.isdir(task_cache_dir): + raise ValueError('Task cache dir exists but is not a directory!') + else: + os.makedirs(task_cache_dir) + return task_cache_dir + + +def _remove_task_cache_dir(tid_cache_dir): + """Remove the task cache directory + + This function is NOT thread/multiprocessing safe. + + Parameters + ---------- """ + try: + shutil.rmtree(tid_cache_dir) + except (OSError, IOError): + raise ValueError('Cannot remove faulty task cache directory %s.' + 'Please do this manually!' % tid_cache_dir) + + +def _create_task_from_xml(xml): dic = xmltodict.parse(xml)["oml:task"] estimation_parameters = dict() @@ -356,7 +370,6 @@ def _create_task_from_xml(xml): if 'evaluation_measures' in inputs: evaluation_measures = inputs["evaluation_measures"]["oml:evaluation_measures"]["oml:evaluation_measure"] - # Convert some more parameters for parameter in \ inputs["estimation_procedure"]["oml:estimation_procedure"][ @@ -365,12 +378,40 @@ def _create_task_from_xml(xml): text = parameter.get("#text", "") estimation_parameters[name] = text - return OpenMLTask( - dic["oml:task_id"], dic['oml:task_type_id'], dic["oml:task_type"], - inputs["source_data"]["oml:data_set"]["oml:data_set_id"], - inputs["source_data"]["oml:data_set"]["oml:target_feature"], - inputs["estimation_procedure"]["oml:estimation_procedure"][ - "oml:type"], - inputs["estimation_procedure"]["oml:estimation_procedure"][ - "oml:data_splits_url"], estimation_parameters, - evaluation_measures, None) + task_type = dic["oml:task_type"] + if task_type == "Supervised Classification": + return ClassificationTask( + dic["oml:task_id"], + dic["oml:task_type_id"], + task_type, + inputs["source_data"]["oml:data_set"]["oml:data_set_id"], + inputs["estimation_procedure"]["oml:estimation_procedure"]["oml:type"], + estimation_parameters, + evaluation_measures, + inputs["source_data"]["oml:data_set"]["oml:target_feature"], + inputs["estimation_procedure"]["oml:estimation_procedure"]["oml:data_splits_url"]) + + elif task_type == "Supervised Regression": + return RegressionTask( + dic["oml:task_id"], + dic["oml:task_type_id"], + task_type, + inputs["source_data"]["oml:data_set"]["oml:data_set_id"], + inputs["estimation_procedure"]["oml:estimation_procedure"]["oml:type"], + estimation_parameters, + evaluation_measures, + inputs["source_data"]["oml:data_set"]["oml:target_feature"], + inputs["estimation_procedure"]["oml:estimation_procedure"]["oml:data_splits_url"]) + + elif task_type == "Clustering": + return ClusteringTask( + dic["oml:task_id"], + dic["oml:task_type_id"], + task_type, + inputs["source_data"]["oml:data_set"]["oml:data_set_id"], + inputs["estimation_procedure"]["oml:estimation_procedure"]["oml:type"], + estimation_parameters, + evaluation_measures) + + else: + raise NotImplementedError(task_type) \ No newline at end of file diff --git a/openml/tasks/task.py b/openml/tasks/task.py index 26ff261618..37326555ef 100644 --- a/openml/tasks/task.py +++ b/openml/tasks/task.py @@ -4,41 +4,56 @@ from .. import config from .. import datasets from .split import OpenMLSplit -import openml._api_calls +from .._api_calls import _read_url, _perform_api_call from ..utils import _create_cache_directory_for_id - class OpenMLTask(object): - def __init__(self, task_id, task_type_id, task_type, data_set_id, - target_name, estimation_procedure_type, data_splits_url, - estimation_parameters, evaluation_measure, cost_matrix, - class_labels=None): + def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + estimation_parameters, evaluation_measure): self.task_id = int(task_id) self.task_type_id = int(task_type_id) self.task_type = task_type self.dataset_id = int(data_set_id) - self.target_name = target_name self.estimation_procedure = dict() self.estimation_procedure["type"] = estimation_procedure_type - self.estimation_procedure["data_splits_url"] = data_splits_url self.estimation_procedure["parameters"] = estimation_parameters # self.estimation_parameters = estimation_parameters self.evaluation_measure = evaluation_measure - self.cost_matrix = cost_matrix - self.class_labels = class_labels - self.split = None - - if cost_matrix is not None: - raise NotImplementedError("Costmatrix") def get_dataset(self): """Download dataset associated with task""" return datasets.get_dataset(self.dataset_id) + def download_split(self): + """Download the OpenML split for a given task. + """ + # Not all tasks come with a split, e.g. in clustering the full dataset is always used + if self.estimation_procedure["data_splits_url"]: + + cached_split_file = os.path.join( + _create_task_cache_dir(self.task_id), "datasplits.arff") + + try: + split = OpenMLSplit._from_arff_file(cached_split_file) + # Add FileNotFoundError in python3 version (which should be a + # subclass of OSError. + except (OSError, IOError): + # Next, download and cache the associated split file + self._download_split(cached_split_file) + split = OpenMLSplit._from_arff_file(cached_split_file) + + return split + + else: # if no data splits are used + no_split = {0: {0: {0: (list(range(self.get_dataset().get_data().shape[0])), + list(range(self.get_dataset().get_data().shape[0])))}}} + split = OpenMLSplit('no_split', 'no actual split, all points in train and test', no_split) + return split + def get_X_and_y(self): """Get data associated with the current task. - + Returns ------- tuple - X and y @@ -58,41 +73,10 @@ def get_train_test_split_indices(self, fold=0, repeat=0, sample=0): train_indices, test_indices = self.split.get(repeat=repeat, fold=fold, sample=sample) return train_indices, test_indices - def _download_split(self, cache_file): - try: - with io.open(cache_file, encoding='utf8'): - pass - except (OSError, IOError): - split_url = self.estimation_procedure["data_splits_url"] - split_arff = openml._api_calls._read_url(split_url) - - with io.open(cache_file, "w", encoding='utf8') as fh: - fh.write(split_arff) - del split_arff - - def download_split(self): - """Download the OpenML split for a given task. - """ - cached_split_file = os.path.join( - _create_cache_directory_for_id('tasks', self.task_id), - "datasplits.arff", - ) - - try: - split = OpenMLSplit._from_arff_file(cached_split_file) - except (OSError, IOError): - # Next, download and cache the associated split file - self._download_split(cached_split_file) - split = OpenMLSplit._from_arff_file(cached_split_file) - - return split - def get_split_dimensions(self): if self.split is None: self.split = self.download_split() - return self.split.repeats, self.split.folds, self.split.samples - def push_tag(self, tag): """Annotates this task with a tag on the server. @@ -102,7 +86,7 @@ def push_tag(self, tag): Tag to attach to the task. """ data = {'task_id': self.task_id, 'tag': tag} - openml._api_calls._perform_api_call("/task/tag", data=data) + _perform_api_call("/task/tag", data=data) def remove_tag(self, tag): """Removes a tag from this task on the server. @@ -113,4 +97,43 @@ def remove_tag(self, tag): Tag to attach to the task. """ data = {'task_id': self.task_id, 'tag': tag} - openml._api_calls._perform_api_call("/task/untag", data=data) + _perform_api_call("/task/untag", data=data) + +class ClassificationTask(OpenMLTask): + def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + estimation_parameters, evaluation_measure, target_name, data_splits_url, class_labels=None, cost_matrix=None): + super().__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + estimation_parameters, evaluation_measure) + self.target_name = target_name + self.class_labels = class_labels + self.cost_matrix = cost_matrix + self.estimation_procedure["data_splits_url"] = data_splits_url + self.split = None + + if cost_matrix is not None: + raise NotImplementedError("Costmatrix") + +class RegressionTask(OpenMLTask): + def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + estimation_parameters, evaluation_measure, target_name, data_splits_url): + super().__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + estimation_parameters, evaluation_measure) + self.target_name = target_name + self.estimation_procedure["data_splits_url"] = data_splits_url + self.split = None + +class ClusteringTask(OpenMLTask): + def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + estimation_parameters, evaluation_measure, number_of_clusters=None): + super().__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + estimation_parameters, evaluation_measure) + self.number_of_clusters = number_of_clusters + + + + + + + + + From 1a6b6ce7972a45db619ec9413276c05337aea13e Mon Sep 17 00:00:00 2001 From: JoaquinVanschoren Date: Thu, 20 Sep 2018 14:44:28 +0200 Subject: [PATCH 02/14] cleanup and fixes --- openml/tasks/functions.py | 143 +++++++++++++++++--------------------- openml/tasks/task.py | 119 ++++++++++++++++++------------- 2 files changed, 132 insertions(+), 130 deletions(-) diff --git a/openml/tasks/functions.py b/openml/tasks/functions.py index cce005be03..5f86a62871 100644 --- a/openml/tasks/functions.py +++ b/openml/tasks/functions.py @@ -2,7 +2,6 @@ import io import re import os -import shutil from oslo_concurrency import lockutils import xmltodict @@ -10,17 +9,21 @@ from ..exceptions import OpenMLCacheException from ..datasets import get_dataset from .task import ClassificationTask, RegressionTask, ClusteringTask -from .. import config -from .._api_calls import _perform_api_call -from ..utils import _create_cache_directory_for_id import openml.utils +import openml._api_calls +TASKS_CACHE_DIR_NAME = 'tasks' def _get_cached_tasks(): + """Return a dict of all the tasks which are cached locally. + Returns + ------- + tasks : OrderedDict + A dict of all the cached tasks. Each task is an instance of + OpenMLTask. + """ tasks = OrderedDict() - cache_dir = config.get_cache_directory() - - task_cache_dir = os.path.join(cache_dir, "tasks") + task_cache_dir = openml.utils._create_cache_directory(TASKS_CACHE_DIR_NAME) directory_content = os.listdir(task_cache_dir) directory_content.sort() @@ -37,16 +40,29 @@ def _get_cached_tasks(): return tasks + def _get_cached_task(tid): - cache_dir = config.get_cache_directory() - task_cache_dir = os.path.join(cache_dir, "tasks") - task_file = os.path.join(task_cache_dir, str(tid), "task.xml") + """Return a cached task based on the given id. + + Parameters + ---------- + tid : int + Id of the task. + + Returns + ------- + OpenMLTask + """ + tid_cache_dir = openml.utils._create_cache_directory_for_id( + TASKS_CACHE_DIR_NAME, + tid + ) try: - with io.open(task_file, encoding='utf8') as fh: - task = _create_task_from_xml(xml=fh.read()) - return task + with io.open(os.path.join(tid_cache_dir, "task.xml"), encoding='utf8') as fh: + return _create_task_from_xml(fh.read()) except (OSError, IOError): + openml.utils._remove_cache_dir_for_id(TASKS_CACHE_DIR_NAME, tid_cache_dir) raise OpenMLCacheException("Task file for tid %d not " "cached" % tid) @@ -62,7 +78,7 @@ def _get_estimation_procedure_list(): name, type, repeats, folds, stratified. """ - xml_string = _perform_api_call("estimationprocedure/list") + xml_string = openml._api_calls._perform_api_call("estimationprocedure/list") procs_dict = xmltodict.parse(xml_string) # Minimalistic check if the XML is useful if 'oml:estimationprocedures' not in procs_dict: @@ -80,12 +96,14 @@ def _get_estimation_procedure_list(): procs = [] for proc_ in procs_dict['oml:estimationprocedures']['oml:estimationprocedure']: - proc = {'id': int(proc_['oml:id']), + procs.append( + { + 'id': int(proc_['oml:id']), 'task_type_id': int(proc_['oml:ttid']), 'name': proc_['oml:name'], - 'type': proc_['oml:type']} - - procs.append(proc) + 'type': proc_['oml:type'], + } + ) return procs @@ -131,7 +149,7 @@ def list_tasks(task_type_id=None, offset=None, size=None, tag=None, **kwargs): task id, dataset id, task_type and status. If qualities are calculated for the associated dataset, some of these are also returned. """ - return openml.utils.list_all(_list_tasks, task_type_id=task_type_id, offset=offset, size=size, tag=tag, **kwargs) + return openml.utils._list_all(_list_tasks, task_type_id=task_type_id, offset=offset, size=size, tag=tag, **kwargs) def _list_tasks(task_type_id=None, **kwargs): @@ -177,27 +195,29 @@ def _list_tasks(task_type_id=None, **kwargs): def __list_tasks(api_call): - xml_string = _perform_api_call(api_call) + xml_string = openml._api_calls._perform_api_call(api_call) tasks_dict = xmltodict.parse(xml_string, force_list=('oml:task', 'oml:input')) # Minimalistic check if the XML is useful if 'oml:tasks' not in tasks_dict: raise ValueError('Error in return XML, does not contain "oml:runs": %s' % str(tasks_dict)) elif '@xmlns:oml' not in tasks_dict['oml:tasks']: - raise ValueError('Error in return XML, does not contain ' + raise ValueError('Error in return XML, does not contain ' '"oml:runs"/@xmlns:oml: %s' % str(tasks_dict)) elif tasks_dict['oml:tasks']['@xmlns:oml'] != 'http://openml.org/openml': - raise ValueError('Error in return XML, value of ' - '"oml:runs"/@xmlns:oml is not ' + raise ValueError('Error in return XML, value of ' + '"oml:runs"/@xmlns:oml is not ' '"http://openml.org/openml": %s' % str(tasks_dict)) + assert type(tasks_dict['oml:tasks']['oml:task']) == list, \ type(tasks_dict['oml:tasks']) tasks = dict() procs = _get_estimation_procedure_list() proc_dict = dict((x['id'], x) for x in procs) + for task_ in tasks_dict['oml:tasks']['oml:task']: tid = None try: @@ -208,6 +228,7 @@ def __list_tasks(api_call): 'name': task_['oml:name'], 'task_type': task_['oml:task_type'], 'status': task_['oml:status']} + # Other task inputs for input in task_.get('oml:input', list()): if input['@name'] == 'estimation_procedure': @@ -215,6 +236,7 @@ def __list_tasks(api_call): else: value = input.get('#text') task[input['@name']] = value + # The number of qualities can range from 0 to infinity for quality in task_.get('oml:quality', list()): if '#text' not in quality: @@ -235,6 +257,7 @@ def __list_tasks(api_call): ) else: raise KeyError('Could not find key %s in %s!' % (e, task_)) + return tasks @@ -266,17 +289,14 @@ def get_task(task_id): task_id : int The OpenML task id. """ - try: - task_id = int(task_id) - except: - raise ValueError("Task ID is neither an Integer nor can be " - "cast to an Integer.") - - tid_cache_dir = _create_task_cache_dir(task_id) + task_id = int(task_id) + tid_cache_dir = openml.utils._create_cache_directory_for_id( + TASKS_CACHE_DIR_NAME, task_id, + ) with lockutils.external_lock( name='task.functions.get_task:%d' % task_id, - lock_path=os.path.join(config.get_cache_directory(), 'locks'), + lock_path=openml.utils._create_lockfiles_dir(), ): try: task = _get_task_description(task_id) @@ -284,9 +304,8 @@ def get_task(task_id): class_labels = dataset.retrieve_class_labels(task.target_name) task.class_labels = class_labels task.download_split() - except Exception as e: - _remove_task_cache_dir(tid_cache_dir) + openml.utils._remove_cache_dir_for_id(TASKS_CACHE_DIR_NAME, tid_cache_dir) raise e return task @@ -297,64 +316,28 @@ def _get_task_description(task_id): try: return _get_cached_task(task_id) except OpenMLCacheException: - xml_file = os.path.join(_create_task_cache_dir(task_id), "task.xml") - task_xml = _perform_api_call("task/%d" % task_id) + xml_file = os.path.join( + openml.utils._create_cache_directory_for_id(TASKS_CACHE_DIR_NAME, task_id), + "task.xml", + ) + task_xml = openml._api_calls._perform_api_call("task/%d" % task_id) with io.open(xml_file, "w", encoding='utf8') as fh: fh.write(task_xml) - task = _create_task_from_xml(task_xml) + return _create_task_from_xml(task_xml) - return task - - -def _create_task_cache_directory(task_id): - """Create a task cache directory - - In order to have a clearer cache structure and because every task - is cached in several files (description, split), there - is a directory for each task witch the task ID being the directory - name. This function creates this cache directory. - - This function is NOT thread/multiprocessing safe. +def _create_task_from_xml(xml): + """Create a task given a xml string. Parameters ---------- - task_id : int - Task ID + xml : string + Task xml representation. Returns ------- - str - Path of the created dataset cache directory. + OpenMLTask """ - task_cache_dir = os.path.join( - config.get_cache_directory(), "tasks", str(task_id) - ) - if os.path.exists(task_cache_dir) and os.path.isdir(task_cache_dir): - pass - elif os.path.exists(task_cache_dir) and not os.path.isdir(task_cache_dir): - raise ValueError('Task cache dir exists but is not a directory!') - else: - os.makedirs(task_cache_dir) - return task_cache_dir - - -def _remove_task_cache_dir(tid_cache_dir): - """Remove the task cache directory - - This function is NOT thread/multiprocessing safe. - - Parameters - ---------- - """ - try: - shutil.rmtree(tid_cache_dir) - except (OSError, IOError): - raise ValueError('Cannot remove faulty task cache directory %s.' - 'Please do this manually!' % tid_cache_dir) - - -def _create_task_from_xml(xml): dic = xmltodict.parse(xml)["oml:task"] estimation_parameters = dict() diff --git a/openml/tasks/task.py b/openml/tasks/task.py index 37326555ef..d0951bda6a 100644 --- a/openml/tasks/task.py +++ b/openml/tasks/task.py @@ -4,7 +4,7 @@ from .. import config from .. import datasets from .split import OpenMLSplit -from .._api_calls import _read_url, _perform_api_call +import openml._api_calls from ..utils import _create_cache_directory_for_id class OpenMLTask(object): @@ -25,31 +25,36 @@ def get_dataset(self): """Download dataset associated with task""" return datasets.get_dataset(self.dataset_id) - def download_split(self): - """Download the OpenML split for a given task. - """ - # Not all tasks come with a split, e.g. in clustering the full dataset is always used - if self.estimation_procedure["data_splits_url"]: + def push_tag(self, tag): + """Annotates this task with a tag on the server. - cached_split_file = os.path.join( - _create_task_cache_dir(self.task_id), "datasplits.arff") + Parameters + ---------- + tag : str + Tag to attach to the task. + """ + data = {'task_id': self.task_id, 'tag': tag} + openml._api_calls._perform_api_call("/task/tag", data=data) - try: - split = OpenMLSplit._from_arff_file(cached_split_file) - # Add FileNotFoundError in python3 version (which should be a - # subclass of OSError. - except (OSError, IOError): - # Next, download and cache the associated split file - self._download_split(cached_split_file) - split = OpenMLSplit._from_arff_file(cached_split_file) + def remove_tag(self, tag): + """Removes a tag from this task on the server. - return split + Parameters + ---------- + tag : str + Tag to attach to the task. + """ + data = {'task_id': self.task_id, 'tag': tag} + openml._api_calls._perform_api_call("/task/untag", data=data) - else: # if no data splits are used - no_split = {0: {0: {0: (list(range(self.get_dataset().get_data().shape[0])), - list(range(self.get_dataset().get_data().shape[0])))}}} - split = OpenMLSplit('no_split', 'no actual split, all points in train and test', no_split) - return split +class SupervisedTask(OpenMLTask): + def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + estimation_parameters, evaluation_measure, target_name, data_splits_url): + super().__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + estimation_parameters, evaluation_measure) + self.target_name = target_name + self.estimation_procedure["data_splits_url"] = data_splits_url + self.split = None def get_X_and_y(self): """Get data associated with the current task. @@ -73,37 +78,54 @@ def get_train_test_split_indices(self, fold=0, repeat=0, sample=0): train_indices, test_indices = self.split.get(repeat=repeat, fold=fold, sample=sample) return train_indices, test_indices - def get_split_dimensions(self): - if self.split is None: - self.split = self.download_split() + def _download_split(self, cache_file): + try: + with io.open(cache_file, encoding='utf8'): + pass + except (OSError, IOError): + split_url = self.estimation_procedure["data_splits_url"] + split_arff = openml._api_calls._read_url(split_url) - def push_tag(self, tag): - """Annotates this task with a tag on the server. + with io.open(cache_file, "w", encoding='utf8') as fh: + fh.write(split_arff) + del split_arff - Parameters - ---------- - tag : str - Tag to attach to the task. + def download_split(self): + """Download the OpenML split for a given task. """ - data = {'task_id': self.task_id, 'tag': tag} - _perform_api_call("/task/tag", data=data) + cached_split_file = os.path.join( + _create_cache_directory_for_id('tasks', self.task_id), + "datasplits.arff", + ) - def remove_tag(self, tag): - """Removes a tag from this task on the server. + # Not all tasks come with a split, e.g. in clustering the full dataset is always used + if self.estimation_procedure["data_splits_url"]: - Parameters - ---------- - tag : str - Tag to attach to the task. - """ - data = {'task_id': self.task_id, 'tag': tag} - _perform_api_call("/task/untag", data=data) + try: + split = OpenMLSplit._from_arff_file(cached_split_file) + except (OSError, IOError): + # Next, download and cache the associated split file + self._download_split(cached_split_file) + split = OpenMLSplit._from_arff_file(cached_split_file) + + return split -class ClassificationTask(OpenMLTask): + else: # if no data splits are used + no_split = {0: {0: {0: (list(range(self.get_dataset().get_data().shape[0])), + list(range(self.get_dataset().get_data().shape[0])))}}} + split = OpenMLSplit('no_split', 'no actual split, all points in train and test', no_split) + return split + + def get_split_dimensions(self): + if self.split is None: + self.split = self.download_split() + + +class ClassificationTask(SupervisedTask): def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, target_name, data_splits_url, class_labels=None, cost_matrix=None): super().__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, - estimation_parameters, evaluation_measure) + estimation_parameters, evaluation_measure, target_name, data_splits_url) self.target_name = target_name self.class_labels = class_labels self.cost_matrix = cost_matrix @@ -113,14 +135,12 @@ def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_pro if cost_matrix is not None: raise NotImplementedError("Costmatrix") -class RegressionTask(OpenMLTask): +class RegressionTask(SupervisedTask): def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, target_name, data_splits_url): super().__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, - estimation_parameters, evaluation_measure) - self.target_name = target_name - self.estimation_procedure["data_splits_url"] = data_splits_url - self.split = None + estimation_parameters, evaluation_measure, target_name, data_splits_url) + class ClusteringTask(OpenMLTask): def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, @@ -136,4 +156,3 @@ def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_pro - From c7bb4c86bbc8d477433ea1c369479bbd55a8a619 Mon Sep 17 00:00:00 2001 From: bilgecelik Date: Thu, 20 Sep 2018 16:17:59 +0200 Subject: [PATCH 03/14] tasks fixes --- openml/tasks/functions.py | 158 ++++++++++++++------------------------ openml/tasks/task.py | 75 ++++++++++-------- 2 files changed, 101 insertions(+), 132 deletions(-) diff --git a/openml/tasks/functions.py b/openml/tasks/functions.py index cce005be03..cf99ecf936 100644 --- a/openml/tasks/functions.py +++ b/openml/tasks/functions.py @@ -2,7 +2,6 @@ import io import re import os -import shutil from oslo_concurrency import lockutils import xmltodict @@ -10,20 +9,26 @@ from ..exceptions import OpenMLCacheException from ..datasets import get_dataset from .task import ClassificationTask, RegressionTask, ClusteringTask -from .. import config -from .._api_calls import _perform_api_call -from ..utils import _create_cache_directory_for_id import openml.utils +import openml._api_calls + +TASKS_CACHE_DIR_NAME = 'tasks' def _get_cached_tasks(): + """Return a dict of all the tasks which are cached locally. + Returns + ------- + tasks : OrderedDict + A dict of all the cached tasks. Each task is an instance of + OpenMLTask. + """ + tasks = OrderedDict() - cache_dir = config.get_cache_directory() - task_cache_dir = os.path.join(cache_dir, "tasks") + task_cache_dir = openml.utils._create_cache_directory(TASKS_CACHE_DIR_NAME) directory_content = os.listdir(task_cache_dir) directory_content.sort() - # Find all dataset ids for which we have downloaded the dataset # description @@ -38,22 +43,31 @@ def _get_cached_tasks(): def _get_cached_task(tid): - cache_dir = config.get_cache_directory() - task_cache_dir = os.path.join(cache_dir, "tasks") - task_file = os.path.join(task_cache_dir, str(tid), "task.xml") + """Return a cached task based on the given id. + Parameters + ---------- + tid : int + Id of the task. + Returns + ------- + OpenMLTask + """ + tid_cache_dir = openml.utils._create_cache_directory_for_id( + TASKS_CACHE_DIR_NAME, + tid + ) try: - with io.open(task_file, encoding='utf8') as fh: - task = _create_task_from_xml(xml=fh.read()) - return task + with io.open(os.path.join(tid_cache_dir, "task.xml"), encoding='utf8') as fh: + return _create_task_from_xml(fh.read()) except (OSError, IOError): + openml.utils._remove_cache_dir_for_id(TASKS_CACHE_DIR_NAME, tid_cache_dir) raise OpenMLCacheException("Task file for tid %d not " "cached" % tid) def _get_estimation_procedure_list(): """Return a list of all estimation procedures which are on OpenML. - Returns ------- procedures : list @@ -62,7 +76,7 @@ def _get_estimation_procedure_list(): name, type, repeats, folds, stratified. """ - xml_string = _perform_api_call("estimationprocedure/list") + xml_string = openml._api_calls._perform_api_call("estimationprocedure/list") procs_dict = xmltodict.parse(xml_string) # Minimalistic check if the XML is useful if 'oml:estimationprocedures' not in procs_dict: @@ -80,12 +94,14 @@ def _get_estimation_procedure_list(): procs = [] for proc_ in procs_dict['oml:estimationprocedures']['oml:estimationprocedure']: - proc = {'id': int(proc_['oml:id']), + procs.append( + { + 'id': int(proc_['oml:id']), 'task_type_id': int(proc_['oml:ttid']), 'name': proc_['oml:name'], - 'type': proc_['oml:type']} - - procs.append(proc) + 'type': proc_['oml:type'], + } + ) return procs @@ -93,17 +109,14 @@ def _get_estimation_procedure_list(): def list_tasks(task_type_id=None, offset=None, size=None, tag=None, **kwargs): """ Return a number of tasks having the given tag and task_type_id - Parameters ---------- Filter task_type_id is separated from the other filters because it is used as task_type_id in the task description, but it is named type when used as a filter in list tasks call. - task_type_id : int, optional ID of the task type as detailed `here `_. - - Supervised classification: 1 - Supervised regression: 2 - Learning curve: 3 @@ -118,11 +131,9 @@ def list_tasks(task_type_id=None, offset=None, size=None, tag=None, **kwargs): the maximum number of tasks to show tag : str, optional the tag to include - kwargs: dict, optional Legal filter operators: data_tag, status, data_id, data_name, number_instances, number_features, number_classes, number_missing_values. - Returns ------- dict @@ -131,23 +142,20 @@ def list_tasks(task_type_id=None, offset=None, size=None, tag=None, **kwargs): task id, dataset id, task_type and status. If qualities are calculated for the associated dataset, some of these are also returned. """ - return openml.utils.list_all(_list_tasks, task_type_id=task_type_id, offset=offset, size=size, tag=tag, **kwargs) + return openml.utils._list_all(_list_tasks, task_type_id=task_type_id, offset=offset, size=size, tag=tag, **kwargs) def _list_tasks(task_type_id=None, **kwargs): """ Perform the api call to return a number of tasks having the given filters. - Parameters ---------- Filter task_type_id is separated from the other filters because it is used as task_type_id in the task description, but it is named type when used as a filter in list tasks call. - task_type_id : int, optional ID of the task type as detailed `here `_. - - Supervised classification: 1 - Supervised regression: 2 - Learning curve: 3 @@ -156,12 +164,10 @@ def _list_tasks(task_type_id=None, **kwargs): - Machine Learning Challenge: 6 - Survival Analysis: 7 - Subgroup Discovery: 8 - kwargs: dict, optional Legal filter operators: tag, data_tag, status, limit, offset, data_id, data_name, number_instances, number_features, number_classes, number_missing_values. - Returns ------- dict @@ -177,27 +183,29 @@ def _list_tasks(task_type_id=None, **kwargs): def __list_tasks(api_call): - xml_string = _perform_api_call(api_call) + xml_string = openml._api_calls._perform_api_call(api_call) tasks_dict = xmltodict.parse(xml_string, force_list=('oml:task', 'oml:input')) # Minimalistic check if the XML is useful if 'oml:tasks' not in tasks_dict: raise ValueError('Error in return XML, does not contain "oml:runs": %s' % str(tasks_dict)) elif '@xmlns:oml' not in tasks_dict['oml:tasks']: - raise ValueError('Error in return XML, does not contain ' + raise ValueError('Error in return XML, does not contain ' '"oml:runs"/@xmlns:oml: %s' % str(tasks_dict)) elif tasks_dict['oml:tasks']['@xmlns:oml'] != 'http://openml.org/openml': - raise ValueError('Error in return XML, value of ' - '"oml:runs"/@xmlns:oml is not ' + raise ValueError('Error in return XML, value of ' + '"oml:runs"/@xmlns:oml is not ' '"http://openml.org/openml": %s' % str(tasks_dict)) + assert type(tasks_dict['oml:tasks']['oml:task']) == list, \ type(tasks_dict['oml:tasks']) tasks = dict() procs = _get_estimation_procedure_list() proc_dict = dict((x['id'], x) for x in procs) + for task_ in tasks_dict['oml:tasks']['oml:task']: tid = None try: @@ -208,6 +216,7 @@ def __list_tasks(api_call): 'name': task_['oml:name'], 'task_type': task_['oml:task_type'], 'status': task_['oml:status']} + # Other task inputs for input in task_.get('oml:input', list()): if input['@name'] == 'estimation_procedure': @@ -215,6 +224,7 @@ def __list_tasks(api_call): else: value = input.get('#text') task[input['@name']] = value + # The number of qualities can range from 0 to infinity for quality in task_.get('oml:quality', list()): if '#text' not in quality: @@ -235,19 +245,17 @@ def __list_tasks(api_call): ) else: raise KeyError('Could not find key %s in %s!' % (e, task_)) + return tasks def get_tasks(task_ids): """Download tasks. - This function iterates :meth:`openml.tasks.get_task`. - Parameters ---------- task_ids : iterable Integers representing task ids. - Returns ------- list @@ -260,23 +268,19 @@ def get_tasks(task_ids): def get_task(task_id): """Download the OpenML task for a given task ID. - Parameters ---------- task_id : int The OpenML task id. """ - try: - task_id = int(task_id) - except: - raise ValueError("Task ID is neither an Integer nor can be " - "cast to an Integer.") - - tid_cache_dir = _create_task_cache_dir(task_id) + task_id = int(task_id) + tid_cache_dir = openml.utils._create_cache_directory_for_id( + TASKS_CACHE_DIR_NAME, task_id, + ) with lockutils.external_lock( name='task.functions.get_task:%d' % task_id, - lock_path=os.path.join(config.get_cache_directory(), 'locks'), + lock_path=openml.utils._create_lockfiles_dir(), ): try: task = _get_task_description(task_id) @@ -284,9 +288,8 @@ def get_task(task_id): class_labels = dataset.retrieve_class_labels(task.target_name) task.class_labels = class_labels task.download_split() - except Exception as e: - _remove_task_cache_dir(tid_cache_dir) + openml.utils._remove_cache_dir_for_id(TASKS_CACHE_DIR_NAME, tid_cache_dir) raise e return task @@ -297,62 +300,15 @@ def _get_task_description(task_id): try: return _get_cached_task(task_id) except OpenMLCacheException: - xml_file = os.path.join(_create_task_cache_dir(task_id), "task.xml") - task_xml = _perform_api_call("task/%d" % task_id) + xml_file = os.path.join( + openml.utils._create_cache_directory_for_id(TASKS_CACHE_DIR_NAME, task_id), + "task.xml", + ) + task_xml = openml._api_calls._perform_api_call("task/%d" % task_id) with io.open(xml_file, "w", encoding='utf8') as fh: fh.write(task_xml) - task = _create_task_from_xml(task_xml) - - return task - - -def _create_task_cache_directory(task_id): - """Create a task cache directory - - In order to have a clearer cache structure and because every task - is cached in several files (description, split), there - is a directory for each task witch the task ID being the directory - name. This function creates this cache directory. - - This function is NOT thread/multiprocessing safe. - - Parameters - ---------- - task_id : int - Task ID - - Returns - ------- - str - Path of the created dataset cache directory. - """ - task_cache_dir = os.path.join( - config.get_cache_directory(), "tasks", str(task_id) - ) - if os.path.exists(task_cache_dir) and os.path.isdir(task_cache_dir): - pass - elif os.path.exists(task_cache_dir) and not os.path.isdir(task_cache_dir): - raise ValueError('Task cache dir exists but is not a directory!') - else: - os.makedirs(task_cache_dir) - return task_cache_dir - - -def _remove_task_cache_dir(tid_cache_dir): - """Remove the task cache directory - - This function is NOT thread/multiprocessing safe. - - Parameters - ---------- - """ - try: - shutil.rmtree(tid_cache_dir) - except (OSError, IOError): - raise ValueError('Cannot remove faulty task cache directory %s.' - 'Please do this manually!' % tid_cache_dir) - + return _create_task_from_xml(task_xml) def _create_task_from_xml(xml): dic = xmltodict.parse(xml)["oml:task"] diff --git a/openml/tasks/task.py b/openml/tasks/task.py index 37326555ef..1d866db14b 100644 --- a/openml/tasks/task.py +++ b/openml/tasks/task.py @@ -4,7 +4,7 @@ from .. import config from .. import datasets from .split import OpenMLSplit -from .._api_calls import _read_url, _perform_api_call +import openml._api_calls from ..utils import _create_cache_directory_for_id class OpenMLTask(object): @@ -25,32 +25,6 @@ def get_dataset(self): """Download dataset associated with task""" return datasets.get_dataset(self.dataset_id) - def download_split(self): - """Download the OpenML split for a given task. - """ - # Not all tasks come with a split, e.g. in clustering the full dataset is always used - if self.estimation_procedure["data_splits_url"]: - - cached_split_file = os.path.join( - _create_task_cache_dir(self.task_id), "datasplits.arff") - - try: - split = OpenMLSplit._from_arff_file(cached_split_file) - # Add FileNotFoundError in python3 version (which should be a - # subclass of OSError. - except (OSError, IOError): - # Next, download and cache the associated split file - self._download_split(cached_split_file) - split = OpenMLSplit._from_arff_file(cached_split_file) - - return split - - else: # if no data splits are used - no_split = {0: {0: {0: (list(range(self.get_dataset().get_data().shape[0])), - list(range(self.get_dataset().get_data().shape[0])))}}} - split = OpenMLSplit('no_split', 'no actual split, all points in train and test', no_split) - return split - def get_X_and_y(self): """Get data associated with the current task. @@ -73,31 +47,70 @@ def get_train_test_split_indices(self, fold=0, repeat=0, sample=0): train_indices, test_indices = self.split.get(repeat=repeat, fold=fold, sample=sample) return train_indices, test_indices + def _download_split(self, cache_file): + try: + with io.open(cache_file, encoding='utf8'): + pass + except (OSError, IOError): + split_url = self.estimation_procedure["data_splits_url"] + split_arff = openml._api_calls._read_url(split_url) + + with io.open(cache_file, "w", encoding='utf8') as fh: + fh.write(split_arff) + del split_arff + + def download_split(self): + """Download the OpenML split for a given task. + """ + + # Not all tasks come with a split, e.g. in clustering the full dataset is always used + if self.estimation_procedure["data_splits_url"]: + + cached_split_file = os.path.join( + _create_cache_directory_for_id('tasks', self.task_id), + "datasplits.arff", + ) + + try: + split = OpenMLSplit._from_arff_file(cached_split_file) + except (OSError, IOError): + # Next, download and cache the associated split file + self._download_split(cached_split_file) + split = OpenMLSplit._from_arff_file(cached_split_file) + + return split + + else: # if no data splits are used + no_split = {0: {0: {0: (list(range(self.get_dataset().get_data().shape[0])), + list(range(self.get_dataset().get_data().shape[0])))}}} + split = OpenMLSplit('no_split', 'no actual split, all points in train and test', no_split) + return split + def get_split_dimensions(self): if self.split is None: self.split = self.download_split() + return self.split.repeats, self.split.folds, self.split.samples + def push_tag(self, tag): """Annotates this task with a tag on the server. - Parameters ---------- tag : str Tag to attach to the task. """ data = {'task_id': self.task_id, 'tag': tag} - _perform_api_call("/task/tag", data=data) + openml._api_calls._perform_api_call("/task/tag", data=data) def remove_tag(self, tag): """Removes a tag from this task on the server. - Parameters ---------- tag : str Tag to attach to the task. """ data = {'task_id': self.task_id, 'tag': tag} - _perform_api_call("/task/untag", data=data) + openml._api_calls._perform_api_call("/task/untag", data=data) class ClassificationTask(OpenMLTask): def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, From e3713dee5d6ccd22912e0cfee0daffb26164c47e Mon Sep 17 00:00:00 2001 From: JoaquinVanschoren Date: Thu, 20 Sep 2018 18:31:09 +0200 Subject: [PATCH 04/14] added missing return --- openml/tasks/task.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/openml/tasks/task.py b/openml/tasks/task.py index d0951bda6a..f4bfaa4757 100644 --- a/openml/tasks/task.py +++ b/openml/tasks/task.py @@ -120,6 +120,9 @@ def get_split_dimensions(self): if self.split is None: self.split = self.download_split() + return self.split.repeats, self.split.folds, self.split.samples + + class ClassificationTask(SupervisedTask): def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, From 0b0e0f1daa3c08b2a188a30be2584fe40b0509f2 Mon Sep 17 00:00:00 2001 From: JoaquinVanschoren Date: Thu, 20 Sep 2018 19:12:35 +0200 Subject: [PATCH 05/14] added learning curve task --- openml/tasks/functions.py | 12 ++++++++++++ openml/tasks/task.py | 14 ++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/openml/tasks/functions.py b/openml/tasks/functions.py index ce805bdac0..97067fda51 100644 --- a/openml/tasks/functions.py +++ b/openml/tasks/functions.py @@ -381,5 +381,17 @@ def _create_task_from_xml(xml): estimation_parameters, evaluation_measures) + elif task_type == "Learning Curve": + return LearningCurveTask( + dic["oml:task_id"], + dic["oml:task_type_id"], + task_type, + inputs["source_data"]["oml:data_set"]["oml:data_set_id"], + inputs["estimation_procedure"]["oml:estimation_procedure"]["oml:type"], + estimation_parameters, + evaluation_measures, + inputs["source_data"]["oml:data_set"]["oml:target_feature"], + inputs["estimation_procedure"]["oml:estimation_procedure"]["oml:data_splits_url"]) + else: raise NotImplementedError(task_type) \ No newline at end of file diff --git a/openml/tasks/task.py b/openml/tasks/task.py index f4bfaa4757..a497a5934b 100644 --- a/openml/tasks/task.py +++ b/openml/tasks/task.py @@ -152,6 +152,20 @@ def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_pro estimation_parameters, evaluation_measure) self.number_of_clusters = number_of_clusters +class LearningCurveTask(SupervisedTask): + def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + estimation_parameters, evaluation_measure, target_name, data_splits_url, class_labels=None, + cost_matrix=None): + super().__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + estimation_parameters, evaluation_measure, target_name, data_splits_url) + self.target_name = target_name + self.class_labels = class_labels + self.cost_matrix = cost_matrix + self.estimation_procedure["data_splits_url"] = data_splits_url + self.split = None + + if cost_matrix is not None: + raise NotImplementedError("Costmatrix") From 26ab96596e64d5572c8f55bc055a1a4fbf5c7c98 Mon Sep 17 00:00:00 2001 From: JoaquinVanschoren Date: Fri, 21 Sep 2018 12:12:55 +0200 Subject: [PATCH 06/14] fixed import --- openml/tasks/functions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openml/tasks/functions.py b/openml/tasks/functions.py index 97067fda51..320b258d3f 100644 --- a/openml/tasks/functions.py +++ b/openml/tasks/functions.py @@ -8,7 +8,7 @@ from ..exceptions import OpenMLCacheException from ..datasets import get_dataset -from .task import ClassificationTask, RegressionTask, ClusteringTask +from .task import ClassificationTask, RegressionTask, ClusteringTask, LearningCurveTask import openml.utils import openml._api_calls From c3021a7c3649a615b708de86c304556c8808c734 Mon Sep 17 00:00:00 2001 From: JoaquinVanschoren Date: Fri, 21 Sep 2018 14:09:51 +0200 Subject: [PATCH 07/14] added 2.7 compatibility --- openml/tasks/task.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/openml/tasks/task.py b/openml/tasks/task.py index a497a5934b..fe5810bb3e 100644 --- a/openml/tasks/task.py +++ b/openml/tasks/task.py @@ -127,7 +127,7 @@ def get_split_dimensions(self): class ClassificationTask(SupervisedTask): def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, target_name, data_splits_url, class_labels=None, cost_matrix=None): - super().__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + super(ClassificationTask, self).__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, target_name, data_splits_url) self.target_name = target_name self.class_labels = class_labels @@ -141,14 +141,14 @@ def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_pro class RegressionTask(SupervisedTask): def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, target_name, data_splits_url): - super().__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + super(RegressionTask, self)).__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, target_name, data_splits_url) class ClusteringTask(OpenMLTask): def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, number_of_clusters=None): - super().__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + super(ClusteringTask, self)).__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure) self.number_of_clusters = number_of_clusters @@ -156,7 +156,7 @@ class LearningCurveTask(SupervisedTask): def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, target_name, data_splits_url, class_labels=None, cost_matrix=None): - super().__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + super(LearningCurveTask, self)).__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, target_name, data_splits_url) self.target_name = target_name self.class_labels = class_labels From 2f0540029427f1bf72bcc44b3ada275d0c1682fd Mon Sep 17 00:00:00 2001 From: JoaquinVanschoren Date: Fri, 21 Sep 2018 15:06:35 +0200 Subject: [PATCH 08/14] typos --- openml/tasks/task.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/openml/tasks/task.py b/openml/tasks/task.py index fe5810bb3e..f2a53f896d 100644 --- a/openml/tasks/task.py +++ b/openml/tasks/task.py @@ -141,14 +141,14 @@ def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_pro class RegressionTask(SupervisedTask): def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, target_name, data_splits_url): - super(RegressionTask, self)).__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + super(RegressionTask, self).__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, target_name, data_splits_url) class ClusteringTask(OpenMLTask): def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, number_of_clusters=None): - super(ClusteringTask, self)).__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + super(ClusteringTask, self).__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure) self.number_of_clusters = number_of_clusters @@ -156,7 +156,7 @@ class LearningCurveTask(SupervisedTask): def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, target_name, data_splits_url, class_labels=None, cost_matrix=None): - super(LearningCurveTask, self)).__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + super(LearningCurveTask, self).__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, target_name, data_splits_url) self.target_name = target_name self.class_labels = class_labels From 1e7aba65df0380dfad1b4fb288bc9fd790bbf263 Mon Sep 17 00:00:00 2001 From: JoaquinVanschoren Date: Fri, 21 Sep 2018 15:59:49 +0200 Subject: [PATCH 09/14] 2.7 compatibility --- openml/tasks/task.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openml/tasks/task.py b/openml/tasks/task.py index f2a53f896d..acd91ee6d9 100644 --- a/openml/tasks/task.py +++ b/openml/tasks/task.py @@ -50,7 +50,7 @@ def remove_tag(self, tag): class SupervisedTask(OpenMLTask): def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, target_name, data_splits_url): - super().__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, + super(SupervisedTask, self).__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure) self.target_name = target_name self.estimation_procedure["data_splits_url"] = data_splits_url From c949a3b9ddcab8540c447f7ad1648e58953c02e9 Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Fri, 21 Sep 2018 18:08:23 +0200 Subject: [PATCH 10/14] MAINT improve style --- openml/tasks/functions.py | 49 ++++++++++---- openml/tasks/task.py | 133 +++++++++++++++++++++++++++----------- 2 files changed, 132 insertions(+), 50 deletions(-) diff --git a/openml/tasks/functions.py b/openml/tasks/functions.py index 320b258d3f..dde46091d8 100644 --- a/openml/tasks/functions.py +++ b/openml/tasks/functions.py @@ -8,7 +8,12 @@ from ..exceptions import OpenMLCacheException from ..datasets import get_dataset -from .task import ClassificationTask, RegressionTask, ClusteringTask, LearningCurveTask +from .task import ( + ClassificationTask, + RegressionTask, + ClusteringTask, + LearningCurveTask, +) import openml.utils import openml._api_calls @@ -290,7 +295,10 @@ def get_task(task_id): task.class_labels = class_labels task.download_split() except Exception as e: - openml.utils._remove_cache_dir_for_id(TASKS_CACHE_DIR_NAME, tid_cache_dir) + openml.utils._remove_cache_dir_for_id( + TASKS_CACHE_DIR_NAME, + tid_cache_dir, + ) raise e return task @@ -302,7 +310,10 @@ def _get_task_description(task_id): return _get_cached_task(task_id) except OpenMLCacheException: xml_file = os.path.join( - openml.utils._create_cache_directory_for_id(TASKS_CACHE_DIR_NAME, task_id), + openml.utils._create_cache_directory_for_id( + TASKS_CACHE_DIR_NAME, + task_id, + ), "task.xml", ) task_xml = openml._api_calls._perform_api_call("task/%d" % task_id) @@ -336,7 +347,8 @@ def _create_task_from_xml(xml): evaluation_measures = None if 'evaluation_measures' in inputs: - evaluation_measures = inputs["evaluation_measures"]["oml:evaluation_measures"]["oml:evaluation_measure"] + evaluation_measures = inputs["evaluation_measures"][ + "oml:evaluation_measures"]["oml:evaluation_measure"] # Convert some more parameters for parameter in \ @@ -353,11 +365,14 @@ def _create_task_from_xml(xml): dic["oml:task_type_id"], task_type, inputs["source_data"]["oml:data_set"]["oml:data_set_id"], - inputs["estimation_procedure"]["oml:estimation_procedure"]["oml:type"], + inputs["estimation_procedure"][ + "oml:estimation_procedure"]["oml:type"], estimation_parameters, evaluation_measures, inputs["source_data"]["oml:data_set"]["oml:target_feature"], - inputs["estimation_procedure"]["oml:estimation_procedure"]["oml:data_splits_url"]) + inputs["estimation_procedure"][ + "oml:estimation_procedure"]["oml:data_splits_url"], + ) elif task_type == "Supervised Regression": return RegressionTask( @@ -365,11 +380,14 @@ def _create_task_from_xml(xml): dic["oml:task_type_id"], task_type, inputs["source_data"]["oml:data_set"]["oml:data_set_id"], - inputs["estimation_procedure"]["oml:estimation_procedure"]["oml:type"], + inputs["estimation_procedure"][ + "oml:estimation_procedure"]["oml:type"], estimation_parameters, evaluation_measures, inputs["source_data"]["oml:data_set"]["oml:target_feature"], - inputs["estimation_procedure"]["oml:estimation_procedure"]["oml:data_splits_url"]) + inputs["estimation_procedure"][ + "oml:estimation_procedure"]["oml:data_splits_url"], + ) elif task_type == "Clustering": return ClusteringTask( @@ -377,9 +395,11 @@ def _create_task_from_xml(xml): dic["oml:task_type_id"], task_type, inputs["source_data"]["oml:data_set"]["oml:data_set_id"], - inputs["estimation_procedure"]["oml:estimation_procedure"]["oml:type"], + inputs["estimation_procedure"][ + "oml:estimation_procedure"]["oml:type"], estimation_parameters, - evaluation_measures) + evaluation_measures, + ) elif task_type == "Learning Curve": return LearningCurveTask( @@ -387,11 +407,14 @@ def _create_task_from_xml(xml): dic["oml:task_type_id"], task_type, inputs["source_data"]["oml:data_set"]["oml:data_set_id"], - inputs["estimation_procedure"]["oml:estimation_procedure"]["oml:type"], + inputs["estimation_procedure"][ + "oml:estimation_procedure"]["oml:type"], estimation_parameters, evaluation_measures, inputs["source_data"]["oml:data_set"]["oml:target_feature"], - inputs["estimation_procedure"]["oml:estimation_procedure"]["oml:data_splits_url"]) + inputs["estimation_procedure"][ + "oml:estimation_procedure"]["oml:data_splits_url"], + ) else: - raise NotImplementedError(task_type) \ No newline at end of file + raise NotImplementedError(task_type) diff --git a/openml/tasks/task.py b/openml/tasks/task.py index acd91ee6d9..2d764f1da4 100644 --- a/openml/tasks/task.py +++ b/openml/tasks/task.py @@ -1,15 +1,16 @@ import io import os -from .. import config from .. import datasets from .split import OpenMLSplit import openml._api_calls from ..utils import _create_cache_directory_for_id + class OpenMLTask(object): - def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, - estimation_parameters, evaluation_measure): + def __init__(self, task_id, task_type_id, task_type, data_set_id, + estimation_procedure_type, estimation_parameters, + evaluation_measure): self.task_id = int(task_id) self.task_type_id = int(task_type_id) self.task_type = task_type @@ -47,11 +48,20 @@ def remove_tag(self, tag): data = {'task_id': self.task_id, 'tag': tag} openml._api_calls._perform_api_call("/task/untag", data=data) + class SupervisedTask(OpenMLTask): - def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, - estimation_parameters, evaluation_measure, target_name, data_splits_url): - super(SupervisedTask, self).__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, - estimation_parameters, evaluation_measure) + def __init__(self, task_id, task_type_id, task_type, data_set_id, + estimation_procedure_type, estimation_parameters, + evaluation_measure, target_name, data_splits_url): + super(SupervisedTask, self).__init__( + task_id=task_id, + task_type_id=task_type_id, + task_type=task_type, + data_set_id=data_set_id, + estimation_procedure_type=estimation_procedure_type, + estimation_parameters=estimation_parameters, + evaluation_measure=evaluation_measure, + ) self.target_name = target_name self.estimation_procedure["data_splits_url"] = data_splits_url self.split = None @@ -75,7 +85,11 @@ def get_train_test_split_indices(self, fold=0, repeat=0, sample=0): if self.split is None: self.split = self.download_split() - train_indices, test_indices = self.split.get(repeat=repeat, fold=fold, sample=sample) + train_indices, test_indices = self.split.get( + repeat=repeat, + fold=fold, + sample=sample, + ) return train_indices, test_indices def _download_split(self, cache_file): @@ -98,7 +112,8 @@ def download_split(self): "datasplits.arff", ) - # Not all tasks come with a split, e.g. in clustering the full dataset is always used + # Not all tasks come with a split, e.g. in clustering the full + # dataset is always used if self.estimation_procedure["data_splits_url"]: try: @@ -111,9 +126,20 @@ def download_split(self): return split else: # if no data splits are used - no_split = {0: {0: {0: (list(range(self.get_dataset().get_data().shape[0])), - list(range(self.get_dataset().get_data().shape[0])))}}} - split = OpenMLSplit('no_split', 'no actual split, all points in train and test', no_split) + no_split = { + 0: { + 0: { + 0: ( + list(range(self.get_dataset().get_data().shape[0])), + list(range(self.get_dataset().get_data().shape[0]))) + } + } + } + split = OpenMLSplit( + 'no_split', + 'no actual split, all points in train and test', + no_split, + ) return split def get_split_dimensions(self): @@ -123,12 +149,22 @@ def get_split_dimensions(self): return self.split.repeats, self.split.folds, self.split.samples - class ClassificationTask(SupervisedTask): - def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, - estimation_parameters, evaluation_measure, target_name, data_splits_url, class_labels=None, cost_matrix=None): - super(ClassificationTask, self).__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, - estimation_parameters, evaluation_measure, target_name, data_splits_url) + def __init__(self, task_id, task_type_id, task_type, data_set_id, + estimation_procedure_type, estimation_parameters, + evaluation_measure, target_name, data_splits_url, + class_labels=None, cost_matrix=None): + super(ClassificationTask, self).__init__( + task_id=task_id, + task_type_id=task_type_id, + task_type=task_type, + data_set_id=data_set_id, + estimation_procedure_type=estimation_procedure_type, + estimation_parameters=estimation_parameters, + evaluation_measure=evaluation_measure, + target_name=target_name, + data_splits_url=data_splits_url, + ) self.target_name = target_name self.class_labels = class_labels self.cost_matrix = cost_matrix @@ -138,26 +174,56 @@ def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_pro if cost_matrix is not None: raise NotImplementedError("Costmatrix") + class RegressionTask(SupervisedTask): - def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, - estimation_parameters, evaluation_measure, target_name, data_splits_url): - super(RegressionTask, self).__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, - estimation_parameters, evaluation_measure, target_name, data_splits_url) + def __init__(self, task_id, task_type_id, task_type, data_set_id, + estimation_procedure_type, estimation_parameters, + evaluation_measure, target_name, data_splits_url): + super(RegressionTask, self).__init__( + task_id=task_id, + task_type_id=task_type_id, + task_type=task_type, + data_set_id=data_set_id, + estimation_procedure_type=estimation_procedure_type, + estimation_parameters=estimation_parameters, + evaluation_measure=evaluation_measure, + target_name=target_name, + data_splits_url=data_splits_url, + ) class ClusteringTask(OpenMLTask): - def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, - estimation_parameters, evaluation_measure, number_of_clusters=None): - super(ClusteringTask, self).__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, - estimation_parameters, evaluation_measure) + def __init__(self, task_id, task_type_id, task_type, data_set_id, + estimation_procedure_type, estimation_parameters, + evaluation_measure, number_of_clusters=None): + super(ClusteringTask, self).__init__( + task_id=task_id, + task_type_id=task_type_id, + task_type=task_type, + data_set_id=data_set_id, + estimation_procedure_type=estimation_procedure_type, + estimation_parameters=estimation_parameters, + evaluation_measure=evaluation_measure, + ) self.number_of_clusters = number_of_clusters + class LearningCurveTask(SupervisedTask): - def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, - estimation_parameters, evaluation_measure, target_name, data_splits_url, class_labels=None, - cost_matrix=None): - super(LearningCurveTask, self).__init__(task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, - estimation_parameters, evaluation_measure, target_name, data_splits_url) + def __init__(self, task_id, task_type_id, task_type, data_set_id, + estimation_procedure_type, estimation_parameters, + evaluation_measure, target_name, data_splits_url, + class_labels=None, cost_matrix=None): + super(LearningCurveTask, self).__init__( + task_id=task_id, + task_type_id=task_type_id, + task_type=task_type, + data_set_id=data_set_id, + estimation_procedure_type=estimation_procedure_type, + estimation_parameters=estimation_parameters, + evaluation_measure=evaluation_measure, + target_name=target_name, + data_splits_url=data_splits_url, + ) self.target_name = target_name self.class_labels = class_labels self.cost_matrix = cost_matrix @@ -166,10 +232,3 @@ def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_pro if cost_matrix is not None: raise NotImplementedError("Costmatrix") - - - - - - - From c07ca12b93862761af740fecbac4f2dcea3ba06b Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Fri, 21 Sep 2018 18:34:29 +0200 Subject: [PATCH 11/14] MAINT refactor if-statement --- openml/tasks/functions.py | 86 +++++++++++++-------------------------- openml/tasks/task.py | 37 ++++------------- 2 files changed, 36 insertions(+), 87 deletions(-) diff --git a/openml/tasks/functions.py b/openml/tasks/functions.py index dde46091d8..e1aea7249a 100644 --- a/openml/tasks/functions.py +++ b/openml/tasks/functions.py @@ -359,62 +359,32 @@ def _create_task_from_xml(xml): estimation_parameters[name] = text task_type = dic["oml:task_type"] - if task_type == "Supervised Classification": - return ClassificationTask( - dic["oml:task_id"], - dic["oml:task_type_id"], - task_type, - inputs["source_data"]["oml:data_set"]["oml:data_set_id"], - inputs["estimation_procedure"][ + common_kwargs = { + 'task_id': dic["oml:task_id"], + 'task_type': task_type, + 'task_type_id': dic["oml:task_type_id"], + 'data_set_id': inputs["source_data"]["oml:data_set"]["oml:data_set_id"], + 'estimation_procedure_type': inputs["estimation_procedure"][ "oml:estimation_procedure"]["oml:type"], - estimation_parameters, - evaluation_measures, - inputs["source_data"]["oml:data_set"]["oml:target_feature"], - inputs["estimation_procedure"][ - "oml:estimation_procedure"]["oml:data_splits_url"], - ) - - elif task_type == "Supervised Regression": - return RegressionTask( - dic["oml:task_id"], - dic["oml:task_type_id"], - task_type, - inputs["source_data"]["oml:data_set"]["oml:data_set_id"], - inputs["estimation_procedure"][ - "oml:estimation_procedure"]["oml:type"], - estimation_parameters, - evaluation_measures, - inputs["source_data"]["oml:data_set"]["oml:target_feature"], - inputs["estimation_procedure"][ - "oml:estimation_procedure"]["oml:data_splits_url"], - ) - - elif task_type == "Clustering": - return ClusteringTask( - dic["oml:task_id"], - dic["oml:task_type_id"], - task_type, - inputs["source_data"]["oml:data_set"]["oml:data_set_id"], - inputs["estimation_procedure"][ - "oml:estimation_procedure"]["oml:type"], - estimation_parameters, - evaluation_measures, - ) - - elif task_type == "Learning Curve": - return LearningCurveTask( - dic["oml:task_id"], - dic["oml:task_type_id"], - task_type, - inputs["source_data"]["oml:data_set"]["oml:data_set_id"], - inputs["estimation_procedure"][ - "oml:estimation_procedure"]["oml:type"], - estimation_parameters, - evaluation_measures, - inputs["source_data"]["oml:data_set"]["oml:target_feature"], - inputs["estimation_procedure"][ - "oml:estimation_procedure"]["oml:data_splits_url"], - ) - - else: - raise NotImplementedError(task_type) + 'estimation_parameters': estimation_parameters, + 'evaluation_measure': evaluation_measures, + } + if task_type in ( + "Supervised Classification", + "Supervised Regression", + "Learning Curve" + ): + common_kwargs['target_name'] = inputs[ + "source_data"]["oml:data_set"]["oml:target_feature"] + common_kwargs['data_splits_url'] = inputs["estimation_procedure"][ + "oml:estimation_procedure"]["oml:data_splits_url"] + + cls = { + "Supervised Classification": ClassificationTask, + "Supervised Regression": RegressionTask, + "Clustering": ClassificationTask, + "Learning Curve": LearningCurveTask, + }.get(task_type) + if cls is None: + raise NotImplementedError('Task type %s not supported.') + return cls(**common_kwargs) diff --git a/openml/tasks/task.py b/openml/tasks/task.py index 2d764f1da4..99060f20c3 100644 --- a/openml/tasks/task.py +++ b/openml/tasks/task.py @@ -112,35 +112,14 @@ def download_split(self): "datasplits.arff", ) - # Not all tasks come with a split, e.g. in clustering the full - # dataset is always used - if self.estimation_procedure["data_splits_url"]: - - try: - split = OpenMLSplit._from_arff_file(cached_split_file) - except (OSError, IOError): - # Next, download and cache the associated split file - self._download_split(cached_split_file) - split = OpenMLSplit._from_arff_file(cached_split_file) - - return split - - else: # if no data splits are used - no_split = { - 0: { - 0: { - 0: ( - list(range(self.get_dataset().get_data().shape[0])), - list(range(self.get_dataset().get_data().shape[0]))) - } - } - } - split = OpenMLSplit( - 'no_split', - 'no actual split, all points in train and test', - no_split, - ) - return split + try: + split = OpenMLSplit._from_arff_file(cached_split_file) + except (OSError, IOError): + # Next, download and cache the associated split file + self._download_split(cached_split_file) + split = OpenMLSplit._from_arff_file(cached_split_file) + + return split def get_split_dimensions(self): if self.split is None: From bc7677f682b37c0cb98c7dd6f9f2e61300816ff9 Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Fri, 21 Sep 2018 18:48:39 +0200 Subject: [PATCH 12/14] MAINT rename classes and import them in main function --- openml/tasks/__init__.py | 22 ++++++++++++++++++++-- openml/tasks/functions.py | 15 +++++++-------- openml/tasks/task.py | 20 ++++++++++---------- 3 files changed, 37 insertions(+), 20 deletions(-) diff --git a/openml/tasks/__init__.py b/openml/tasks/__init__.py index 3784c32a72..2cf210dec9 100644 --- a/openml/tasks/__init__.py +++ b/openml/tasks/__init__.py @@ -1,5 +1,23 @@ -from .task import OpenMLTask +from .task import ( + OpenMLTask, + OpenMLSupervisedTask, + OpenMLClassificationTask, + OpenMLRegressionTask, + OpenMLClusteringTask, + OpenMLLearningCurveTask, +) from .split import OpenMLSplit from .functions import (get_task, get_tasks, list_tasks) -__all__ = ['OpenMLTask', 'get_task', 'get_tasks', 'list_tasks', 'OpenMLSplit'] +__all__ = [ + 'OpenMLTask', + 'OpenMLSupervisedTask', + 'OpenMLClusteringTask', + 'OpenMLRegressionTask', + 'OpenMLClassificationTask', + 'OpenMLLearningCurveTask', + 'get_task', + 'get_tasks', + 'list_tasks', + 'OpenMLSplit', +] diff --git a/openml/tasks/functions.py b/openml/tasks/functions.py index e1aea7249a..26aec9138b 100644 --- a/openml/tasks/functions.py +++ b/openml/tasks/functions.py @@ -9,10 +9,9 @@ from ..exceptions import OpenMLCacheException from ..datasets import get_dataset from .task import ( - ClassificationTask, - RegressionTask, - ClusteringTask, - LearningCurveTask, + ClassificationTaskOpenML, + RegressionTaskOpenML, + LearningCurveTaskOpenML, ) import openml.utils import openml._api_calls @@ -380,10 +379,10 @@ def _create_task_from_xml(xml): "oml:estimation_procedure"]["oml:data_splits_url"] cls = { - "Supervised Classification": ClassificationTask, - "Supervised Regression": RegressionTask, - "Clustering": ClassificationTask, - "Learning Curve": LearningCurveTask, + "Supervised Classification": ClassificationTaskOpenML, + "Supervised Regression": RegressionTaskOpenML, + "Clustering": ClassificationTaskOpenML, + "Learning Curve": LearningCurveTaskOpenML, }.get(task_type) if cls is None: raise NotImplementedError('Task type %s not supported.') diff --git a/openml/tasks/task.py b/openml/tasks/task.py index 99060f20c3..a17f0a059a 100644 --- a/openml/tasks/task.py +++ b/openml/tasks/task.py @@ -49,11 +49,11 @@ def remove_tag(self, tag): openml._api_calls._perform_api_call("/task/untag", data=data) -class SupervisedTask(OpenMLTask): +class OpenMLSupervisedTask(OpenMLTask): def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, target_name, data_splits_url): - super(SupervisedTask, self).__init__( + super(OpenMLSupervisedTask, self).__init__( task_id=task_id, task_type_id=task_type_id, task_type=task_type, @@ -128,12 +128,12 @@ def get_split_dimensions(self): return self.split.repeats, self.split.folds, self.split.samples -class ClassificationTask(SupervisedTask): +class OpenMLClassificationTask(OpenMLSupervisedTask): def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, target_name, data_splits_url, class_labels=None, cost_matrix=None): - super(ClassificationTask, self).__init__( + super(OpenMLClassificationTask, self).__init__( task_id=task_id, task_type_id=task_type_id, task_type=task_type, @@ -154,11 +154,11 @@ def __init__(self, task_id, task_type_id, task_type, data_set_id, raise NotImplementedError("Costmatrix") -class RegressionTask(SupervisedTask): +class OpenMLRegressionTask(OpenMLSupervisedTask): def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, target_name, data_splits_url): - super(RegressionTask, self).__init__( + super(OpenMLRegressionTask, self).__init__( task_id=task_id, task_type_id=task_type_id, task_type=task_type, @@ -171,11 +171,11 @@ def __init__(self, task_id, task_type_id, task_type, data_set_id, ) -class ClusteringTask(OpenMLTask): +class OpenMLClusteringTask(OpenMLTask): def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, number_of_clusters=None): - super(ClusteringTask, self).__init__( + super(OpenMLClusteringTask, self).__init__( task_id=task_id, task_type_id=task_type_id, task_type=task_type, @@ -187,12 +187,12 @@ def __init__(self, task_id, task_type_id, task_type, data_set_id, self.number_of_clusters = number_of_clusters -class LearningCurveTask(SupervisedTask): +class OpenMLLearningCurveTask(OpenMLSupervisedTask): def __init__(self, task_id, task_type_id, task_type, data_set_id, estimation_procedure_type, estimation_parameters, evaluation_measure, target_name, data_splits_url, class_labels=None, cost_matrix=None): - super(LearningCurveTask, self).__init__( + super(OpenMLLearningCurveTask, self).__init__( task_id=task_id, task_type_id=task_type_id, task_type=task_type, From d1443777eb9952a0df362b66b2e294a95c97a4b4 Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Fri, 21 Sep 2018 18:56:35 +0200 Subject: [PATCH 13/14] FIX stupid import errors --- openml/tasks/functions.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/openml/tasks/functions.py b/openml/tasks/functions.py index 26aec9138b..d295493419 100644 --- a/openml/tasks/functions.py +++ b/openml/tasks/functions.py @@ -9,9 +9,10 @@ from ..exceptions import OpenMLCacheException from ..datasets import get_dataset from .task import ( - ClassificationTaskOpenML, - RegressionTaskOpenML, - LearningCurveTaskOpenML, + OpenMLClassificationTask, + OpenMLRegressionTask, + OpenMLClusteringTask, + OpenMLLearningCurveTask, ) import openml.utils import openml._api_calls @@ -379,10 +380,10 @@ def _create_task_from_xml(xml): "oml:estimation_procedure"]["oml:data_splits_url"] cls = { - "Supervised Classification": ClassificationTaskOpenML, - "Supervised Regression": RegressionTaskOpenML, - "Clustering": ClassificationTaskOpenML, - "Learning Curve": LearningCurveTaskOpenML, + "Supervised Classification": OpenMLClassificationTask, + "Supervised Regression": OpenMLRegressionTask, + "Clustering": OpenMLClusteringTask, + "Learning Curve": OpenMLLearningCurveTask, }.get(task_type) if cls is None: raise NotImplementedError('Task type %s not supported.') From 62818c897591eb59f9abddfe887997bbacc7836c Mon Sep 17 00:00:00 2001 From: Matthias Feurer Date: Fri, 21 Sep 2018 19:46:41 +0200 Subject: [PATCH 14/14] fix PEP8 --- openml/tasks/functions.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/openml/tasks/functions.py b/openml/tasks/functions.py index d295493419..2c35325940 100644 --- a/openml/tasks/functions.py +++ b/openml/tasks/functions.py @@ -363,7 +363,8 @@ def _create_task_from_xml(xml): 'task_id': dic["oml:task_id"], 'task_type': task_type, 'task_type_id': dic["oml:task_type_id"], - 'data_set_id': inputs["source_data"]["oml:data_set"]["oml:data_set_id"], + 'data_set_id': inputs["source_data"][ + "oml:data_set"]["oml:data_set_id"], 'estimation_procedure_type': inputs["estimation_procedure"][ "oml:estimation_procedure"]["oml:type"], 'estimation_parameters': estimation_parameters,