-
Notifications
You must be signed in to change notification settings - Fork 181
/
Copy pathevaluate_meta.py
392 lines (281 loc) · 12.5 KB
/
evaluate_meta.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
391
392
import argparse
import os
import numpy as np
import matplotlib.pyplot as plt
from dataset import read_csv_to_meta_dict, write_meta_dict_to_csv
def create_subset200_eval_csv(args):
r"""Select 200 files from 60,724 downloaded files to evaluate the precision,
recall of piano solo detection.
Args:
workspace: str
Returns:
None
"""
workspace = args.workspace
eval_num = 200
csv_path = os.path.join(workspace, 'full_music_pieces_youtube_similarity_pianosoloprob_split.csv')
output_path = os.path.join('subset_csvs_for_evaluation', 'subset200_eval.csv')
os.makedirs(os.path.dirname(output_path), exist_ok=True)
meta_dict = read_csv_to_meta_dict(csv_path)
audios_num = len(meta_dict['surname'])
indexes = []
for n in range(audios_num):
if float(meta_dict['similarity'][n]) > 0.6:
indexes.append(n)
skip_num = len(indexes) // eval_num
eval_indexes = indexes[0 : : skip_num][0 : eval_num]
new_meta_dict = {key: [] for key in meta_dict.keys()}
new_meta_dict['index_in_csv'] = []
for index in eval_indexes:
for key in meta_dict.keys():
new_meta_dict[key].append(meta_dict[key][index])
new_meta_dict['index_in_csv'].append(index)
new_meta_dict['piano_solo'] = [''] * eval_num
new_meta_dict['electronic_piano'] = [''] * eval_num
new_meta_dict['sequenced'] = [''] * eval_num
write_meta_dict_to_csv(new_meta_dict, output_path)
print('Write out to {}'.format(output_path))
def plot_piano_solo_p_r_f1(args):
r"""Plot piano solo detection precision, recall, and F1 score.
Args:
subset200_eval_with_labels_path: str
surname_in_youtube_title: bool
Returns:
None
"""
# arguments & paramteres
subset200_eval_with_labels_path = args.subset200_eval_with_labels_path
surname_in_youtube_title = args.surname_in_youtube_title
# paths
out_fig_path = os.path.join('results', 'piano_solo_p_r_f1.pdf')
meta_dict = read_csv_to_meta_dict(subset200_eval_with_labels_path)
audios_num = len(meta_dict['surname'])
precs = []
recalls = []
thresholds = []
f1s = []
for threshold in np.arange(0, 0.99, 0.1):
tp, fn, fp, tn = 0, 0, 0, 0
for n in range(audios_num):
if meta_dict['audio_name'][n] == '':
flag = False
else:
if surname_in_youtube_title and int(meta_dict['surname_in_youtube_title'][n]) == 0:
flag = False
else:
flag = True
if flag:
if float(meta_dict['piano_solo_prob'][n]) >= threshold:
pred = 1
else:
pred = 0
target = int(meta_dict['piano_solo'][n])
if target == 1 and pred == 1:
tp += 1
if target == 1 and pred == 0:
fn += 1
if target == 0 and pred == 1:
fp += 1
if target == 0 and pred == 0:
tn += 1
prec = tp / np.clip(tp + fp, 1e-8, np.inf)
recall = tp / np.clip(tp + fn, 1e-8, np.inf)
f1 = 2 * prec * recall / (prec + recall)
precs.append(prec)
recalls.append(recall)
thresholds.append(threshold)
f1s.append(f1)
if threshold == 0.5:
print('Threshold: {:.3f}, TP: {}, FN: {}, FP: {}, TN: {}'.format(threshold, tp, fn, fp, tn))
print('Total num: {}'.format(tp + fn + fp + tn))
print('Thresholds: {}'.format(thresholds))
print('Precisions: {}'.format(precs))
print('Recalls: {}'.format(recalls))
print('F1s: {}'.format(f1s))
N = len(thresholds)
fontsize = 14
fig, axs = plt.subplots(1, 1, sharex=True, figsize=(5, 3))
axs.scatter(np.arange(N), precs, color='blue')
axs.scatter(np.arange(N), recalls, color='green')
axs.scatter(np.arange(N), f1s, color='red')
line_p, = axs.plot(precs, label='Precision', linestyle='--', color='blue')
line_r, = axs.plot(recalls, label='Recall', linestyle='-.', color='green')
line_f1, = axs.plot(f1s, label='F1', linestyle='-', color='red')
axs.set_ylim(0., 1.02)
axs.set_xlabel(r"Thresholds", fontsize=fontsize)
axs.set_ylabel('Scores', fontsize=fontsize)
axs.legend(handles=[line_p, line_r, line_f1], loc=4)
axs.xaxis.set_ticks(np.arange(N))
axs.xaxis.set_ticklabels(['{:.2f}'.format(e) for e in thresholds], rotation=0)
plt.tight_layout(pad=0, h_pad=0, w_pad=0)
os.makedirs(os.path.dirname(out_fig_path), exist_ok=True)
plt.savefig(out_fig_path)
print('Write out to {}'.format(out_fig_path))
def create_subset200_piano_solo_eval_csv(args):
r"""Select 200 pieces from GiantMIDI-Piano to evaluate the music piece accuracy.
Args:
workspace: str
Returns:
None
"""
# arguments & parameters
workspace = args.workspace
eval_num = 200
# paths
csv_path = os.path.join(workspace, 'full_music_pieces_youtube_similarity_pianosoloprob_split.csv')
output_path = os.path.join('subset_csvs_for_evaluation', 'subset200_piano_solo_eval.csv')
os.makedirs(os.path.dirname(output_path), exist_ok=True)
meta_dict = read_csv_to_meta_dict(csv_path)
audios_num = len(meta_dict['surname'])
indexes = []
for n in range(audios_num):
if meta_dict['giant_midi_piano'][n] != '' and int(meta_dict['giant_midi_piano'][n]) == 1:
indexes.append(n)
skip_num = len(indexes) // eval_num
eval_indexes = indexes[0 : : skip_num][0 : eval_num]
new_meta_dict = {key: [] for key in meta_dict.keys()}
new_meta_dict['index_in_csv'] = []
for index in eval_indexes:
for key in meta_dict.keys():
new_meta_dict[key].append(meta_dict[key][index])
new_meta_dict['index_in_csv'].append(index)
new_meta_dict['meta_correct'] = [''] * eval_num
new_meta_dict['sequenced'] = [''] * eval_num
write_meta_dict_to_csv(new_meta_dict, output_path)
print('Write out to {}'.format(output_path))
def piano_solo_meta_accuracy(args):
r"""Calcualte piano piece accuracy from 200 files from GiantMIDI-Piano.
Args:
subset200_piano_solo_eval_with_labels_path: str
youtube_title_contain_surname: bool
Returns:
None
"""
# arguments & parameters
subset200_piano_solo_eval_with_labels_path = args.subset200_piano_solo_eval_with_labels_path
surname_in_youtube_title = args.surname_in_youtube_title
meta_dict = read_csv_to_meta_dict(subset200_piano_solo_eval_with_labels_path)
audios_num = len(meta_dict['surname'])
tp, fp = 0, 0
for n in range(audios_num):
if meta_dict['audio_name'][n] == '':
flag = False
else:
if surname_in_youtube_title and int(meta_dict['surname_in_youtube_title'][n]) == 0:
flag = False
else:
flag = True
if flag:
if int(meta_dict['meta_correct'][n]) == 1:
tp += 1
else:
fp += 1
precision = tp / (tp + fp)
print('Correct rate: {} / {}, {}'.format(tp, tp + fp, precision))
def piano_solo_performed_ratio(args):
r"""Calcualte piano piece accuracy from 200 files from GiantMIDI-Piano.
Args:
subset200_piano_solo_eval_with_labels_path: str
youtube_title_contain_surname: bool
Returns:
None
"""
# arguments & parameters
subset200_piano_solo_eval_with_labels_path = args.subset200_piano_solo_eval_with_labels_path
surname_in_youtube_title = args.surname_in_youtube_title
meta_dict = read_csv_to_meta_dict(subset200_piano_solo_eval_with_labels_path)
audios_num = len(meta_dict['surname'])
tp, fp = 0, 0
for n in range(audios_num):
if meta_dict['audio_name'][n] == '':
flag = False
else:
if surname_in_youtube_title and int(meta_dict['surname_in_youtube_title'][n]) == 0:
flag = False
else:
flag = True
if flag:
if int(meta_dict['sequenced'][n]) == 1:
tp += 1
else:
fp += 1
sequenced_ratio = tp / (tp + fp)
print('Performance ratio: {:.3f}'.format(1. - sequenced_ratio))
def individual_composer_piano_solo_meta_accuracy(args):
"""Calcualte individual composer piano solo meta accuracy. Composers include:
Bach, Johann Sebastian
Mozart, Wolfgang Amadeus
Beethoven, Ludwig van
Chopin, Frédéric
Liszt, Franz
Debussy, Claude
Args:
workspace: str
surname: str
firstname: str
surname_in_youtube_title: bool
Returns:
None
"""
workspace = args.workspace
surname = args.surname
firstname = args.firstname
surname_in_youtube_title = args.surname_in_youtube_title
eval_num = 200
csv_path = os.path.join(workspace, 'full_music_pieces_youtube_similarity_pianosoloprob_split.csv')
meta_dict = read_csv_to_meta_dict(csv_path)
audios_num = len(meta_dict['surname'])
indexes = []
tp, fp = 0, 0
for n in range(audios_num):
if meta_dict['giant_midi_piano'][n] != '' and int(meta_dict['giant_midi_piano'][n]) == 1:
match_composer = (surname == meta_dict['surname'][n] and firstname == meta_dict['firstname'][n])
if surname_in_youtube_title and int(meta_dict['surname_in_youtube_title'][n]) == 0:
flag = False
else:
flag = True
if flag:
if surname in meta_dict['youtube_title'][n] or match_composer:
if match_composer:
tp += 1
else:
fp += 1
accuracy = tp / (tp + fp)
print('Match: {}, Accuracy: {}'.format(tp, fp))
print('Accuracy: {:.3f}'.format(accuracy))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Example of parser. ')
subparsers = parser.add_subparsers(dest='mode')
parser_create_subset200_eval_csv = subparsers.add_parser('create_subset200_eval_csv')
parser_create_subset200_eval_csv.add_argument('--workspace', type=str, required=True)
parser_plot_piano_solo_p_r_f1 = subparsers.add_parser('plot_piano_solo_p_r_f1')
parser_plot_piano_solo_p_r_f1.add_argument('--subset200_eval_with_labels_path', type=str, required=True)
parser_plot_piano_solo_p_r_f1.add_argument('--surname_in_youtube_title', action='store_true', default=False)
parser_create_subset200_piano_solo_eval_csv = subparsers.add_parser('create_subset200_piano_solo_eval_csv')
parser_create_subset200_piano_solo_eval_csv.add_argument('--workspace', type=str, required=True)
parser_piano_solo_meta_accuracy = subparsers.add_parser('piano_solo_meta_accuracy')
parser_piano_solo_meta_accuracy.add_argument('--subset200_piano_solo_eval_with_labels_path', type=str, required=True)
parser_piano_solo_meta_accuracy.add_argument('--surname_in_youtube_title', action='store_true', default=False)
parser_piano_solo_performed_ratio = subparsers.add_parser('piano_solo_performed_ratio')
parser_piano_solo_performed_ratio.add_argument('--subset200_piano_solo_eval_with_labels_path', type=str, required=True)
parser_piano_solo_performed_ratio.add_argument('--surname_in_youtube_title', action='store_true', default=False)
parser_individual_composer_piano_solo_meta_accuracy = subparsers.add_parser('individual_composer_piano_solo_meta_accuracy')
parser_individual_composer_piano_solo_meta_accuracy.add_argument('--workspace', type=str, required=True)
parser_individual_composer_piano_solo_meta_accuracy.add_argument('--surname', type=str, required=True)
parser_individual_composer_piano_solo_meta_accuracy.add_argument('--firstname', type=str, required=True)
parser_individual_composer_piano_solo_meta_accuracy.add_argument('--surname_in_youtube_title', action='store_true', default=False)
args = parser.parse_args()
if args.mode == 'create_subset200_eval_csv':
create_subset200_eval_csv(args)
elif args.mode == 'plot_piano_solo_p_r_f1':
plot_piano_solo_p_r_f1(args)
elif args.mode == 'create_subset200_piano_solo_eval_csv':
create_subset200_piano_solo_eval_csv(args)
elif args.mode == 'piano_solo_meta_accuracy':
piano_solo_meta_accuracy(args)
elif args.mode == 'piano_solo_performed_ratio':
piano_solo_performed_ratio(args)
elif args.mode == 'individual_composer_piano_solo_meta_accuracy':
individual_composer_piano_solo_meta_accuracy(args)
else:
raise Exception('Incorrect argument!')