-
Notifications
You must be signed in to change notification settings - Fork 17
/
vae_evaluation.py
2910 lines (2264 loc) · 146 KB
/
vae_evaluation.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ----------------------------------------------------------------------------------------------
# Import dependencies
# ----------------------------------------------------------------------------------------------
from settings import *
import sys
import math
from random import shuffle
import progressbar
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib.patches as mpatches
import os
import numpy as np
import _pickle as pickle
import time
import csv
from collections import defaultdict
from keras.models import load_model, model_from_yaml
from keras.utils import to_categorical
from sklearn.utils import class_weight
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from matplotlib2tikz import save as tikz_save
import pretty_midi as pm
import scipy
import midi_functions as mf
import vae_definition
from vae_definition import VAE
from vae_definition import KLDivergenceLayer
import data_class
from import_midi import import_midi_from_folder
# ----------------------------------------------------------------------------------------------
# Set schedule for the evaluation
# ----------------------------------------------------------------------------------------------
harmonicity_evaluations = False
frankenstein_harmonicity_evaluations = False # runs only if harmonicity_evaluations are turned on
max_new_chosen_interpolation_songs = 42
interpolation_length = 4 #how many iterations?
how_many_songs_in_one_medley = 3
noninterpolated_samples_between_interpolation = 8 #should be at least 1, otherwise it can not interpolate
max_new_sampled_interpolation_songs = 42
interpolation_song_length = 10 #how many iterations?
latent_sweep = True
num_latent_sweep_samples = 100
num_latent_sweep_evaluation_songs = 10
chord_evaluation = True
evaluate_different_sampling_regions = True
pitch_evaluation = True
max_new_sampled_songs = 100
max_new_sampled_long_songs = 100
evaluate_autoencoding_and_stuff = True
mix_with_previous = True
switch_styles = True
# ----------------------------------------------------------------------------------------------
# Model library (Change those strings to use it)
# ----------------------------------------------------------------------------------------------
model_name = 'your_model_name/'
epoch = 410
pitches_classifier_model_path = './models/clustering/-/'
pitches_classifier_model_name = 'modelEpoch?.pickle'
pitches_classifier_model = load_model(pitches_classifier_model_path+pitches_classifier_model_name)
pitches_classifier_model_weight = 0.999 - 0.5 #subtract 0.5 since you would want to weight a random model with 0
velocity_classifier_model_path = './models/velocityclustering/1521669531-num_layers_2_maxlen_64_otns_False_lstmsize_256_trainsize_909_testsize_104_thresh_0.5_scale_False/'
velocity_classifier_model_name = 'modelEpoch?.pickle'
velocity_classifier_model = load_model(velocity_classifier_model_path+velocity_classifier_model_name)
velocity_classifier_model_weight = 0.999 - 0.5
instrument_classifier_model_path = './models/instrumentclustering/-/'
instrument_classifier_model_name = 'modelEpoch?.pickle'
instrument_classifier_model = load_model(instrument_classifier_model_path+instrument_classifier_model_name)
instrument_classifier_model_weight = 0.999 - 0.5
if test_train_set:
set_string = 'train/'
else:
set_string = 'test/'
model_path = 'models/autoencode/vae/' + model_name
save_folder = 'autoencode_midi/vae/' + model_name[:10] + '/' + set_string
if not os.path.exists(save_folder):
os.makedirs(save_folder)
def ensemble_prediction(Y,I,V):
pitch_prediction = pitches_classifier_model.predict(Y)
instrument_prediction = instrument_classifier_model.predict(I)
velocity_prediction = velocity_classifier_model.predict(V)
weighted_prediction = (pitch_prediction * pitches_classifier_model_weight + instrument_prediction * instrument_classifier_model_weight + velocity_prediction * velocity_classifier_model_weight) / (pitches_classifier_model_weight + instrument_classifier_model_weight + velocity_classifier_model_weight)
return weighted_prediction
# ----------------------------------------------------------------------------------------------
# Evaluation settings
# ----------------------------------------------------------------------------------------------
model_filetype = '.pickle'
max_plots_per_song = 3
BPM = 100
shuffle = False
composer_decoder_latent_size = 10
assert(output_length > 0)
verbose = False
sample_method = 'argmax' #choice, argmax
# ----------------------------------------------------------------------------------------------
# Import and preprocess data
# ----------------------------------------------------------------------------------------------
print('loading data...')
# Get Train and test sets
if rolls:
folder = source_folder
else:
folder = roll_folder
V_train, V_test, D_train, D_test, T_train, T_test, I_train, I_test, Y_train, Y_test, X_train, X_test, C_train, C_test, train_paths, test_paths = import_midi_from_folder(folder)
train_set_size = len(X_train)
test_set_size = len(X_test)
print(len(train_paths))
print(len(test_paths))
print(C_test)
# ----------------------------------------------------------------------------------------------
# Simple statistics on train and test set
# ----------------------------------------------------------------------------------------------
total_train_songs_per_class = [0 for _ in range(num_classes)]
total_train_samples_per_class = [0 for _ in range(num_classes)]
total_test_songs_per_class = [0 for _ in range(num_classes)]
total_test_samples_per_class = [0 for _ in range(num_classes)]
for i, C in enumerate(C_train):
total_train_songs_per_class[C] += 1
total_train_samples_per_class[C] += X_train[i].shape[0]
for i, C in enumerate(C_test):
total_test_songs_per_class[C] += 1
total_test_samples_per_class[C] += X_test[i].shape[0]
print("Total train songs per class: ", total_train_songs_per_class)
print("Total train samples per class: ", total_train_samples_per_class)
print("Total test songs per class: ", total_test_songs_per_class)
print("Total test samples per class: ", total_test_samples_per_class)
print("Classes", classes)
print("Model name", model_name)
print("Test on train set", test_train_set)
input("Correct settings?")
# ----------------------------------------------------------------------------------------------
# Harmonicity statistics
# ----------------------------------------------------------------------------------------------
if harmonicity_evaluations:
if frankenstein_harmonicity_evaluations:
def spm_based_on_random_pitches(total_evaluations=1000):
spms = np.zeros((total_evaluations, max_voices, max_voices))
for i in range(total_evaluations):
bar = np.zeros((1,output_length, new_num_notes))
notes_per_step_maximum = 5
#fill bar with random notes
for step in range(output_length):
for _ in range(notes_per_step_maximum):
#silent every third time on average
silent = np.random.randint(3) == 0
if not silent:
pitch = np.random.randint(new_num_notes)
bar[0, step, pitch] = 1
score_pair_matrix = data_class.get_harmonicity_scores_for_each_track_combination(bar)
spms[i] = score_pair_matrix
return np.nanmean(spms, axis=0)
spm = spm_based_on_random_pitches()
print("Harmonicity score based on random pitches :\n", spm)
def frankenstein_spm_based_on_Y_list(Y_list, total_evaluations=1000):
num_songs = len(Y_list)
spms = np.zeros((total_evaluations, max_voices, max_voices))
for i in range(total_evaluations):
#pick max_voices different songs
song_choices = np.random.choice(num_songs, max_voices, replace=False)
frankenstein_bar = np.zeros((1, output_length, new_num_notes))
for voice, song_choice in enumerate(song_choices):
Y = Y_list[song_choice]
#pick a random bar
num_bars = Y.shape[0]
bar_choice = np.random.randint(num_bars)
picked_bar = np.copy(Y[bar_choice])
if include_silent_note:
picked_bar = picked_bar[:, :-1]
#fill the frankenstein_bar
frankenstein_bar[0, voice::max_voices, :] = picked_bar[0::max_voices,:]
score_pair_matrix = data_class.get_harmonicity_scores_for_each_track_combination(frankenstein_bar)
spms[i] = score_pair_matrix
return np.nanmean(spms, axis=0)
for C in range(num_classes):
indices = [i for i, x in enumerate(C_train) if x == C]
Y_train_for_this_class = np.copy([Y_train[i] for i in indices])
spm = frankenstein_spm_based_on_Y_list(Y_train_for_this_class)
print("Frankenstein train spm for class " + classes[C] + ":\n", spm)
indices = [i for i, x in enumerate(C_test) if x == C]
Y_test_for_this_class = np.copy([Y_test[i] for i in indices])
spm = frankenstein_spm_based_on_Y_list(Y_test_for_this_class)
print("Frankenstein test spm for class " + classes[C] + ":\n", spm)
spm = frankenstein_spm_based_on_Y_list(Y_train)
print("Frankenstein train spm for whole set :\n", spm)
spm = frankenstein_spm_based_on_Y_list(Y_test)
print("Frankenstein test spm for whole set :\n", spm)
spm_train = np.zeros((len(Y_train), max_voices, max_voices))
for i, Y in enumerate(Y_train):
bars= np.copy(Y)
if include_silent_note:
bars = bars[:,:,:-1]
score_pair_matrix = data_class.get_harmonicity_scores_for_each_track_combination(bars)
spm_train[i] = score_pair_matrix
spm_train_mean = np.nanmean(spm_train, axis=0)
print("Score pair matrix train mean: \n", spm_train_mean)
spm_train_mean_for_each_class = []
for C in range(num_classes):
spms_for_this_class = spm_train[np.where(np.asarray(C_train) == C)]
m = np.nanmean(np.asarray(spms_for_this_class), axis=0)
print("Score pair matrix for train set in class " + classes[C] + ":\n", m)
spm_train_mean_for_each_class.append(m)
spm_test = np.zeros((len(Y_test),max_voices, max_voices))
for i, Y in enumerate(Y_test):
bars= np.copy(Y)
if include_silent_note:
bars = bars[:,:,:-1]
score_pair_matrix = data_class.get_harmonicity_scores_for_each_track_combination(bars)
spm_test[i] = score_pair_matrix
spm_test_mean = np.nanmean(spm_test, axis=0)
print("\nScore pair matrix test mean: \n", spm_test_mean)
spm_test_mean_for_each_class = []
for C in range(num_classes):
spms_for_this_class = spm_test[np.where(np.asarray(C_test) == C)]
m = np.nanmean(np.asarray(spms_for_this_class), axis=0)
print("Score pair matrix for test set in class " + classes[C] + ":\n", m)
spm_test_mean_for_each_class.append(m)
# ----------------------------------------------------------------------------------------------
# Instruments (midi programs) statistics
# ----------------------------------------------------------------------------------------------
programs_for_each_class = [[] for _ in range(num_classes)]
for train_song_num in range(len(Y_train)):
C = C_train[train_song_num]
I = I_train[train_song_num]
programs = data_class.instrument_representation_to_programs(I, instrument_attach_method)
for program in programs:
if not program in programs_for_each_class[C]:
programs_for_each_class[C].append(program)
print(programs_for_each_class)
#calculate how many programs have to be switched on average for a style change on the training set
all_programs_plus_length_for_each_class = [[] for _ in range(num_classes)]
total_programs_for_each_class = [0 for _ in range(num_classes)]
program_probability_dict_for_each_class = [dict() for _ in range(num_classes)]
for i in range(len(I_train)):
num_samples = X_train[i].shape[0] #get the number of samples to know how many splitted songs there are for this original song
I = I_train[i]
C = C_train[i]
programs = data_class.instrument_representation_to_programs(I, instrument_attach_method)
all_programs_plus_length_for_each_class[C].append((programs, num_samples))
total_programs_for_each_class[C] += num_samples * max_voices
for program in programs:
program_probability_dict_for_each_class[C][program] = program_probability_dict_for_each_class[C].get(program, 0) + num_samples
for d in program_probability_dict_for_each_class:
print(d)
#divide by total number of programs to get a probability for each key
for C, d in enumerate(program_probability_dict_for_each_class):
for k in d.keys():
d[k] /= total_programs_for_each_class[C]
for d in program_probability_dict_for_each_class:
print(d)
#enlist the possible instruments for each class
if instrument_attach_method == '1hot-category' or 'khot-category':
possible_programs = list(range(0,127,8))
else:
possible_programs = list(range(0,127))
#calculate the random probability for each class
print("Calculate how probable your instrument picks are if you pick them completely random: ")
for C, class_name in enumerate(classes):
probabilities_for_this_class = []
for program in possible_programs:
probabilities_for_this_class.append(program_probability_dict_for_each_class[C].get(program, 0))
print("Random probability for class " + class_name + ": ", np.mean(probabilities_for_this_class))
#of course, this is the same as 1/len(possible_programs)
#calculate the instrument probability for each class
print("Calculate how probable your instrument picks are if you don't switch any instrument and stay in the same class: ")
for C, class_name in enumerate(classes):
probability_for_this_class = 0
for (programs, length) in all_programs_plus_length_for_each_class[C]:
for program in programs:
probability_for_this_class += length * program_probability_dict_for_each_class[C].get(program, 0)
probability_for_this_class /= total_programs_for_each_class[C]
print("Same probability for class " + class_name + ": ", probability_for_this_class)
#calculate the instrument probability for each class
print("Calculate how probable your instrument picks are in another classif you don't switch any instrument: ")
for C, class_name in enumerate(classes):
for C_switch, class_name_switch in enumerate(classes):
if C != C_switch:
probability_for_other_class = 0
for (programs, length) in all_programs_plus_length_for_each_class[C]:
for program in programs:
probability_for_other_class += length * program_probability_dict_for_each_class[C_switch].get(program, 0)
probability_for_other_class /= total_programs_for_each_class[C]
print("Probability that a program-pick from class " + class_name + " is occuring class " + class_name_switch +" : ", probability_for_other_class)
for C, class_name in enumerate(classes):
programs_plus_length_for_this_class = all_programs_plus_length_for_each_class[C]
print(len(programs_plus_length_for_this_class))
for C_switch, class_name_switch in enumerate(classes):
if C_switch != C:
print("Calculating how many instruments switches have to be made from " + class_name + " to " + class_name_switch)
same = 0.0
different = 0.0
programs_plus_length_for_other_class = all_programs_plus_length_for_each_class[C_switch]
for programs, length in programs_plus_length_for_this_class:
for programs_switch, length_switch in programs_plus_length_for_other_class:
for this_program, other_program in zip(programs, programs_switch):
if this_program == other_program:
same += length * length_switch
else:
different += length * length_switch
print("Switch percentage: ", different / (same + different))
# ----------------------------------------------------------------------------------------------
# Prepare signature vectors
# ----------------------------------------------------------------------------------------------
S_train_for_each_class = [[] for _ in range(num_classes)]
S_test_for_each_class = [[] for _ in range(num_classes)]
all_S = []
S_train = []
for train_song_num in range(len(Y_train)):
Y = Y_train[train_song_num]
C = C_train[train_song_num]
num_samples = Y.shape[0]
signature_vectors = np.zeros((num_samples, signature_vector_length))
for sample in range(num_samples):
poly_sample = data_class.monophonic_to_khot_pianoroll(Y[sample], max_voices)
if include_silent_note:
poly_sample = poly_sample[:,:-1]
signature = data_class.signature_from_pianoroll(poly_sample)
signature_vectors[sample] = signature
S_train.append(signature_vectors)
all_S.extend(signature_vectors)
S_train_for_each_class[C].extend(signature_vectors)
all_S = np.asarray(all_S)
mean_signature = np.mean(all_S, axis=0)
print(mean_signature)
std_signature = np.std(all_S, axis=0)
#make sure you don't divide by zero if std is 0
for i, val in enumerate(std_signature):
if val == 0:
std_signature[i] = 1.0e-10
print(std_signature)
normalized_S_train = []
for signature_vectors in S_train:
normalized_signature_vectors = (signature_vectors - mean_signature) / std_signature
normalized_S_train.append(normalized_signature_vectors)
normalized_S_test = []
S_test = []
for test_song_num in range(len(Y_test)):
Y = Y_test[test_song_num]
C = C_test[test_song_num]
num_samples = Y.shape[0]
signature_vectors = np.zeros((num_samples, signature_vector_length))
normalized_signature_vectors = np.zeros((num_samples, signature_vector_length))
for sample in range(num_samples):
poly_sample = data_class.monophonic_to_khot_pianoroll(Y[sample], max_voices)
if include_silent_note:
poly_sample = poly_sample[:,:-1]
signature = data_class.signature_from_pianoroll(poly_sample)
normalized_signature_vectors[sample] = signature
signature = (signature - mean_signature) / std_signature
normalized_signature_vectors[sample] = signature
normalized_S_test.append(signature_vectors)
S_test_for_each_class[C].extend(signature_vectors)
S_test.append(signature_vectors)
normalized_S_test = np.asarray(normalized_S_test)
S_test = np.asarray(S_test)
normalized_S_train = np.asarray(normalized_S_train)
S_test = np.asarray(S_train)
S_train_for_each_class = np.asarray(S_train_for_each_class)
S_test_for_each_class = np.asarray(S_test_for_each_class)
# ----------------------------------------------------------------------------------------------
# Build VAE and load from weights
# ----------------------------------------------------------------------------------------------
#You have to create the model again with the same parameters as in training and set the weights manually
#There is an issue with storing the model with the recurrentshop extension
if do_not_sample_in_evaluation:
e = 0.0
else:
e = epsilon_std
model = VAE()
model.create( input_dim=input_dim,
output_dim=output_dim,
use_embedding=use_embedding,
embedding_dim=embedding_dim,
input_length=input_length,
output_length=output_length,
latent_rep_size=latent_dim,
vae_loss=vae_loss,
optimizer=optimizer,
activation=activation,
lstm_activation=lstm_activation,
lstm_state_activation=lstm_state_activation,
epsilon_std=e,
epsilon_factor=epsilon_factor,
include_composer_decoder=include_composer_decoder,
num_composers=num_composers,
composer_weight=composer_weight,
lstm_size=lstm_size,
cell_type=cell_type,
num_layers_encoder=num_layers_encoder,
num_layers_decoder=num_layers_decoder,
bidirectional=bidirectional,
decode=decode,
teacher_force=teacher_force,
learning_rate=learning_rate,
split_lstm_vector=split_lstm_vector,
history=history,
beta=beta,
prior_mean=prior_mean,
prior_std=prior_std,
decoder_additional_input=decoder_additional_input,
decoder_additional_input_dim=decoder_additional_input_dim,
extra_layer=extra_layer,
meta_instrument= meta_instrument,
meta_instrument_dim= meta_instrument_dim,
meta_instrument_length=meta_instrument_length,
meta_instrument_activation=meta_instrument_activation,
meta_instrument_weight = meta_instrument_weight,
signature_decoder = signature_decoder,
signature_dim = signature_dim,
signature_activation = signature_activation,
signature_weight = signature_weight,
composer_decoder_at_notes_output=composer_decoder_at_notes_output,
composer_decoder_at_notes_weight=composer_decoder_at_notes_weight,
composer_decoder_at_notes_activation=composer_decoder_at_notes_activation,
composer_decoder_at_instrument_output=composer_decoder_at_instrument_output,
composer_decoder_at_instrument_weight=composer_decoder_at_instrument_weight,
composer_decoder_at_instrument_activation=composer_decoder_at_instrument_activation,
meta_velocity=meta_velocity,
meta_velocity_length=meta_velocity_length,
meta_velocity_activation=meta_velocity_activation,
meta_velocity_weight=meta_velocity_weight,
meta_held_notes=meta_held_notes,
meta_held_notes_length=meta_held_notes_length,
meta_held_notes_activation=meta_held_notes_activation,
meta_held_notes_weight=meta_held_notes_weight,
meta_next_notes=meta_next_notes,
meta_next_notes_output_length=meta_next_notes_output_length,
meta_next_notes_weight=meta_next_notes_weight,
meta_next_notes_teacher_force=meta_next_notes_teacher_force,
activation_before_splitting=activation_before_splitting
)
autoencoder = model.autoencoder
autoencoder.load_weights(model_path+'autoencoder'+'Epoch'+str(epoch)+'.pickle', by_name=False)
encoder = model.encoder
encoder.load_weights(model_path+'encoder'+'Epoch'+str(epoch)+'.pickle', by_name=False)
decoder = model.decoder
decoder.load_weights(model_path+'decoder'+'Epoch'+str(epoch)+'.pickle', by_name=False)
print(encoder.summary())
print(decoder.summary())
print(autoencoder.summary())
if reset_states:
autoencoder.reset_states()
encoder.reset_states()
decoder.reset_states()
# ----------------------------------------------------------------------------------------------
# Helper functions
# ----------------------------------------------------------------------------------------------
#spherical linear interpolation
def slerp(p0, p1, t):
omega = arccos(dot(p0/np.linalg.norm(p0), p1/np.linalg.norm(p1)))
so = sin(omega)
return sin((1.0-t)*omega) / so * p0 + sin(t*omega)/so * p1
def linear_interpolation(p0, p1, t):
return p0 * (1.0-t) + p1 * t
def split_song_back_to_samples(X, length):
number_of_splits = int(X.shape[0] / length)
splitted_songs = np.split(X, number_of_splits)
return splitted_songs
#I_pred instrument prediction of shape (num_samples, max_voices, different_instruments)
#returns list of program numbers of length max_voices
def vote_for_programs(I_pred):
program_voting_dict_for_each_voice = [dict() for _ in range(max_voices)]
for instrument_feature_matrix in I_pred:
programs = data_class.instrument_representation_to_programs(instrument_feature_matrix, instrument_attach_method)
for voice, program in enumerate(programs):
program_voting_dict_for_each_voice[voice][program] = program_voting_dict_for_each_voice[voice].get(program,0) + 1
#determine mixed_programs_for_whole_song by taking the instruments for each track with the most occurence in the mixed predictions
programs_for_whole_long_song = []
for voice in range(max_voices):
best_program = 0
highest_value = 0
for k in program_voting_dict_for_each_voice[voice].keys():
if program_voting_dict_for_each_voice[voice][k] > highest_value:
best_program = k
highest_value = program_voting_dict_for_each_voice[voice][k]
programs_for_whole_long_song.append(best_program)
return programs_for_whole_long_song
def prepare_for_drawing(Y, V=None):
#use V to make a grey note if it is more silent
newY = np.copy(Y)
if V is not None:
for step in range(V.shape[0]):
if V[step] > velocity_threshold_such_that_it_is_a_played_note:
velocity = (V[step] - velocity_threshold_such_that_it_is_a_played_note) * MAX_VELOCITY
newY[step,:] *= velocity
else:
if step > max_voices:
previous_pitch = np.argmax(newY[step-max_voices])
current_pitch = np.argmax(newY[step])
if current_pitch != previous_pitch:
newY[step,:] = 0
else:
newY[step,:] = newY[step-max_voices,:]
else:
newY[step,:] = 0
Y_poly = data_class.monophonic_to_khot_pianoroll(newY, max_voices, set_all_nonzero_to_1=False)
else:
Y_poly = data_class.monophonic_to_khot_pianoroll(newY, max_voices)
return np.transpose(Y_poly)
def restructure_song_to_fit_more_instruments(Y, I_list, V, D):
num_samples = len(I_list)
Y_final = np.zeros((num_samples * output_length * num_samples, Y.shape[1]))
V_final = np.zeros((num_samples * output_length * num_samples,))
D_final = np.zeros((num_samples * output_length * num_samples,))
final_programs = []
for sample, I in enumerate(I_list):
programs = data_class.instrument_representation_to_programs(I, instrument_attach_method)
final_programs.extend(programs)
for step in range(output_length//max_voices):
for voice in range(max_voices):
Y_final[sample * output_length * num_samples + step * num_samples * max_voices + voice,:] = Y[sample *output_length+ step*max_voices + voice,:]
V_final[sample * output_length * num_samples + step * num_samples * max_voices + voice] = V[sample *output_length+ step*max_voices + voice]
D_final[sample * output_length * num_samples + step * num_samples * max_voices + voice] = D[sample *output_length + step*max_voices + voice]
return Y_final, final_programs, V_final, D_final
# ----------------------------------------------------------------------------------------------
# Save latent train lists
# ----------------------------------------------------------------------------------------------
print("Saving latent train lists...")
train_representation_list = []
all_z = []
for train_song_num in range(len(X_train)):
#create dataset
song_name = train_paths[train_song_num].split('/')[-1]
song_name = song_name.replace('mid.pickle', '')
X = X_train[train_song_num]
C = C_train[train_song_num]
I = I_train[train_song_num]
V = V_train[train_song_num]
D = D_train[train_song_num]
encoder_input_list = vae_definition.prepare_encoder_input_list(X,I,V,D)
#get the latent representation of every song part
encoded_representation = encoder.predict(encoder_input_list, batch_size=batch_size, verbose=False)
train_representation_list.append(encoded_representation)
all_z.extend(encoded_representation)
train_save_folder = save_folder
if not test_train_set:
train_save_folder = save_folder[:-5] + 'train/'
if not os.path.exists(train_save_folder+ classes[C]+'/'):
os.makedirs(train_save_folder + classes[C]+'/')
if save_anything: np.save(train_save_folder + classes[C]+'/'+'z_' + song_name, encoded_representation)
z_mean_train = np.mean(np.asarray(all_z))
z_std_train = np.std(np.asarray(all_z))
print("z mean train: ", z_mean_train)
print("z std train: ", z_std_train)
# ----------------------------------------------------------------------------------------------
# Generation of interpolation songs from the chosen training or test set
# ----------------------------------------------------------------------------------------------
sample_method = 'argmax'
assert(noninterpolated_samples_between_interpolation > 0)
for song_num in range(max_new_chosen_interpolation_songs):
print("Producing chosen interpolation song ", song_num)
medley_name = 'medley_songs_' + str(how_many_songs_in_one_medley) + '_original_' + str(noninterpolated_samples_between_interpolation) + '_bridge_' + str(interpolation_length) + '_'
Y_list = []
V_list = []
D_list = []
I_list = []
info_dict = dict()
previous_medley_z = None
C = 0
previous_latent_rep = np.zeros((1,latent_dim))
S = np.zeros((1, signature_vector_length))
for medley_song_num in range(how_many_songs_in_one_medley):
if test_train_set:
#chose random train song that is long enough
song_num = np.random.randint(train_set_size)
while X_train[song_num].shape[0] <= noninterpolated_samples_between_interpolation:
song_num = np.random.randint(train_set_size)
X = X_train[song_num]
I = I_train[song_num]
C = C_train[song_num]
V = V_train[song_num]
D = D_train[song_num]
song_name = train_paths[song_num].split('/')[-1]
song_name = song_name.replace('mid.pickle', '')
else:
#chose random train song that is long enough
song_num = np.random.randint(test_set_size)
while X_test[song_num].shape[0] <= noninterpolated_samples_between_interpolation:
song_num = np.random.randint(test_set_size)
X = X_test[song_num]
I = I_test[song_num]
C = C_test[song_num]
V = V_test[song_num]
D = D_test[song_num]
song_name = test_paths[song_num].split('/')[-1]
song_name = song_name.replace('mid.pickle', '')
#chose random sample
sample_num = np.random.randint(X.shape[0])
if sample_num < noninterpolated_samples_between_interpolation and medley_song_num == 0:
sample_num = noninterpolated_samples_between_interpolation
elif sample_num >= X.shape[0] - noninterpolated_samples_between_interpolation:
sample_num = X.shape[0] - noninterpolated_samples_between_interpolation - 1
medley_name += '_' + str(song_num) + '-' + str(sample_num)
info_dict["song_name_" + str(medley_song_num)] = song_name
info_dict["sample_num_" + str(medley_song_num)] = sample_num
info_dict["programs_" + str(medley_song_num)] = data_class.instrument_representation_to_programs(I, instrument_attach_method)
#calculate which samples are needed
if medley_song_num == 0:
sample_list = range(sample_num-noninterpolated_samples_between_interpolation,sample_num)
else:
sample_list = range(sample_num , sample_num + noninterpolated_samples_between_interpolation)
X = np.copy(X[sample_list])
V = np.copy(V[sample_list])
D = np.copy(D[sample_list])
if X.ndim == 2:
X = np.expand_dims(X, axis=0)
if V.ndim == 1:
V = np.expand_dims(V, axis=0)
if D.ndim == 1:
D = np.expand_dims(D, axis=0)
encoder_input_list = vae_definition.prepare_encoder_input_list(X,I,V,D)
R = encoder.predict(encoder_input_list, batch_size=batch_size, verbose=False)
if previous_medley_z is not None:
for i in range(interpolation_length):
z = linear_interpolation(previous_medley_z, R[0], i/float(interpolation_length))
z = np.expand_dims(z, axis=0)
interpolation_input_list = vae_definition.prepare_decoder_input(z, C, S, previous_latent_rep)
decoder_outputs = decoder.predict(interpolation_input_list, batch_size=batch_size, verbose=False)
Y, I, V, D, N = vae_definition.process_decoder_outputs(decoder_outputs, sample_method)
Y_list.extend(Y)
I_list.extend(I)
V_list.extend(V)
D_list.extend(D)
info_dict["programs_" + str(medley_song_num) + "_interpolation_" +str(i)] = data_class.instrument_representation_to_programs(I[0], instrument_attach_method)
previous_latent_rep = z
for i in range(R.shape[0]):
z = R[i]
z = np.expand_dims(z, axis=0)
interpolation_input_list = vae_definition.prepare_decoder_input(z, C, S, previous_latent_rep)
decoder_outputs = decoder.predict(interpolation_input_list, batch_size=batch_size, verbose=False)
Y, I, V, D, N = vae_definition.process_decoder_outputs(decoder_outputs, sample_method)
Y_list.extend(Y)
I_list.extend(I)
V_list.extend(V)
D_list.extend(D)
previous_latent_rep = z
previous_medley_z = R[-1]
programs_for_whole_long_song = vote_for_programs(I_list)
Y_list = np.asarray(Y_list)
D_list = np.asarray(D_list)
V_list = np.asarray(V_list)
if save_anything:
with open(save_folder + medley_name + "_info.txt", "w", encoding='utf-8') as text_file:
for k, v in info_dict.items():
text_file.write(k + ": %s" % v + '\n')
if save_anything: data_class.draw_pianoroll(prepare_for_drawing(Y_list, V_list), name=medley_name, show=False, save_path=save_folder +medley_name)
Y_all_programs, all_programs, V_all_programs, D_all_programs = restructure_song_to_fit_more_instruments(Y_list, I_list, V_list, D_list)
if save_anything: mf.rolls_to_midi(Y_all_programs, all_programs, save_folder, medley_name, BPM, V_all_programs, D_all_programs)
# ----------------------------------------------------------------------------------------------
# Generation of random interpolation songs
# ----------------------------------------------------------------------------------------------
sample_method = 'argmax'
for song_num in range(max_new_sampled_interpolation_songs):
print("Producing random interpolation song ", song_num)
random_code_1 = np.random.normal(loc=0.0, scale=z_std_train, size=(1,latent_dim))
random_code_2 = np.random.normal(loc=0.0, scale=z_std_train, size=(1,latent_dim))
C = 0
Y_list = []
V_list = []
D_list = []
I_list = []
previous_latent_rep = np.zeros((1,latent_dim))
S = np.zeros((1, signature_vector_length))
for i in range(interpolation_song_length+1):
R = linear_interpolation(random_code_1, random_code_2, i/float(interpolation_song_length))
interpolation_input_list = vae_definition.prepare_decoder_input(R, C, S, previous_latent_rep)
decoder_outputs = decoder.predict(interpolation_input_list, batch_size=batch_size, verbose=False)
Y, I, V, D, N = vae_definition.process_decoder_outputs(decoder_outputs, sample_method)
Y_list.extend(Y)
I_list.extend(I)
V_list.extend(V)
D_list.extend(D)
previous_latent_rep = R
programs_for_whole_long_song = vote_for_programs(I_list)
Y_list = np.asarray(Y_list)
D_list = np.asarray(D_list)
V_list = np.asarray(V_list)
if save_anything: data_class.draw_pianoroll(prepare_for_drawing(Y_list, V_list), name='random_interpolation_' + str(song_num) + '_length_' + str(interpolation_song_length), show=False, save_path=save_folder +'random_interpolation_' + str(song_num)+'_length_' + str(interpolation_song_length))
if save_anything: mf.rolls_to_midi(Y_list, programs_for_whole_long_song, save_folder, 'random_interpolation_' + str(song_num) + '_length_' + str(interpolation_song_length), BPM, V_list, D_list)
Y_all_programs, all_programs, V_all_programs, D_all_programs = restructure_song_to_fit_more_instruments(Y_list, I_list, V_list, D_list)
if save_anything: mf.rolls_to_midi(Y_all_programs, all_programs, save_folder, 'random_interpolation_' + str(song_num) + '_length_' + str(interpolation_song_length) + '_all_programs', BPM, V_all_programs, D_all_programs)
# ----------------------------------------------------------------------------------------------
# Latent list helper functions
# ----------------------------------------------------------------------------------------------
#get points around 0 with sigma that look like this: . . . . . ... . . . . .
#range end: between 0.5 and 1.0
#evaluations_per_dimension how many samples to give back / 2
#sigma: std of normal distribution that needs to be 'sampled' from
def get_normal_distributed_values(range_end, evaluations_per_dimension, sigma, evaluate_postive_and_negative):
values = []
range_end = float(range_end) #make sure you have a float, otherwise the division by dimension will result in int
cdf_values = np.linspace(0.5, 0.5 + range_end, evaluations_per_dimension)
for cdf in cdf_values:
x = scipy.stats.norm.ppf(cdf, loc=0.0, scale=sigma)
if x != 0:
if evaluate_postive_and_negative:
values.append(-x)
values.append(x)
else:
values.append(x)
return sorted(values)
def save_to_summary(args, summary_dict):
name, strength, probability = args
summary_dict[name] = (strength, probability)
def get_strength_probability_direction_for_value_list(value_list):
if len(value_list) > 0:
#determine the order
if np.mean(value_list[:len(value_list)//2]) > np.mean(value_list[len(value_list)//2:]):
#descending order -> switch order
value_list = value_list[::-1]
direction = 'descending'
else:
direction = 'ascending'
#calculate strength as a mean of the difference of these values
differences_value_list = np.asarray(value_list[1:]) - np.asarray(value_list[:-1])
strength = np.mean(differences_value_list)
#calculate the probability that this
correct_ascending = 0
incorrect_ascending = 0
previous_value = value_list[0]
for value in value_list[1:]:
if value >= previous_value:
correct_ascending += 1
else:
incorrect_ascending += 1
previous_value = value
if (correct_ascending + incorrect_ascending) > 0:
probability = correct_ascending / (correct_ascending + incorrect_ascending)
else:
probability = 0
else:
direction='ascending'
strength = 0.0
probability = 0.0
return strength, probability, direction
#statistic_name: which statistic to test, can be 'mean', 'median' 'std', 'max', 'min', 'range'
def evaluate_statistic_value(splitted_list, value_name, statistic_name):
statistic_values = []
for value_list in splitted_list:
if len(value_list) > 0:
if statistic_name == 'mean':
statistic_values.append(np.mean(value_list))
elif statistic_name == 'median':
statistic_values.append(np.median(value_list))
elif statistic_name == 'std':
statistic_values.append(np.std(value_list))
elif statistic_name == 'max':
statistic_values.append(np.max(value_list))
elif statistic_name == 'min':
statistic_values.append(np.min(value_list))
elif statistic_name == 'range':
statistic_values.append(np.max(value_list) - np.min(value_list))
strength, probability, direction = get_strength_probability_direction_for_value_list(statistic_values)
return (statistic_name + "_" + value_name + "_" +direction, strength, probability)
def evaluate_count_of_values(splitted_list, value_name, specific_value=None):
count_of_values = []
for value_list in splitted_list:
if specific_value is None:
count_of_values.append(len(value_list))
else:
count_of_values.append(value_list.count(specific_value))
strength, probability, direction = get_strength_probability_direction_for_value_list(count_of_values)
return ("total_count_of_" + value_name + "_" + direction, strength, probability)
def evaluate_change_of_values(splitted_list, value_name):
previous_values = splitted_list[0]
change_counter = 0.0
total_counter = 0.0
for values in splitted_list[1:]:
for v_current, v_previous in zip(values, previous_values):
total_counter += 1.0
if v_current != v_previous:
change_counter += 1.0
previous_values = values