-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
390 lines (310 loc) · 9.71 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import dcase_util
import sys
import os
import argparse
import textwrap
def handle_application_arguments(param, application_title='', version=''):
"""Handle application arguments
Parameters
----------
param : dcase_util.containers.DCASEAppParameterContainer
Application parameters
application_title : str
Application title
Default value ''
version : str
Application version
Default value ''
Returns
-------
nothing
"""
parser = argparse.ArgumentParser(
prefix_chars='-+',
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent(
'''\
DCASE 2018
{app_title}
Baseline system
---------------------------------------------
Author: Toni Heittola ( [email protected] )
Tampere University of Technology / Audio Research Group
'''.format(app_title=application_title)
)
)
# Setup argument handling
parser.add_argument(
'-m', '--mode',
choices=('dev', 'eval', 'leaderboard'),
default=None,
help="Selector for application operation mode",
required=False,
dest='mode',
type=str
)
# Application parameter modification
parser.add_argument(
'-s', '--parameter_set',
help='Parameter set id, can be comma separated list',
dest='parameter_set',
required=False,
type=str
)
parser.add_argument(
'-p', '--param_file',
help='Parameter file override',
dest='parameter_override',
required=False,
metavar='FILE',
type=dcase_util.utils.argument_file_exists
)
# Specific actions
parser.add_argument(
'--overwrite',
help='Overwrite mode',
dest='overwrite',
action='store_true',
required=False
)
parser.add_argument(
'--download_dataset',
help='Download dataset to given path and exit',
dest='dataset_path',
required=False,
type=str
)
# Output
parser.add_argument(
'-o', '--output',
help='Output file',
dest='output_file',
required=False,
type=str
)
# Show information
parser.add_argument(
'--show_parameters',
help='Show active application parameter set',
dest='show_parameters',
action='store_true',
required=False
)
parser.add_argument(
'--show_sets',
help='List of available parameter sets',
dest='show_set_list',
action='store_true',
required=False
)
parser.add_argument(
'--show_results',
help='Show results of the evaluated system setups',
dest='show_results',
action='store_true',
required=False
)
# Application information
parser.add_argument(
'-v', '--version',
help='Show version number and exit',
action='version',
version='%(prog)s ' + version
)
# Parse arguments
args = parser.parse_args()
if args.parameter_override:
# Override parameters from a file
param.override(override=args.parameter_override)
if args.overwrite:
# Inject overwrite into parameters
param['general']['overwrite'] = True
if args.show_parameters:
# Process parameters, and clean up parameters a bit for showing
param_ = dcase_util.containers.AppParameterContainer(param).process(
create_paths=False,
create_parameter_hints=False
)
del param_['sets']
del param_['defaults']
for section in param_:
if section.endswith('_method_parameters'):
param_[section] = {}
param_.log()
sys.exit(0)
if args.dataset_path:
# Make sure given path exists
dcase_util.utils.Path().create(
paths=args.dataset_path
)
# Get dataset and initialize
dcase_util.datasets.dataset_factory(
dataset_class_name=param.get_path('dataset.parameters.dataset'),
data_path=args.dataset_path,
).initialize().log()
sys.exit(0)
return args
def save_system_output(db, folds, param, log, output_file, mode='dcase'):
"""Save system output
Parameters
----------
db : dcase_util.dataset.Dataset
Dataset
folds : list
List of active folds
param : dcase_util.containers.DCASEAppParameterContainer
Application parameters
log : dcase_util.ui.FancyLogger
Logging interface
output_file : str
mode : str
Output mode, possible values ['dcase', 'leaderboard']
Default value 'dcase'
Returns
-------
nothing
"""
# Initialize results container
all_res = dcase_util.containers.MetaDataContainer(
filename=output_file
)
# Loop over all cross-validation folds and collect results
for fold in folds:
# Get results filename
fold_results_filename = os.path.join(
param.get_path('path.application.recognizer'),
'res_fold_{fold}.txt'.format(fold=fold)
)
if os.path.isfile(fold_results_filename):
# Load results container
res = dcase_util.containers.MetaDataContainer().load(
filename=fold_results_filename
)
all_res += res
else:
raise ValueError(
'Results output file does not exists [{fold_results_filename}]'.format(
fold_results_filename=fold_results_filename
)
)
# Convert paths to relative to the dataset root
for item in all_res:
item.filename = db.absolute_to_relative_path(item.filename)
if mode == 'leaderboard':
item['Id'] = os.path.splitext(os.path.split(item.filename)[-1])[0]
item['Scene_label'] = item.scene_label
if mode == 'leaderboard':
all_res.save(fields=['Id', 'Scene_label'], delimiter=',')
else:
all_res.save(csv_header=False)
log.line('System output saved to [{output_file}]'.format(output_file=output_file), indent=2)
log.line()
def show_general_information(parameter_set, active_folds, param, db, log):
"""Show application general information
Parameters
----------
parameter_set : str
Dataset
active_folds : list
List of active folds
param : dcase_util.containers.DCASEAppParameterContainer
Application parameters
db : dcase_util.dataset.Dataset
Dataset
log : dcase_util.ui.FancyLogger
Logging interface
Returns
-------
nothing
"""
log.section_header('General information')
log.line('Parameter set', indent=2)
log.data(field='Set ID', value=parameter_set, indent=4)
log.data(field='Set description', value=param.get('description'), indent=4)
log.line('Application', indent=2)
log.data(field='Overwrite', value=param.get_path('general.overwrite'), indent=4)
log.data(field='Dataset', value=db.storage_name, indent=4)
log.data(field='Active folds', value=active_folds, indent=4)
log.line()
log.foot()
def show_results(param, log):
"""Show system evaluation results
Parameters
----------
param : dcase_util.containers.DCASEAppParameterContainer
Application parameters
log : dcase_util.ui.FancyLogger
Logging interface
Returns
-------
nothing
"""
eval_path = param.get_path('path.application.evaluator')
eval_files = dcase_util.utils.Path().file_list(path=eval_path, extensions='yaml')
eval_data = {}
for filename in eval_files:
data = dcase_util.containers.DictContainer().load(filename=filename)
set_id = data.get_path('parameters.set_id')
if set_id not in eval_data:
eval_data[set_id] = {}
params_hash = data.get_path('parameters._hash')
if params_hash not in eval_data[set_id]:
eval_data[set_id][params_hash] = data
log.section_header('Evaluated systems')
log.line()
log.row_reset()
log.row(
'Set ID', 'Mode', 'Accuracy', 'Description', 'Parameter hash',
widths=[25, 10, 11, 45, 35],
separators=[False, True, True, True, True],
types=['str25', 'str10', 'float1_percentage', 'str', 'str']
)
log.row_sep()
for set_id in sorted(list(eval_data.keys())):
for params_hash in eval_data[set_id]:
data = eval_data[set_id][params_hash]
desc = data.get_path('parameters.description')
application_mode = data.get_path('application_mode', '')
log.row(
set_id,
application_mode,
data.get_path('overall_accuracy') * 100.0,
desc,
params_hash
)
log.line()
sys.exit(0)
def show_parameter_sets(param, log):
"""Show available parameter sets
Parameters
----------
param : dcase_util.containers.DCASEAppParameterContainer
Application parameters
log : dcase_util.ui.FancyLogger
Logging interface
Returns
-------
nothing
"""
log.section_header('Parameter sets')
log.line()
log.row_reset()
log.row(
'Set ID', 'Description',
widths=[20, 70],
separators=[True, False],
)
log.row_sep()
for set_id in param.set_ids():
current_parameter_set = param.get_set(set_id=set_id)
if current_parameter_set:
desc = current_parameter_set.get('description', '')
else:
desc = ''
log.row(
set_id,
desc
)
log.line()