Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 36 additions & 19 deletions openml/runs/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import io
import json
import os
import shutil
import sys
import time
import warnings
Expand All @@ -16,7 +15,7 @@
import openml
import openml.utils
import openml._api_calls
from ..exceptions import PyOpenMLError, OpenMLServerNoResult
from ..exceptions import PyOpenMLError
from .. import config
from ..flows import sklearn_to_flow, get_flow, flow_exists, _check_n_jobs, \
_copy_server_fields, OpenMLFlow
Expand Down Expand Up @@ -405,11 +404,11 @@ def _prediction_to_probabilities(y, model_classes):
# this information is multiple times overwritten, but due to the ordering
# of tne loops, eventually it contains the information based on the full
# dataset size
user_defined_measures_per_fold = collections.defaultdict(lambda: collections.defaultdict(dict))
user_defined_measures_per_fold = collections.OrderedDict()
# stores sample-based evaluation measures (sublevel of fold-based)
# will also be filled on a non sample-based task, but the information
# is the same as the fold-based measures, and disregarded in that case
user_defined_measures_per_sample = collections.defaultdict(lambda: collections.defaultdict(lambda: collections.defaultdict(dict)))
user_defined_measures_per_sample = collections.OrderedDict()

# sys.version_info returns a tuple, the following line compares the entry of tuples
# https://docs.python.org/3.6/reference/expressions.html#value-comparisons
Expand All @@ -431,6 +430,19 @@ def _prediction_to_probabilities(y, model_classes):
arff_tracecontent.extend(arff_tracecontent_fold)

for measure in user_defined_measures_fold:

if measure not in user_defined_measures_per_fold:
user_defined_measures_per_fold[measure] = collections.OrderedDict()
if rep_no not in user_defined_measures_per_fold[measure]:
user_defined_measures_per_fold[measure][rep_no] = collections.OrderedDict()

if measure not in user_defined_measures_per_sample:
user_defined_measures_per_sample[measure] = collections.OrderedDict()
if rep_no not in user_defined_measures_per_sample[measure]:
user_defined_measures_per_sample[measure][rep_no] = collections.OrderedDict()
if fold_no not in user_defined_measures_per_sample[measure][rep_no]:
user_defined_measures_per_sample[measure][rep_no][fold_no] = collections.OrderedDict()

user_defined_measures_per_fold[measure][rep_no][fold_no] = user_defined_measures_fold[measure]
user_defined_measures_per_sample[measure][rep_no][fold_no][sample_no] = user_defined_measures_fold[measure]

Expand Down Expand Up @@ -515,7 +527,7 @@ def _prediction_to_probabilities(y, model_classes):
trainY = Y[train_indices]
testX = X[test_indices]
testY = Y[test_indices]
user_defined_measures = dict()
user_defined_measures = collections.OrderedDict()

try:
# for measuring runtime. Only available since Python 3.3
Expand Down Expand Up @@ -752,10 +764,10 @@ def obtain_field(xml_obj, fieldname, from_server, cast=None):
elif not from_server:
dataset_id = None

