diff --git a/examples/40_paper/2015_neurips_feurer_example.py b/examples/40_paper/2015_neurips_feurer_example.py index 106d120df6..6f0de618ec 100644 --- a/examples/40_paper/2015_neurips_feurer_example.py +++ b/examples/40_paper/2015_neurips_feurer_example.py @@ -10,9 +10,80 @@ ~~~~~~~~~~~ | Efficient and Robust Automated Machine Learning -| Matthias Feurer, Aaron Klein, Katharina Eggensperger, Jost Springenberg, Manuel Blum and Frank Hutter +| Matthias Feurer, Aaron Klein, Katharina Eggensperger, Jost Springenberg, Manuel Blum and Frank Hutter # noqa F401 | In *Advances in Neural Information Processing Systems 28*, 2015 | Available at http://papers.nips.cc/paper/5872-efficient-and-robust-automated-machine-learning.pdf - -This is currently a placeholder. """ + +import pandas as pd + +import openml + +#################################################################################################### +# List of dataset IDs given in the supplementary material of Feurer et al.: +# https://papers.nips.cc/paper/5872-efficient-and-robust-automated-machine-learning-supplemental.zip +dataset_ids = [ + 3, 6, 12, 14, 16, 18, 21, 22, 23, 24, 26, 28, 30, 31, 32, 36, 38, 44, 46, + 57, 60, 179, 180, 181, 182, 184, 185, 273, 293, 300, 351, 354, 357, 389, + 390, 391, 392, 393, 395, 396, 398, 399, 401, 554, 679, 715, 718, 720, 722, + 723, 727, 728, 734, 735, 737, 740, 741, 743, 751, 752, 761, 772, 797, 799, + 803, 806, 807, 813, 816, 819, 821, 822, 823, 833, 837, 843, 845, 846, 847, + 849, 866, 871, 881, 897, 901, 903, 904, 910, 912, 913, 914, 917, 923, 930, + 934, 953, 958, 959, 962, 966, 971, 976, 977, 978, 979, 980, 991, 993, 995, + 1000, 1002, 1018, 1019, 1020, 1021, 1036, 1040, 1041, 1049, 1050, 1053, + 1056, 1067, 1068, 1069, 1111, 1112, 1114, 1116, 1119, 1120, 1128, 1130, + 1134, 1138, 1139, 1142, 1146, 1161, 1166, +] + +#################################################################################################### +# The dataset IDs could be used directly to load the dataset and split the data into a training +# and a test set. However, to be reproducible, we will first obtain the respective tasks from +# OpenML, which define both the target feature and the train/test split. +# +# .. note:: +# It is discouraged to work directly on datasets and only provide dataset IDs in a paper as +# this does not allow reproducibility (unclear splitting). Please do not use datasets but the +# respective tasks as basis for a paper and publish task IDS. This example is only given to +# showcase the use OpenML-Python for a published paper and as a warning on how not to do it. +# Please check the `OpenML documentation of tasks `_ if you +# want to learn more about them. + +#################################################################################################### +# This lists both active and inactive tasks (because of ``status='all'``). Unfortunately, +# this is necessary as some of the datasets contain issues found after the publication and became +# deactivated, which also deactivated the tasks on them. More information on active or inactive +# datasets can be found in the `online docs `_. +tasks = openml.tasks.list_tasks( + task_type_id=openml.tasks.TaskTypeEnum.SUPERVISED_CLASSIFICATION, + status='all', + output_format='dataframe', +) + +# Query only those with holdout as the resampling startegy. +tasks = tasks.query('estimation_procedure == "33% Holdout set"') + +task_ids = [] +for did in dataset_ids: + tasks_ = list(tasks.query("did == {}".format(did)).tid) + if len(tasks_) >= 1: # if there are multiple task, take the one with lowest ID (oldest). + task_id = min(tasks_) + else: + raise ValueError(did) + + # Optional - Check that the task has the same target attribute as the + # dataset default target attribute + # (disabled for this example as it needs to run fast to be rendered online) + # task = openml.tasks.get_task(task_id) + # dataset = task.get_dataset() + # if task.target_name != dataset.default_target_attribute: + # raise ValueError( + # (task.target_name, dataset.default_target_attribute) + # ) + + task_ids.append(task_id) + +assert len(task_ids) == 140 +task_ids.sort() + +# These are the tasks to work with: +print(task_ids) diff --git a/examples/40_paper/2018_ida_strang_example.py b/examples/40_paper/2018_ida_strang_example.py index 21165a8ffb..70ed51ba23 100644 --- a/examples/40_paper/2018_ida_strang_example.py +++ b/examples/40_paper/2018_ida_strang_example.py @@ -9,9 +9,92 @@ ~~~~~~~~~~~ | Don't Rule Out Simple Models Prematurely: A Large Scale Benchmark Comparing Linear and Non-linear Classifiers in OpenML -| Benjamin Strang, Pieter Putten, Jan van Rijn and Frank Hutter +| Benjamin Strang, Peter van der Putten, Jan N. van Rijn and Frank Hutter | In *Advances in Intelligent Data Analysis XVII 17th International Symposium*, 2018 | Available at https://link.springer.com/chapter/10.1007%2F978-3-030-01768-2_25 - -This is currently a placeholder. """ +import matplotlib.pyplot as plt +import openml +import pandas as pd + +############################################################################## +# A basic step for each data-mining or machine learning task is to determine +# which model to choose based on the problem and the data at hand. In this +# work we investigate when non-linear classifiers outperform linear +# classifiers by means of a large scale experiment. +# +# The paper is accompanied with a study object, containing all relevant tasks +# and runs (``study_id=123``). The paper features three experiment classes: +# Support Vector Machines (SVM), Neural Networks (NN) and Decision Trees (DT). +# This example demonstrates how to reproduce the plots, comparing two +# classifiers given the OpenML flow ids. Note that this allows us to reproduce +# the SVM and NN experiment, but not the DT experiment, as this requires a bit +# more effort to distinguish the same flow with different hyperparameter +# values. + +study_id = 123 +# for comparing svms: flow_ids = [7754, 7756] +# for comparing nns: flow_ids = [7722, 7729] +# for comparing dts: flow_ids = [7725], differentiate on hyper-parameter value +classifier_family = 'SVM' +flow_ids = [7754, 7756] +measure = 'predictive_accuracy' +meta_features = ['NumberOfInstances', 'NumberOfFeatures'] +class_values = ['non-linear better', 'linear better', 'equal'] + +# Downloads all evaluation records related to this study +evaluations = openml.evaluations.list_evaluations( + measure, flow=flow_ids, study=study_id, output_format='dataframe') +# gives us a table with columns data_id, flow1_value, flow2_value +evaluations = evaluations.pivot( + index='data_id', columns='flow_id', values='value').dropna() +# downloads all data qualities (for scatter plot) +data_qualities = openml.datasets.list_datasets( + data_id=list(evaluations.index.values), output_format='dataframe') +# removes irrelevant data qualities +data_qualities = data_qualities[meta_features] +# makes a join between evaluation table and data qualities table, +# now we have columns data_id, flow1_value, flow2_value, meta_feature_1, +# meta_feature_2 +evaluations = evaluations.join(data_qualities, how='inner') + +# adds column that indicates the difference between the two classifiers +evaluations['diff'] = evaluations[flow_ids[0]] - evaluations[flow_ids[1]] + +# makes the s-plot +fig_splot, ax_splot = plt.subplots() +ax_splot.plot(range(len(evaluations)), sorted(evaluations['diff'])) +ax_splot.set_title(classifier_family) +ax_splot.set_xlabel('Dataset (sorted)') +ax_splot.set_ylabel('difference between linear and non-linear classifier') +ax_splot.grid(linestyle='--', axis='y') +plt.show() + + +# adds column that indicates the difference between the two classifiers +def determine_class(val_lin, val_nonlin): + if val_lin < val_nonlin: + return class_values[0] + elif val_nonlin < val_lin: + return class_values[1] + else: + return class_values[2] + + +evaluations['class'] = evaluations.apply( + lambda row: determine_class(row[flow_ids[0]], row[flow_ids[1]]), axis=1) + +# makes the scatter plot +fig_scatter, ax_scatter = plt.subplots() +for class_val in class_values: + df_class = evaluations[evaluations['class'] == class_val] + plt.scatter(df_class[meta_features[0]], + df_class[meta_features[1]], + label=class_val) +ax_scatter.set_title(classifier_family) +ax_scatter.set_xlabel(meta_features[0]) +ax_scatter.set_ylabel(meta_features[1]) +ax_scatter.legend() +ax_scatter.set_xscale('log') +ax_scatter.set_yscale('log') +plt.show() diff --git a/examples/40_paper/2018_neurips_fusi_example.py b/examples/40_paper/2018_neurips_fusi_example.py deleted file mode 100644 index 656f617fad..0000000000 --- a/examples/40_paper/2018_neurips_fusi_example.py +++ /dev/null @@ -1,17 +0,0 @@ -""" -Fusi et al. (2018) -================== - -A tutorial on how to get the datasets used in the paper introducing *Probabilistic Matrix -Factorization for Automated Machine Learning* by Fusi et al.. - -Publication -~~~~~~~~~~~ - -| Probabilistic Matrix Factorization for Automated Machine Learning -| Nicolo Fusi and Rishit Sheth and Melih Elibol -| In *Advances in Neural Information Processing Systems 31*, 2018 -| Available at http://papers.nips.cc/paper/7595-probabilistic-matrix-factorization-for-automated-machine-learning.pdf - -This is currently a placeholder. -""" diff --git a/openml/datasets/functions.py b/openml/datasets/functions.py index bd33592208..0f8b486cd4 100644 --- a/openml/datasets/functions.py +++ b/openml/datasets/functions.py @@ -190,6 +190,7 @@ def list_qualities() -> List[str]: def list_datasets( + data_id: Optional[List[int]] = None, offset: Optional[int] = None, size: Optional[int] = None, status: Optional[str] = None, @@ -204,6 +205,9 @@ def list_datasets( Parameters ---------- + data_id : list, optional + A list of data ids, to specify which datasets should be + listed offset : int, optional The number of datasets to skip, starting from the first. size : int, optional @@ -251,7 +255,8 @@ def list_datasets( raise ValueError("Invalid output format selected. " "Only 'dict' or 'dataframe' applicable.") - return openml.utils._list_all(output_format=output_format, + return openml.utils._list_all(data_id=data_id, + output_format=output_format, listing_call=_list_datasets, offset=offset, size=size, @@ -260,12 +265,19 @@ def list_datasets( **kwargs) -def _list_datasets(output_format='dict', **kwargs): +def _list_datasets(data_id: Optional[List] = None, output_format='dict', **kwargs): """ Perform api call to return a list of all datasets. Parameters ---------- + The arguments that are lists are separated from the single value + ones which are put into the kwargs. + display_errors is also separated from the kwargs since it has a + default value. + + data_id : list, optional + output_format: str, optional (default='dict') The parameter decides the format of the output. - If 'dict' the output is a dict of dict @@ -285,6 +297,8 @@ def _list_datasets(output_format='dict', **kwargs): if kwargs is not None: for operator, value in kwargs.items(): api_call += "/%s/%s" % (operator, value) + if data_id is not None: + api_call += "/data_id/%s" % ','.join([str(int(i)) for i in data_id]) return __list_datasets(api_call=api_call, output_format=output_format) diff --git a/openml/evaluations/functions.py b/openml/evaluations/functions.py index 6e67623fda..38c31ad12e 100644 --- a/openml/evaluations/functions.py +++ b/openml/evaluations/functions.py @@ -21,6 +21,7 @@ def list_evaluations( flow: Optional[List] = None, uploader: Optional[List] = None, tag: Optional[str] = None, + study: Optional[int] = None, per_fold: Optional[bool] = None, sort_order: Optional[str] = None, output_format: str = 'object' @@ -50,6 +51,8 @@ def list_evaluations( tag : str, optional + study : int, optional + per_fold : bool, optional sort_order : str, optional @@ -84,6 +87,7 @@ def list_evaluations( flow=flow, uploader=uploader, tag=tag, + study=study, sort_order=sort_order, per_fold=per_fold_str) @@ -95,6 +99,7 @@ def _list_evaluations( setup: Optional[List] = None, flow: Optional[List] = None, uploader: Optional[List] = None, + study: Optional[int] = None, sort_order: Optional[str] = None, output_format: str = 'object', **kwargs @@ -120,6 +125,8 @@ def _list_evaluations( uploader : list, optional + study : int, optional + kwargs: dict, optional Legal filter operators: tag, limit, offset. @@ -153,6 +160,8 @@ def _list_evaluations( api_call += "/flow/%s" % ','.join([str(int(i)) for i in flow]) if uploader is not None: api_call += "/uploader/%s" % ','.join([str(int(i)) for i in uploader]) + if study is not None: + api_call += "/study/%d" % study if sort_order is not None: api_call += "/sort_order/%s" % sort_order @@ -196,7 +205,7 @@ def __list_evaluations(api_call, output_format='object'): int(eval_['oml:setup_id']), int(eval_['oml:flow_id']), eval_['oml:flow_name'], - eval_['oml:data_id'], + int(eval_['oml:data_id']), eval_['oml:data_name'], eval_['oml:function'], eval_['oml:upload_time'], @@ -210,7 +219,7 @@ def __list_evaluations(api_call, output_format='object'): 'setup_id': int(eval_['oml:setup_id']), 'flow_id': int(eval_['oml:flow_id']), 'flow_name': eval_['oml:flow_name'], - 'data_id': eval_['oml:data_id'], + 'data_id': int(eval_['oml:data_id']), 'data_name': eval_['oml:data_name'], 'function': eval_['oml:function'], 'upload_time': eval_['oml:upload_time'], diff --git a/openml/runs/functions.py b/openml/runs/functions.py index 623a2544e9..95407d5177 100644 --- a/openml/runs/functions.py +++ b/openml/runs/functions.py @@ -789,6 +789,7 @@ def list_runs( flow: Optional[List] = None, uploader: Optional[List] = None, tag: Optional[str] = None, + study: Optional[int] = None, display_errors: bool = False, output_format: str = 'dict', **kwargs @@ -816,6 +817,8 @@ def list_runs( tag : str, optional + study : int, optional + display_errors : bool, optional (default=None) Whether to list runs which have an error (for example a missing prediction file). @@ -857,6 +860,7 @@ def list_runs( flow=flow, uploader=uploader, tag=tag, + study=study, display_errors=display_errors, **kwargs) @@ -867,6 +871,7 @@ def _list_runs( setup: Optional[List] = None, flow: Optional[List] = None, uploader: Optional[List] = None, + study: Optional[int] = None, display_errors: bool = False, output_format: str = 'dict', **kwargs @@ -892,6 +897,8 @@ def _list_runs( uploader : list, optional + study : int, optional + display_errors : bool, optional (default=None) Whether to list runs which have an error (for example a missing prediction file). @@ -924,6 +931,8 @@ def _list_runs( api_call += "/flow/%s" % ','.join([str(int(i)) for i in flow]) if uploader is not None: api_call += "/uploader/%s" % ','.join([str(int(i)) for i in uploader]) + if study is not None: + api_call += "/study/%d" % study if display_errors: api_call += "/show_errors/true" return __list_runs(api_call=api_call, output_format=output_format) diff --git a/tests/test_datasets/test_dataset_functions.py b/tests/test_datasets/test_dataset_functions.py index 5726d2442a..3453644576 100644 --- a/tests/test_datasets/test_dataset_functions.py +++ b/tests/test_datasets/test_dataset_functions.py @@ -525,23 +525,23 @@ def test_data_status(self): openml.datasets.status_update(did, 'active') # need to use listing fn, as this is immune to cache - result = openml.datasets.list_datasets(data_id=did, status='all') + result = openml.datasets.list_datasets(data_id=[did], status='all') self.assertEqual(len(result), 1) self.assertEqual(result[did]['status'], 'active') openml.datasets.status_update(did, 'deactivated') # need to use listing fn, as this is immune to cache - result = openml.datasets.list_datasets(data_id=did, status='all') + result = openml.datasets.list_datasets(data_id=[did], status='all') self.assertEqual(len(result), 1) self.assertEqual(result[did]['status'], 'deactivated') openml.datasets.status_update(did, 'active') # need to use listing fn, as this is immune to cache - result = openml.datasets.list_datasets(data_id=did, status='all') + result = openml.datasets.list_datasets(data_id=[did], status='all') self.assertEqual(len(result), 1) self.assertEqual(result[did]['status'], 'active') with self.assertRaises(ValueError): openml.datasets.status_update(did, 'in_preparation') # need to use listing fn, as this is immune to cache - result = openml.datasets.list_datasets(data_id=did, status='all') + result = openml.datasets.list_datasets(data_id=[did], status='all') self.assertEqual(len(result), 1) self.assertEqual(result[did]['status'], 'active') diff --git a/tests/test_study/test_study_functions.py b/tests/test_study/test_study_functions.py index 2c4574da3a..0194c5b0fb 100644 --- a/tests/test_study/test_study_functions.py +++ b/tests/test_study/test_study_functions.py @@ -117,15 +117,15 @@ def test_publish_benchmark_suite(self): def test_publish_study(self): # get some random runs to attach - run_list = openml.runs.list_runs(size=10) + run_list = openml.evaluations.list_evaluations('predictive_accuracy', size=10) self.assertEqual(len(run_list), 10) fixt_alias = None fixt_name = 'unit tested study' fixt_descr = 'bla' - fixt_flow_ids = set([run['flow_id'] for run in run_list.values()]) - fixt_task_ids = set([run['task_id'] for run in run_list.values()]) - fixt_setup_ids = set([run['setup_id']for run in run_list.values()]) + fixt_flow_ids = set([evaluation.flow_id for evaluation in run_list.values()]) + fixt_task_ids = set([evaluation.task_id for evaluation in run_list.values()]) + fixt_setup_ids = set([evaluation.setup_id for evaluation in run_list.values()]) study = openml.study.create_study( alias=fixt_alias, @@ -149,6 +149,14 @@ def test_publish_study(self): self.assertSetEqual(set(study_downloaded.flows), set(fixt_flow_ids)) self.assertSetEqual(set(study_downloaded.tasks), set(fixt_task_ids)) + # test whether the list run function also handles study data fine + run_ids = openml.runs.list_runs(study=study_id) + self.assertSetEqual(set(run_ids), set(study_downloaded.runs)) + + # test whether the list evaluation function also handles study data fine + run_ids = openml.evaluations.list_evaluations('predictive_accuracy', study=study_id) + self.assertSetEqual(set(run_ids), set(study_downloaded.runs)) + # attach more runs run_list_additional = openml.runs.list_runs(size=10, offset=10) openml.study.attach_to_study(study_id,