-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain1.py
1576 lines (1401 loc) · 65.1 KB
/
main1.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 logging
import logging.handlers
import argparse
import os
import time
from data_loader import organiser
import shutil
import sys
import torch
import random
import numpy as np
import pandas as pd
import utilities.utilities_main as util
import socket
from distutils.dir_util import copy_tree
import sklearn.metrics as metrics
from sklearn.metrics import confusion_matrix
import natsort
from utilities import model_utilities as mu
from exp_run.plotter import plot_graph
from exp_run import config_dataset
import pickle
from exp_run.models_pytorch import CustomMel7 as CustomMel
from exp_run.models_pytorch import CustomRaw1 as CustomRaw
from exp_run import config_1 as config
import warnings
warnings.filterwarnings('ignore')
learn_rate_factor = 2
EPS = 1e-12
def evaluation_for_test(results_dict, num_class, f_score, main_logger,
hidden_test=False):
"""
This function is only used for mode==test and data_type=='test'. Every
prediction for each folder in the test set is accumulated to results_dict
along with the number of instances of each folder. There will be multiple
predictions for each folder depending on how many times the experiment
was run during training (e.g. 5). If the user sets argument:
prediction_metric=0 -> the accuracy will be determined for every experiment
iteration (e.g. 5) and the best performing model will be selected. NOTE:
This will not work if running in test mode without validation set and
using the test_split_Depression_AVEC2017.csv file.
prediction_metric=1 -> the average of the accumulated predictions for
each folder will be taken and the final score will relate to these
averaged results.
prediction_metric=2 -> The majority vote of the accumulated predictions
for each folder will be taken and the final score will related to these
results
Input
results_dict: dictionary key: output, target, accum. For each of
these keys is a corresponding dictionary where key:
folder, value relates to the super key: output ->
predictions from experiments, target -> corresponding
label for the folder, accum -> the accumulated
instances of each folder
num_class: int - Number of classes in the dataset
f_score: str - Type of F1 Score processing
Outputs:
scores: List - contains accuracy, fscore and tn_fp_fn_tp
"""
if not hidden_test:
temp_tar = np.array(list(results_dict['target'].values()))
final_results = {}
# Pick best performing model
if prediction_metric == 0:
f_score_avg = []
temp_out = np.zeros((exp_runthrough,
len(results_dict['output'].keys())))
temp_scores = np.zeros((exp_runthrough, 15))
for pos, f in enumerate(results_dict['output'].keys()):
if exp_runthrough == 1:
temp_out[0, pos] = results_dict['output'][f] / results_dict[
'accum'][f]
else:
temp_out[:, pos] = list(results_dict['output'][f] /
results_dict['accum'][f])
for exp in range(exp_runthrough):
temp_scores[exp, :], _ = prediction_and_accuracy(temp_out[exp, :],
temp_tar,
True,
num_class,
np.zeros(15),
0,
0,
f_score)
f_score_avg = f_score_avg + [np.mean(temp_scores[exp, 6:8])]
best_result_index = f_score_avg.index(max(f_score_avg))
print(f"\nThe best performing model was experiment: "
f"{best_result_index+1}")
main_logger.info(f"The best performing model was experiment: "
f"{best_result_index + 1}")
scores = temp_scores[best_result_index, :]
# Average the performance of all models
elif prediction_metric == 1:
print("\nPerforming averaging of accumulated predictions")
for f in results_dict['output'].keys():
final_results[f] = np.average(
results_dict['output'][f] / results_dict['accum'][f])
temp_out = np.array(list(final_results.values()))
if not hidden_test:
scores, _ = prediction_and_accuracy(temp_out,
temp_tar,
True,
num_class,
np.zeros(15),
0,
0,
f_score)
else:
scores = temp_out
# Calculate majority vote from all models
elif prediction_metric == 2:
print("\nPerforming majority vote on accumulated predictions")
for f in results_dict['output'].keys():
final_results[f] = np.average(
np.round(results_dict['output'][f] / results_dict['accum'][f]))
temp_out = np.array(list(final_results.values()))
if not hidden_test:
scores, _ = prediction_and_accuracy(temp_out,
temp_tar,
True,
num_class,
np.zeros(15),
0,
0,
f_score)
else:
scores = temp_out
if not hidden_test:
scores[8] = np.mean(scores[0:2])
scores[9] = np.mean(scores[6:8])
scores = [scores[8], scores[0], scores[1], scores[9], scores[6], scores[7],
scores[11], scores[12], scores[13], scores[14]]
else:
scores = np.round(scores)
return scores
def calculate_accuracy(target, predict, classes_num, f_score_average):
"""
Calculates accuracy, precision, recall, F1-Score, True Negative,
False Negative, True Positive, and False Positives of the output of
the model
Inputs
target: np.array() The labels for the predicted outputs from the model
predict: np.array() The batched outputs of the network
classes_num: int How many classes are in the dataset
f_score_average: str How to average the F1-Score
Outputs:
accuracy: Float Accuracy of the model outputs
p_r_f: Array of Floats Precision, Recall, and F1-Score
tn_fp_fn_tp: Array of Floats True Negative, False Positive,
False Negative, and True Positive
"""
number_samples_labels = len(target)
number_correct_predictions = np.zeros(classes_num)
total = np.zeros(classes_num)
for n in range(number_samples_labels):
total[target[n]] += 1
if target[n] == predict[n]:
number_correct_predictions[target[n]] += 1
con_matrix = confusion_matrix(target,
predict)
tn_fp_fn_tp = con_matrix.ravel()
if tn_fp_fn_tp.shape != (4,):
value = int(tn_fp_fn_tp)
if target[0][0] == 1:
tn_fp_fn_tp = np.array([0, 0, 0, value])
elif target[0][0] == 0:
tn_fp_fn_tp = np.array([value, 0, 0, 0])
else:
print('Error in the true_neg/false_pos value')
sys.exit()
if f_score_average is None:
# This code fixes the divide by zero error
accuracy = np.divide(number_correct_predictions,
total,
out=np.zeros_like(number_correct_predictions),
where=total != 0)
p_r_f = metrics.precision_recall_fscore_support(target,
predict)
elif f_score_average == 'macro':
# This code fixes the divide by zero error
accuracy = np.divide(number_correct_predictions,
total,
out=np.zeros_like(number_correct_predictions),
where=total != 0)
p_r_f = metrics.precision_recall_fscore_support(target,
predict,
average='macro')
elif f_score_average == 'micro':
# This code fixes the divide by zero error
accuracy = np.divide(np.sum(number_correct_predictions),
np.sum(total),
out=np.zeros_like(number_correct_predictions),
where=total != 0)
p_r_f = metrics.precision_recall_fscore_support(target,
predict,
average='micro')
else:
raise Exception('Incorrect average!')
if p_r_f[0].shape == (1,):
temp = np.zeros((4, 2))
position = int(target[0])
for val in range(len(p_r_f)):
temp[val][position] = float(p_r_f[val])
p_r_f = (temp[0], temp[1], temp[2], temp[3])
return accuracy, p_r_f, tn_fp_fn_tp
def forward(model, generate_dev, data_type):
"""
Pushes the data to the model and collates the outputs
Inputs:
model: The neural network for experimentation
generate_dev: generator - holds the batches for the validation
data_type: str - set to 'train', 'dev' or 'test'
Output:
results_dict: dictionary - Outputs, optional - labels and folders
"""
outputs = []
folders = []
targets = []
# Evaluate on mini-batch
counter = 0
for data in generate_dev:
(batch_data, batch_label, batch_folder, batch_locator) = data
# Predict
model.eval()
# Potentially speeds up evaluation and memory usage
with torch.no_grad():
batch_output = get_output_from_model(model=model,
data=batch_data)
counter += 1
# Append data
outputs.append(batch_output.data.cpu().numpy())
folders.append(batch_folder)
targets.append(batch_label)
results_dict = {}
outputs = np.concatenate(outputs, axis=0)
results_dict['output'] = outputs
folders = np.concatenate(folders, axis=0)
results_dict['folder'] = np.array(folders)
targets = np.concatenate(targets, axis=0)
results_dict['target'] = np.array(targets)
return results_dict
def evaluate(model, generator, data_type, class_weights, comp_res, class_num,
f_score_average, epochs, logger, gender_balance=False,
hidden_test=False):
"""
Processes the validation set by creating batches, passing these through
the model and then calculating the resulting loss and accuracy metrics.
Input
model: neural network for experimentation
generator: generator - Created to load validation data to the model
data_type: str - set to 'dev' or 'test'
class_weights: Dictionary - Key is Folder, Value is weight
comp_res: np.array - holds results for each iteration of experiment
class_num: int - Number of classes in the dataset
f_score_average: str - Type of F1 Score processing
averaging: str - Geometric or arithmetic for the outputs from the model
net_p: dictionary - holds the model configurations
recurrent_out: str - If RNN used, how to process the output
epochs: int - The current epoch
logger: log for keeping important info
gender_balance: bool
Returns:
complete_results: np.array - holds results for each iteration of
experiment
per_epoch_pred: numpy.array - collated outputs and labels from the
current validation test
"""
# Generate function
print('Generating data for evaluation')
start_time_dev = time.time()
if data_type == 'dev':
generate_dev = generator.generate_development_data(epoch=epochs)
else:
generate_dev = generator.generate_test_data()
# Forward
results_dict = forward(model=model,
generate_dev=generate_dev,
data_type=data_type)
outputs = results_dict['output'] # (audios_num, classes_num)
folders = results_dict['folder']
targets = results_dict['target'] # (audios_num, classes_num)
collected_output = {}
output_for_loss = {}
collected_targets = {}
counter = {}
for p, fol in enumerate(folders):
if fol not in collected_output.keys():
collected_targets[fol] = targets[p]
output_for_loss[fol] = outputs[p]
collected_output[fol] = np.round(outputs[p])
counter[fol] = 1
else:
output_for_loss[fol] = outputs[p]
collected_output[fol] += np.round(outputs[p])
counter[fol] += 1
if mode == 'test':
intermediate_outputs = collected_output
intermediate_counter = counter
intermediate_targets = collected_targets
new_outputs = []
new_folders = []
new_targets = []
new_output_for_loss = []
# This is essentially performing majority vote. We have rounded all the
# predictions made per file. We now divide the resulting value by the
# number of instances per file.
for co in collected_output:
tmp = collected_output[co] / counter[co]
new_outputs.append(tmp)
tmp = output_for_loss[co] / counter[co]
new_output_for_loss.append(tmp)
new_folders.append(co)
new_targets.append(collected_targets[co])
outputs = np.array(new_outputs)
folders = np.array(new_folders)
targets = np.array(new_targets)
calculate_time(start_time_dev,
time.time(),
data_type,
logger)
batch_weights = find_batch_weights(folders,
class_weights)
loss = mu.calculate_loss(torch.Tensor(outputs),
torch.LongTensor(targets),
batch_weights,
gender_balance)
if gender_balance:
targets = targets % 2
if not hidden_test:
complete_results, per_epoch_pred = prediction_and_accuracy(outputs,
targets,
True,
class_num,
comp_res,
loss, 0,
f_score_average)
if data_type == 'test':
return complete_results, (per_epoch_pred, intermediate_outputs, \
intermediate_counter, intermediate_targets)
else:
return complete_results, (per_epoch_pred, folders)
else:
return -1, (-1, intermediate_outputs, intermediate_counter, -1)
def logging_info(current_dir, data_type=''):
"""
Sets up the logger to be used for the current experiment. This is useful
to capture relevant information during the course of the experiment.
Inputs:
current_dir: str - the location of the current experiment
data_type: str - set to 'test' or 'dev' when running the code in test
mode. 'dev' will load existing best epochs and
re-run them on validation set, 'test' will load
existing best epochs and run them on test set.
Output
main_logger: logger - The created logger
"""
if mode == 'test':
pm = {0: 'best', 1: 'avg', 2: 'mv'}
log_path = current_dir + '/' + pm[prediction_metric]
if data_type == 'test':
log_path = log_path + '_test.log'
elif data_type == 'dev':
log_path = log_path + '_val_test.log'
else:
log_path = os.path.join(current_dir, 'log',
f"model_{folder_extensions[i]}.log")
main_logger = logging.getLogger('MainLogger')
main_logger.setLevel(logging.INFO)
if os.path.exists(log_path) and mode == 'test':
os.remove(log_path)
main_handler = logging.handlers.RotatingFileHandler(log_path)
main_logger.addHandler(main_handler)
main_logger.info(config_dataset.SEPARATOR)
main_logger.info('EXPERIMENT DETAILS')
for dict_val in config.EXPERIMENT_DETAILS:
if dict_val == 'SEED':
main_logger.info(f"Starting {dict_val}:"
f" {str(config.EXPERIMENT_DETAILS[dict_val])}")
else:
main_logger.info(f"{dict_val}:"
f" {str(config.EXPERIMENT_DETAILS[dict_val])}")
main_logger.info(f"Current Seed: {chosen_seed}")
main_logger.info(f"Logged into: {socket.gethostname()}")
main_logger.info(f"Experiment details: {config.EXPERIMENT_BRIEF}")
main_logger.info(config_dataset.SEPARATOR)
return main_logger
def create_model():
"""
Creates the model to be used in the current experimentation
Output
model: obj - The model to be used for training during experiment
"""
if config.EXPERIMENT_DETAILS['FEATURE_EXP'] == 'mel':
model = CustomMel()
elif config.EXPERIMENT_DETAILS['FEATURE_EXP'] == 'raw':
model = CustomRaw()
if cuda:
model.cuda()
return model
def setup(current_dir, model_dir, data_type='', path_to_logger_for_test=None):
"""
Creates the necessary directories, data folds, logger, and model to be
used in the experiment. It also determines whether a previous checkpoint
has been saved.
Inputs:
current_dir: str - dir for the experiment
model_dir: str - location of the current model run-through
data_type: str - set to 'test' for different setup processing
path_to_logger_for_test: str - path to create a logger for running a
test
Outputs
main_logger: logger - The logger to be used to record information
model: obj - The model to be used for training during the experiment
checkpoint_run: str - The location of the last saved checkpoint
checkpoint: bool - True if loading from a saved checkpoint
next_exp: bool - If loading from a checkpoint is suspected but the
current experiment has been completed set True
"""
reproducibility(chosen_seed)
checkpoint_run = None
checkpoint = False
next_exp = False
if not os.path.exists(features_dir):
print('There is no folder and therefore no database created. '
'Create the database first')
sys.exit()
if os.path.exists(current_dir) and os.path.exists(model_dir) and debug:
shutil.rmtree(current_dir, ignore_errors=False, onerror=None)
# THIS WILL DELETE EVERYTHING IN THE CURRENT WORKSPACE #
if os.path.exists(current_dir) and os.path.exists(model_dir):
temp_dirs = os.listdir(model_dir)
temp_dirs = natsort.natsorted(temp_dirs, reverse=True)
temp_dirs = [d for d in temp_dirs if '.pth' in d]
if len(temp_dirs) == 0:
pass
else:
if int(temp_dirs[0].split('_')[1]) == final_iteration and mode ==\
'train':
directory = model_dir.split('/')[-1]
final_directory = model_dir.replace(directory, str(exp_runthrough))
if os.path.exists(final_directory):
temp_dirs2 = os.listdir(final_directory)
temp_dirs2 = natsort.natsorted(temp_dirs2, reverse=True)
temp_dirs2 = [d for d in temp_dirs2 if '.pth' in d]
if int(temp_dirs2[0].split('_')[1]) == final_iteration:
if i == exp_runthrough-1:
print(f"A directory at this location "
f"exists: {current_dir}")
sys.exit()
else:
next_exp = True
return None, None, None, None, next_exp
else:
return None, None, None, None, next_exp
else:
return None, None, None, None, next_exp
else:
print(f"Current directory exists but experiment not finished")
print(f"Loading from checkpoint: "
f"{int(temp_dirs[0].split('_')[1])}")
checkpoint_run = os.path.join(model_dir, temp_dirs[0])
checkpoint = True
elif not os.path.exists(current_dir):
os.mkdir(current_dir)
util.create_directories(current_dir,
config.EXP_FOLDERS)
os.mkdir(model_dir)
elif os.path.exists(current_dir) and not os.path.exists(model_dir):
os.mkdir(model_dir)
if mode == 'test' and path_to_logger_for_test is not None:
if not os.path.exists(path_to_logger_for_test):
os.mkdir(path_to_logger_for_test)
main_logger = logging_info(path_to_logger_for_test,
data_type)
else:
main_logger = logging_info(current_dir,
data_type)
model = create_model()
return main_logger, model, checkpoint_run, checkpoint, next_exp
def record_top_results(current_results, scores, epoch):
"""
Function to record the best validation F1-Score up to the current epoch.
More accurate than the alternate function record_top_results
Inputs:
current_results: list - current epoch results
scores: tuple - contains the best results for the experiment
epoch: int - The current epoch
Output
best_res: list - updated best result and epoch of discovery
"""
if current_results[8] > .86:
if validate:
train_f = current_results[9] / 4
train_loss = current_results[10] / 10
dev_f = current_results[-6]
dev_loss = current_results[-5] / 10
total = train_f - train_loss + dev_f - dev_loss
if total > scores[0]:
best_res = [total, current_results[8], current_results[0],
current_results[1], current_results[9],
current_results[6], current_results[7],
current_results[10], current_results[23],
current_results[15], current_results[16], dev_f,
current_results[21], current_results[22],
current_results[25], epoch]
else:
best_res = scores
else:
if current_results[8] > scores[0]:
best_res = [current_results[8], current_results[8],
current_results[0],
current_results[1], current_results[9],
current_results[6], current_results[7],
current_results[10], 0, 0, 0, 0, 0, 0, 0, epoch]
else:
best_res = scores
else:
best_res = scores
return best_res
def initialiser(test_value):
"""
Used to set a bool to True for the initialisation of some function or
variable
Input
test_value: int - If set to 1 then this is the initial condition
otherwise, already initialised
Output
bool - True if this is the initialisation case
"""
if test_value == 1:
return True
else:
return False
def compile_train_val_pred(train_res, val_res, comp_train, comp_val, epoch):
"""
Used to group the latest results for both the training and the validation
set into their respective complete results array
Inputs
train_res: numpy.array - The current results for this epoch
val_res: numpy.array - The current results for this epoch
comp_train: numpy.array - The total recorded results
comp_val: numpy.array - The total recorded results
epoch: int - The current epoch used for initialisation
Outputs
comp_train: numpy.array - The updated complete results
comp_val - numpy.array - The updated complete results
"""
# 3D matrix ('Num_segments_batches', 'pred+label', 'epochs')
if epoch == 1:
comp_train = train_res
comp_val = val_res
else:
if train_res.shape[0] != comp_train.shape[0]:
difference = comp_train.shape[0] - train_res.shape[0]
train_res = np.vstack((train_res, np.zeros((difference, 2))))
comp_train = np.dstack((comp_train, train_res))
comp_val = np.dstack((comp_val, val_res))
return comp_train, comp_val
def update_complete_results(complete_results, avg_counter, placeholder,
best_scores):
"""
Finalises the complete results dataframe by calculating the mean of the 2
class scores for accuracy and F1-Score and in the case of the training
data, divides the results by the number of iterations in order to get the
average results from the current epoch (previously updated by accumulation)
Also obtains the best scores for the model.
Inputs
complete_results: dataframe - holds the complete results from the
experiment so far
avg_counter: int - used in train mode to average the recorded results
for the current epoch
placeholder: Essentially the number of epochs (but can be used in
iteration mode)
best_scores: list - Contains the best scores so far and the
respective epochs, calculated according to weighting of
training and validation scores/losses:
train_f/4 - train_loss/10 + dev_f - dev_loss/10
with a threshold of 86% if training score is less than
this we do not consider it
Outputs
complete_results: np.array - Updated version of the complete results
best_scores: list - Updated version of best_scores
"""
complete_results[0:11] = complete_results[0:11] / avg_counter
# Accuracy Mean
complete_results[8] = np.mean(complete_results[0:2])
complete_results[23] = np.mean(complete_results[15:17])
# FScore Mean
complete_results[9] = np.mean(complete_results[6:8])
complete_results[24] = np.mean(complete_results[21:23])
print_log_results(placeholder, complete_results[0:15], 'train')
if validate:
print_log_results(placeholder, complete_results[15:], 'dev')
best_scores = record_top_results(complete_results,
best_scores,
placeholder)
return complete_results, best_scores
def prediction_and_accuracy(batch_output, batch_labels, initial_condition,
num_of_classes, complete_results, loss,
per_epoch_pred, f_score_average=None):
"""
Calculates the accuracy (including F1-Score) of the predictions from a
model. Also the True Negatives, False Negatives, True Positives, and False
Positives are calculated. These results are stored along with results
from previous epochs.
Input
batch_output: The output from the model
batch_labels: The respective labels for the batched output
initial_condition: Bool - True if this is the first instance to set
up the variables for logging accuracy
num_of_classes: The number of classes in this dataset
complete_results: np.array - holds results for each iteration of
experiment
loss: The value of the loss from the current epoch
per_epoch_pred: Combined batch outputs and labels for record keeping
f_score_average: The type of averaging to be used fro the F1-Score (
Macro, Micro, or None
Output
complete_results: np.array - holds results for each iteration of
experiment
per_epoch_pred: Combined results of batch outputs and labels for
current epoch
"""
if type(batch_output) is not np.ndarray:
batch_output = batch_output.data.cpu().numpy()
batch_labels = batch_labels.data.cpu().numpy()
if len(batch_output.shape) == 1:
batch_output = batch_output.reshape(-1, 1)
if len(batch_labels.shape) == 1:
batch_labels = batch_labels.reshape(-1, 1)
if initial_condition:
per_epoch_pred = np.hstack((batch_output, batch_labels))
else:
temp_stack = np.hstack((batch_output, batch_labels))
per_epoch_pred = np.vstack((per_epoch_pred, temp_stack))
prediction = np.round(batch_output)
prediction = prediction.reshape(-1)
if len(batch_labels.shape) > 1:
batch_labels = batch_labels.reshape(-1)
if batch_labels.dtype == 'float32':
batch_labels = batch_labels.astype(np.long)
acc, fscore, tn_fp_fn_tp = calculate_accuracy(batch_labels,
prediction,
num_of_classes,
f_score_average)
complete_results[0:2] += acc
complete_results[2:8] += np.array(fscore[0:3]).reshape(1, -1)[0]
complete_results[10] += loss
complete_results[11:15] += tn_fp_fn_tp
return complete_results, per_epoch_pred
def print_log_results(epoch, results, data_type):
"""
Used to print/log results after every epoch
Inputs
epoch: int - The current epoch
results: numpy.array - The current results
data_type: str - Set to train, val, or test
"""
print('\n', config_dataset.SEPARATOR)
print(f"{data_type} accuracy at epoch: {epoch}\n{data_type} Accuracy: Mean:"
f" {np.round(results[8], 3)} - {np.round(results[0:2], 3)}, "
f"F1_Score: Mean: {np.round(results[9], 3)} -"
f" {np.round(results[6:8], 3)}, Loss: {np.round(results[10], 3)}")
print(config_dataset.SEPARATOR, '\n')
main_logger.info(f"\n{config_dataset.SEPARATOR}{config_dataset.SEPARATOR}")
main_logger.info(f"{data_type} accuracy at epoch: {epoch}\n{data_type} "
f"Accuracy: Mean: {np.round(results[8], 3)} -"
f" {np.round(results[0:2], 3)}, F1_Score: Mean:"
f" {np.round(results[9], 3)},"
f" {np.round(results[6:8], 3)}, Loss:"
f" {np.round(results[10], 3)}")
main_logger.info(f"{config_dataset.SEPARATOR}{config_dataset.SEPARATOR}\n")
def final_organisation(scores, train_pred, val_pred, df, patience, epoch,
workspace_files_dir, data_saver):
"""
Records final information with the logger such as the best scores for
training and validation and saves/copies files from the current
experiment into the saved model directory for future analysis. The
complete results to the current epoch are saved for checkpoints or future
analysis.
Copys the current directory to the current experiment dir but only copies
over the current main.py and config.py files in case multiple are present
due to multiple experiments being run
Inputs
scores: list - The best scores from the training and validation results
train_pred: numpy.array - Record of the complete outputs of the
network for every epoch
val_pred: numpy.array - Record of the complete outputs of the
network for every epoch
df: pandas.dataframe - The complete results for every epoch
patience: int - Used to record if early stopping was implemented
epoch: int - The current epoch
workspace_files_dir: str - Location of the programme code
"""
main_logger.info(f"Best epoch at: {scores[-1]}")
main_logger.info(f"Best Train Acc: {scores[1]}\nBest Train Fscore:"
f" {scores[4]}\nBest Train Loss: {scores[7]}")
if validate:
main_logger.info(f"Best Val "
f"Acc: {scores[8]}\nBest Val Fscore: {scores[11]}\nBest "
f"Val Loss: {scores[14]}")
main_logger.info(f"\nscores: {scores[1:-1]}")
if epoch == final_iteration:
main_logger.info(f"System will exit as the total number of "
f"epochs has been reached {final_iteration}")
else:
main_logger.info(f"System will exit as the validation loss "
f"has not improved for {patience} epochs")
print(f"System will exit as the validation loss has not "
"improved for {patience} epochs")
util.save_model_outputs(model_dir,
df,
train_pred,
val_pred,
scores,
data_saver)
copy_tree(workspace_files_dir, current_dir+'/daic')
dirs = os.listdir(workspace_files_dir)
current_main = 'main' + str(position) + '.py'
mains = [d for d in dirs if 'main' in d and d != current_main]
current_config = 'config_' + str(position) + '.py'
nest = 'exp_run'
dirs = os.listdir(os.path.join(workspace_files_dir, nest))
configs = [d for d in dirs if 'config_' in d and d != current_config]
del configs[configs.index('config_dataset.py')]
for m in mains:
os.remove(os.path.join(current_dir, 'daic', m))
for c in configs:
os.remove(os.path.join(current_dir, 'daic', nest, c))
def reduce_learning_rate(optimizer):
"""
Reduce the learning rate of the optimiser for training
Input
optimiser: obj - The optimiser setup at the start of the experiment
"""
learning_rate_reducer = 0.9
for param_group in optimizer.param_groups:
print('Reducing Learning rate from: ', param_group['lr'],
' to ', param_group['lr'] * learning_rate_reducer)
main_logger.info(f"Reducing Learning rate from: "
f"{param_group['lr']}, to "
f"{param_group['lr'] * learning_rate_reducer}")
param_group['lr'] *= learning_rate_reducer
def reproducibility(chosen_seed):
"""
The is required for reproducible experimentation. It sets the random
generators for the different libraries used to a specific, user chosen
seed.
Input
chosen_seed: int - The seed chosen for this experiment
"""
torch.manual_seed(chosen_seed)
torch.cuda.manual_seed_all(chosen_seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(chosen_seed)
random.seed(chosen_seed)
def get_output_from_model(model, data):
"""
Pushes the batched data to the user specified neural network. The output
is pushed back to the CPU if GPU is being used for training.
Inputs:
model: obj - the neural network for experimentation
data: Data to be pushed to the model
Output
output: The output of the model from the input batch data
"""
current_data = mu.create_tensor_data(data,
cuda)
output = model(current_data)
if cuda:
output = output.cpu()
return output
def begin_evaluation(mode, epoch, reset, iteration, iteration_epoch):
"""
Determines whether to start the validation processing. This is determined
by the a change in epoch and reset
Inputs
mode: str - Is the mode in epoch selection or iteration selection
epoch: int - The current epoch of the experiment
reset: Bool - True if the end of a training phase has occurred
iteration: int - The current iteration of the experiment
iteration_epoch: int - The number of iterations equivalent to the
number of epochs if it were in epoch mode
Output
Bool: True if validation set should be processed
"""
if mode == 'epoch':
if epoch > 0 and reset:
return True
elif mode == 'iteration':
it = iteration + 1
if it % iteration_epoch == 0 and iteration > 0:
return True
elif mode is None:
print('Wrong Mode Selected. Choose either epoch or iteration in the '
'config file.')
print('The program will now exit')
sys.exit()
def calculate_time(start_time, end_time, mode_label, main_logger, placeholder=0,
iteration=0):
"""
Stores the time it took for the current experimental iteration and saves
it to the log
Inputs:
start_time: value of timer when started
end_time: value of timer when stopped
mode_label: 'train', 'dev', or 'test'
main_logger: log to retain useful information
placeholder: used in place of the current epoch
iteration: the current training iteration
"""
calc_time = end_time - start_time
if mode_label == 'train':
print(f"Iteration: {iteration}\nTime taken for {mode_label}:"
f" {calc_time:.2f}s")
main_logger.info(f"Time taken for {mode_label}: {calc_time:.2f}s "
f"at iteration: {iteration}, epoch: {placeholder}")
else:
print(f"\nTime taken to evaluate {mode_label}: {calc_time:.2f}s")
main_logger.info(f"Time taken to evaluate {mode_label}:"
f" {calc_time:.2f}s")
def find_batch_weights(folders, weights):
"""
Finds the corresponding weight for the folders in the current batch,
if weights are not used as specified by config file, set the weights to '1'
Inputs:
folders: The folders in the current batch
weights: Dictionary, Key is Folder, Value is corresponding weight
Outputs:
batch_weights: Weights w.r.t. folder for the current batch
"""
batch_weights = torch.ones(folders.shape[0])
use_weights = config.EXPERIMENT_DETAILS['CLASS_WEIGHTS'] or \
config.EXPERIMENT_DETAILS['USE_GENDER_WEIGHTS']
for indx, folder in enumerate(folders):
if use_weights:
batch_weights[indx] = weights[folder]
else:
batch_weights[indx] = 1
return batch_weights.reshape(-1, 1)
def bookeeping():
"""
Loads the best results from all experiment run-throughs and stores them
together in on variable
Outputs:
final_results: Array of the best results from all experiment
run-throughs
"""
files = [os.path.join(current_dir, 'model', str(f), 'best_scores.pickle')
for f in range(1, exp_runthrough+1)]
final_results = np.zeros((exp_runthrough, 14))
for f in range(len(files)):
with open(files[f], 'rb') as file:
data = pickle.load(file)
current_model_dir = os.path.join(current_dir, 'model', str(f+1))
if data[0] == 0:
pass
else:
path = os.path.join(current_model_dir,
'md_'+str(data[-1])+'_epochs.pth')
mod_paths = [os.path.join(current_model_dir, l) for l in os.listdir(
current_model_dir) if 'md_' in l]
del mod_paths[mod_paths.index(path)]
for m in mod_paths:
os.remove(m)
final_results[f, :] = data[0:-1]
return final_results
def train(model, workspace_files_dir):
"""