files = dict()
evaluations = dict()
fold_evaluations = collections.defaultdict(lambda: collections.defaultdict(dict))
sample_evaluations = collections.defaultdict(lambda: collections.defaultdict(lambda: collections.defaultdict(dict)))
files = collections.OrderedDict()
evaluations = collections.OrderedDict()
fold_evaluations = collections.OrderedDict()
sample_evaluations = collections.OrderedDict()
if 'oml:output_data' not in run:
if from_server:
raise ValueError('Run does not contain output_data (OpenML server error?)')
Expand All @@ -781,16 +793,21 @@ def obtain_field(xml_obj, fieldname, from_server, cast=None):
repeat = int(evaluation_dict['@repeat'])
fold = int(evaluation_dict['@fold'])
sample = int(evaluation_dict['@sample'])
repeat_dict = sample_evaluations[key]
fold_dict = repeat_dict[repeat]
sample_dict = fold_dict[fold]
sample_dict[sample] = value
if key not in sample_evaluations:
sample_evaluations[key] = collections.OrderedDict()
if repeat not in sample_evaluations[key]:
sample_evaluations[key][repeat] = collections.OrderedDict()
if fold not in sample_evaluations[key][repeat]:
sample_evaluations[key][repeat][fold] = collections.OrderedDict()
sample_evaluations[key][repeat][fold][sample] = value
elif '@repeat' in evaluation_dict and '@fold' in evaluation_dict:
repeat = int(evaluation_dict['@repeat'])
fold = int(evaluation_dict['@fold'])
repeat_dict = fold_evaluations[key]
fold_dict = repeat_dict[repeat]
fold_dict[fold] = value
if key not in fold_evaluations:
fold_evaluations[key] = collections.OrderedDict()
if repeat not in fold_evaluations[key]:
fold_evaluations[key][repeat] = collections.OrderedDict()
fold_evaluations[key][repeat][fold] = value
else:
evaluations[key] = value

Expand Down Expand Up @@ -832,7 +849,7 @@ def _create_trace_from_description(xml):
result_dict = xmltodict.parse(xml, force_list=('oml:trace_iteration',))['oml:trace']

run_id = result_dict['oml:run_id']
trace = dict()
trace = collections.OrderedDict()

if 'oml:trace_iteration' not in result_dict:
raise ValueError('Run does not contain valid trace. ')
Expand Down Expand Up @@ -878,7 +895,7 @@ def _create_trace_from_arff(arff_obj):
run : OpenMLRunTrace
Object containing None for run id and a dict containing the trace iterations
"""
trace = dict()
trace = collections.OrderedDict()
attribute_idx = {att[0]: idx for idx, att in enumerate(arff_obj['attributes'])}
for required_attribute in ['repeat', 'fold', 'iteration', 'evaluation', 'selected']:
if required_attribute not in attribute_idx:
Expand Down Expand Up @@ -1045,7 +1062,7 @@ def __list_runs(api_call):
assert type(runs_dict['oml:runs']['oml:run']) == list, \
type(runs_dict['oml:runs'])

runs = dict()
runs = collections.OrderedDict()
for run_ in runs_dict['oml:runs']['oml:run']:
run_id = int(run_['oml:run_id'])
run = {'run_id': run_id,
Expand Down
27 changes: 14 additions & 13 deletions openml/runs/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,8 @@ def from_filesystem(cls, folder):
raise ValueError('Could not find model.pkl')

with open(description_path, 'r') as fp:
run = openml.runs.functions._create_run_from_xml(fp.read(), from_server=False)
xml_string = fp.read()
run = openml.runs.functions._create_run_from_xml(xml_string, from_server=False)

with open(predictions_path, 'r') as fp:
predictions = arff.load(fp)
Expand All @@ -111,10 +112,10 @@ def from_filesystem(cls, folder):
run.model = pickle.load(fp)

if os.path.isfile(trace_path):
with open(trace_path, 'r') as fp:
trace = arff.load(fp)
run.trace_attributes = trace['attributes']
run.trace_content = trace['data']
trace_arff = openml.runs.OpenMLRunTrace._from_filesystem(trace_path)

run.trace_attributes = trace_arff['attributes']
run.trace_content = trace_arff['data']

return run

Expand Down Expand Up @@ -177,7 +178,7 @@ def _generate_arff_dict(self):
task = get_task(self.task_id)
class_labels = task.class_labels

arff_dict = {}
arff_dict = OrderedDict()
arff_dict['attributes'] = [('repeat', 'NUMERIC'), # lowercase 'numeric' gives an error
('fold', 'NUMERIC'),
('sample', 'NUMERIC'),
Expand Down Expand Up @@ -206,7 +207,7 @@ def _generate_trace_arff_dict(self):
if len(self.trace_attributes) != len(self.trace_content[0]):
raise ValueError('Trace_attributes and trace_content not compatible')

arff_dict = dict()
arff_dict = OrderedDict()
arff_dict['attributes'] = self.trace_attributes
arff_dict['data'] = self.trace_content
arff_dict['relation'] = 'openml_task_' + str(self.task_id) + '_predictions'
Expand Down Expand Up @@ -252,7 +253,7 @@ def _attribute_list_to_dict(attribute_list):
# convenience function: Creates a mapping to map from the name of attributes
# present in the arff prediction file to their index. This is necessary
# because the number of classes can be different for different tasks.
res = dict()
res = OrderedDict()
for idx in range(len(attribute_list)):
res[attribute_list[idx][0]] = idx
return res
Expand Down Expand Up @@ -282,11 +283,11 @@ def _attribute_list_to_dict(attribute_list):
prediction = predictions_arff['attributes'][predicted_idx][1].index(line[predicted_idx])
correct = predictions_arff['attributes'][predicted_idx][1].index(line[correct_idx])
if rep not in values_predict:
values_predict[rep] = dict()
values_correct[rep] = dict()
values_predict[rep] = OrderedDict()
values_correct[rep] = OrderedDict()
if fold not in values_predict[rep]:
values_predict[rep][fold] = dict()
values_correct[rep][fold] = dict()
values_predict[rep][fold] = OrderedDict()
values_correct[rep][fold] = OrderedDict()
if samp not in values_predict[rep][fold]:
values_predict[rep][fold][samp] = []
values_correct[rep][fold][samp] = []
Expand Down Expand Up @@ -542,7 +543,7 @@ def _to_dict(taskid, flow_id, setup_string, error_message, parameter_settings,
description['oml:run']['oml:tag'] = tags # Tags describing the run
if (fold_evaluations is not None and len(fold_evaluations) > 0) or \
(sample_evaluations is not None and len(sample_evaluations) > 0):
description['oml:run']['oml:output_data'] = dict()
description['oml:run']['oml:output_data'] = OrderedDict()
description['oml:run']['oml:output_data']['oml:evaluation'] = list()
if fold_evaluations is not None:
for measure in fold_evaluations:
Expand Down
59 changes: 52 additions & 7 deletions openml/runs/trace.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import arff
import json
import os


class OpenMLRunTrace(object):
"""OpenML Run Trace: parsed output from Run Trace call
Expand All @@ -19,18 +22,60 @@ def __init__(self, run_id, trace_iterations):
self.trace_iterations = trace_iterations

def get_selected_iteration(self, fold, repeat):
'''
"""
Returns the trace iteration that was marked as selected. In
case multiple are marked as selected (should not happen) the
first of these is returned
'''

Parameters
----------
fold: int

repeat: int

Returns
----------
OpenMLTraceIteration
The trace iteration from the given fold and repeat that was
selected as the best iteration by the search procedure
"""
for (r, f, i) in self.trace_iterations:
if r == repeat and f == fold and self.trace_iterations[(r, f, i)].selected is True:
return i
raise ValueError('Could not find the selected iteration for rep/fold %d/%d' %(repeat,fold))
raise ValueError('Could not find the selected iteration for rep/fold %d/%d' % (repeat, fold))

@staticmethod
def _from_filesystem(file_path):
"""
Logic to deserialize the trace from the filesystem

Parameters
----------
file_path: str
File path where the trace is stored

Returns
----------
trace: dict
a dict in the liac-arff style that contains trace information
"""
if not os.path.isfile(file_path):
raise ValueError('Trace file doesn\'t exist')

with open(file_path, 'r') as fp:
trace = arff.load(fp)

# TODO probably we want to integrate the trace object with the run object, rather than the current
# situation (which stores the arff)
for trace_idx in range(len(trace['data'])):
# iterate over first three entrees of a trace row (fold, repeat, trace_iteration) these should be int
for line_idx in range(3):
value = trace['data'][trace_idx][line_idx]
trace['data'][trace_idx][line_idx] = int(trace['data'][trace_idx][line_idx])
return trace

def __str__(self):
return '[Run id: %d, %d trace iterations]' %(self.run_id, len(self.trace_iterations))
return '[Run id: %d, %d trace iterations]' % (self.run_id, len(self.trace_iterations))


class OpenMLTraceIteration(object):
Expand Down Expand Up @@ -79,9 +124,9 @@ def get_parameters(self):
return result

def __str__(self):
'''
"""
tmp string representation, will be changed in the near future
'''
"""
return '[(%d,%d,%d): %f (%r)]' %(self.repeat, self.fold, self.iteration,
self.evaluation, self.selected)
self.evaluation, self.selected)

2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
'mock',
'numpy>=1.6.2',
'scipy>=0.13.3',
'liac-arff>=2.2.1',
'liac-arff>=2.2.2',
'xmltodict',
'nose',
'requests',
Expand Down
46 changes: 39 additions & 7 deletions tests/test_runs/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV, StratifiedKFold
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import Imputer

from openml.testing import TestBase
from openml.flows.sklearn_converter import sklearn_to_flow
Expand Down Expand Up @@ -91,18 +93,38 @@ def _test_run_obj_equals(self, run, run_prime):
np.testing.assert_array_equal(string_part, string_part_prime)

if run.trace_content is not None:
numeric_part = np.array(np.array(run.trace_content)[:, 0:-2], dtype=float)
numeric_part_prime = np.array(np.array(run_prime.trace_content)[:, 0:-2], dtype=float)
string_part = np.array(run.trace_content)[:, -2:]
string_part_prime = np.array(run_prime.trace_content)[:, -2:]
def _check_array(array, type_):
for line in array:
for entry in line:
self.assertIsInstance(entry, type_)

int_part = [line[:3] for line in run.trace_content]
_check_array(int_part, int)
int_part_prime = [line[:3] for line in run_prime.trace_content]
_check_array(int_part_prime, int)

float_part = np.array(np.array(run.trace_content)[:, 3:4], dtype=float)
float_part_prime = np.array(np.array(run_prime.trace_content)[:, 3:4], dtype=float)
bool_part = [line[4] for line in run.trace_content]
bool_part_prime = [line[4] for line in run_prime.trace_content]
for bp, bpp in zip(bool_part, bool_part_prime):
self.assertIn(bp, ['true', 'false'])
self.assertIn(bpp, ['true', 'false'])
string_part = np.array(run.trace_content)[:, 5:]
string_part_prime = np.array(run_prime.trace_content)[:, 5:]
# JvR: Python 2.7 requires an almost equal check, rather than an equals check
np.testing.assert_array_almost_equal(numeric_part, numeric_part_prime)
np.testing.assert_array_almost_equal(int_part, int_part_prime)
np.testing.assert_array_almost_equal(float_part, float_part_prime)
self.assertEqual(bool_part, bool_part_prime)
np.testing.assert_array_equal(string_part, string_part_prime)
else:
self.assertIsNone(run_prime.trace_content)

def test_to_from_filesystem_vanilla(self):
model = DecisionTreeClassifier(max_depth=1)
model = Pipeline([
('imputer', Imputer(strategy='mean')),
('classifier', DecisionTreeClassifier(max_depth=1)),
])
task = openml.tasks.get_task(119)
run = openml.runs.run_model_on_task(task, model, add_local_measures=False)

Expand All @@ -114,7 +136,17 @@ def test_to_from_filesystem_vanilla(self):
run_prime.publish()

def test_to_from_filesystem_search(self):
model = GridSearchCV(estimator=DecisionTreeClassifier(), param_grid={"max_depth": [1, 2, 3, 4, 5]})
model = Pipeline([
('imputer', Imputer(strategy='mean')),
('classifier', DecisionTreeClassifier(max_depth=1)),
])
model = GridSearchCV(
estimator=model,
param_grid={
"classifier__max_depth": [1, 2, 3, 4, 5],
"imputer__strategy": ['mean', 'median'],
}
)

task = openml.tasks.get_task(119)
run = openml.runs.run_model_on_task(task, model, add_local_measures=False)
Expand Down