/
training.py
2003 lines (1630 loc) · 72.2 KB
/
training.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 os
import matplotlib.pyplot as plt
import numpy as np
import sails
import torch
import random
import pickle
from copy import deepcopy
from scipy import signal
from scipy.io import savemat
from scipy.fft import rfft, irfft
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from torch.nn import MSELoss, DataParallel
from torch.nn.parallel import DistributedDataParallel
from torch.optim import Adam
from loss import Loss
from classifiers_linear import LDA, LDA_average_trials
class Experiment:
def __init__(self, args, dataset=None, gpu_id=None):
'''
Initialize model and dataset using an Args object.
'''
self.args = args
self.loss = Loss()
self.val_losses = []
self.train_losses = []
self.initialize_amp()
self.set_device_and_gpu(gpu_id)
self.fix_random_seed()
self.create_result_directory()
self.save_args_object()
self.initialize_dataset(dataset)
self.initialize_model()
self.print_model_parameters()
self.use_data_parallel(gpu_id)
print(f'Experiment initialized on GPU {self.gpu_id}', flush=True)
def initialize_amp(self):
if not hasattr(self.args, 'amp'):
self.args.amp = False
elif self.args.amp:
print('Using automatic mixed precision.', flush=True)
def set_device_and_gpu(self, gpu_id):
self.gpu_id = 0 if gpu_id is None else gpu_id
self.args.gpu_id = self.gpu_id
self.args.num_gpus = 1
self.device = torch.device('cuda')
if gpu_id is not None:
self.args.num_gpus = torch.cuda.device_count()
self.device = torch.device(f'cuda:{gpu_id}')
if gpu_id == 0:
print(f'Number of GPUs: {self.args.num_gpus}', flush=True)
self.args.device = self.device
def fix_random_seed(self):
if self.args.fix_seed:
torch.manual_seed(42)
np.random.seed(42)
random.seed(42)
def create_result_directory(self):
if os.path.isdir(self.args.result_dir):
print('Result directory already exists, writing to it.',
flush=True)
else:
os.makedirs(self.args.result_dir, exist_ok=True)
print('New result directory created.', flush=True)
print(self.args.result_dir, flush=True)
def save_args_object(self):
path = os.path.join(self.args.result_dir, 'args_saved.py')
os.system(f'cp {self.args.name} {path}')
def initialize_dataset(self, dataset):
if dataset is not None:
self.dataset = dataset
elif self.args.load_dataset:
self.dataset = self.args.dataset(self.args)
print('Dataset initialized.', flush=True)
def initialize_model(self):
if self.args.load_model:
self.load_model()
else:
self.create_model()
def load_model(self):
if 'model' in self.args.load_model:
self.model_path = self.args.load_model
else:
self.model_path = os.path.join(self.args.load_model, 'model.pt')
try:
self.model = torch.load(self.model_path)
self.model.loaded(self.args)
self.model.to(self.device)
except (AttributeError, RuntimeError):
self.model = pickle.load(open(self.model_path, 'rb'))
self.model.loaded(self.args)
self.model_path = os.path.join(self.args.result_dir, 'model.pt')
print('Model loaded from file.', flush=True)
def create_model(self):
self.model_path = os.path.join(self.args.result_dir, 'model.pt')
if self.args.from_pretrained:
self.model = self.args.model.from_pretrained(self.args)
else:
self.model = self.args.model(self.args)
try:
self.model = self.model.to(self.device)
print('Model initialized with cuda.', flush=True)
except (AttributeError, RuntimeError):
print('Model initialized without cuda.')
def print_model_parameters(self):
try:
parameters = [param.numel() for param in self.model.parameters()]
print('Number of parameters: ', sum(parameters), flush=True)
except AttributeError:
print("Can't calculate number of parameters.", flush=True)
def use_data_parallel(self, gpu_id):
if gpu_id is not None:
self.ddp = DistributedDataParallel(self.model, device_ids=[gpu_id])
self.model = self.ddp.module
def initialize_optimizer(self, model):
params = filter(lambda p: p.requires_grad, model.parameters())
optimizer = Adam(params,
lr=self.args.learning_rate,
weight_decay=self.args.alpha_norm)
return optimizer
def initialize_scheduler(self, optimizer):
scheduler = None
if self.args.anneal_lr:
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
optimizer, T_max=self.dataset.train_batches)
return scheduler
def process_batch(self, batch, sid, bid, optimizer, scaler):
if not isinstance(batch, list):
batch = [batch]
sid = [sid]
for subbatch, subsid in zip(batch, sid):
if self.args.amp:
with torch.autocast(device_type='cuda',
dtype=torch.float16):
losses, _, _ = self.model.loss(
subbatch, bid, subsid, train=True)
# find the optimization loss
optkey = [key for key in losses if 'optloss' in key]
scaler.scale(losses[optkey[0]]).backward()
scaler.step(optimizer)
scaler.update()
else:
losses, _, _ = self.model.loss(
subbatch, bid, subsid, train=True)
optkey = [key for key in losses if 'optloss' in key]
losses[optkey[0]].backward()
optimizer.step()
optimizer.zero_grad(set_to_none=True)
losses = self.loss.append(losses)
def train_epoch(self, model, optimizer, scaler, scheduler):
model.train()
self.loss.dict = {}
for i in range(self.dataset.train_batches):
batch, sid = self.dataset.get_train_batch(i)
if self.is_empty_batch(batch) or batch is None:
break
self.process_batch(batch, sid, i, optimizer, scaler)
if scheduler is not None:
scheduler.step()
def save_initial_model(self):
path = os.path.join(self.args.result_dir, 'model_init.pt')
torch.save(self.model, path, pickle_protocol=4)
print('Model saved to result directory.', flush=True)
def is_empty_batch(self, batch):
try:
if batch.shape[0] < 1:
return True
except AttributeError:
pass
return False
def print_and_save_train_losses(self):
losses = self.loss.print('trainloss', gpu_id=self.gpu_id)
self.train_losses.append([losses[k] for k in losses])
def validate_and_save(self, model, epoch, best_val):
losses = self.evaluate(model)
loss = [losses[k] for k in losses if 'saveloss' in k]
losses = [losses[k] for k in losses if 'saveloss' not in k]
self.val_losses.append(losses)
if loss[0] < best_val:
if self.gpu_id == 0:
best_val = loss[0]
torch.save(self.model, self.model_path, pickle_protocol=4)
print('Validation loss improved, model saved.', flush=True)
self.testing(model)
if self.gpu_id == 0:
self.save_epoch_model()
if self.args.save_curves:
self.save_curves()
return best_val
def save_epoch_model(self):
path = self.model_path.strip('.pt') + '_epoch.pt'
torch.save(self.model, path, pickle_protocol=4)
def wrap_up_training(self, model):
if self.args.epochs and self.gpu_id == 0:
path = self.model_path.strip('.pt') + '_end.pt'
torch.save(self.model, path, pickle_protocol=4)
self.model.end()
self.evaluate(model)
self.testing(model)
def train(self):
'''
Main training loop over epochs and training batches.
'''
model = self.ddp if hasattr(self, 'ddp') else self.model
optimizer = self.initialize_optimizer(model)
scaler = torch.cuda.amp.GradScaler()
scheduler = self.initialize_scheduler(optimizer)
print_gpu_info = True
best_val = 1000000
self.evaluate(model)
for epoch in range(self.args.epochs):
# if epoch == 0 and self.gpu_id == 0:
# self.save_initial_model()
self.train_epoch(model, optimizer, scaler, scheduler)
if print_gpu_info and self.gpu_id == 0:
os.system('nvidia-smi')
print_gpu_info = False
if not epoch % self.args.print_freq:
self.print_and_save_train_losses()
if not epoch % self.args.val_freq:
best_val = self.validate_and_save(model, epoch, best_val)
self.wrap_up_training(model)
def eval_batch_iter(self, model, num_batches, batch_func, split):
self.loss.dict = {}
model.eval()
if getattr(self.args, 'recursive_loss', None):
self.model.ds = self.dataset
# loop over test batches
for i in range(num_batches):
batch, sid = batch_func(i)
if batch is None:
break
if not isinstance(batch, list):
batch = [batch]
sid = [sid]
for subbatch, subsid in zip(batch, sid):
if self.args.amp:
with torch.autocast(device_type='cuda',
dtype=torch.float16):
loss, _, _ = self.model.loss(
subbatch, i, subsid, train=False)
else:
loss, _, _ = self.model.loss(
subbatch, i, subsid, train=False)
self.loss.append(loss)
losses = self.loss.print('valloss', gpu_id=self.gpu_id)
# if gpu_id is 0 don't append it to file
path = os.path.join(self.args.result_dir,
f'{split}_loss{self.gpu_id}.txt')
if self.gpu_id == 0:
path = os.path.join(self.args.result_dir, f'{split}_loss.txt')
with open(path, 'w') as f:
f.write(str(losses))
if getattr(self.args, 'recursive_loss', None):
self.model.ds = None
return losses
def testing(self, model):
'''
Evaluate model on the test set.
'''
_ = self.eval_batch_iter(model,
self.dataset.test_batches,
self.dataset.get_test_batch,
'test')
def save_curves(self):
'''
Save train and validation loss plots to file.
'''
val_losses = np.array(self.val_losses)
train_losses = np.array(self.train_losses)
if val_losses.shape[0] > 2:
val_ratio = int((train_losses.shape[0]-1)/(val_losses.shape[0]-1))
val_losses = np.repeat(val_losses, val_ratio, axis=0)
plt.semilogy(train_losses, linewidth=1, label='training losses')
plt.semilogy(val_losses, linewidth=1, label='validation losses')
plt.legend()
path = os.path.join(self.args.result_dir,
f'losses{self.gpu_id}.svg')
if self.gpu_id == 0:
path = os.path.join(self.args.result_dir, 'losses.svg')
plt.savefig(path, format='svg', dpi=1200)
plt.close('all')
def evaluate(self, model):
'''
Evaluate model on the validation dataset.
'''
losses = self.eval_batch_iter(model,
self.dataset.val_batches,
self.dataset.get_val_batch,
'val')
return losses
def classify(self):
self.model.eval()
accs = []
batches, _ = self.dataset.get_val_batch(0)
batch = {'inputs': [], 'targets': [], 'condition': [], 'sid': []}
# loop over validation batches
for i in range(0, batches['sid'].shape[0], self.args.batch_size):
for k in batch.keys():
batch[k] = batches[k][i:i+self.args.batch_size]
acc = self.model.classify(batch)
accs.append(acc.double())
accs = torch.cat(accs, dim=0)
accs = accs.mean(dim=0)
print(accs)
def evaluate_train(self):
'''
Evaluate model on the validation dataset.
'''
self.loss.dict = {}
self.model.eval()
# loop over validation batches
for i in range(self.dataset.train_batches):
batch, sid = self.dataset.get_train_batch(i)
loss, output, target = self.model.loss(batch, i, sid, train=False)
self.loss.append(loss)
self.loss.print('valloss')
def save_validation_subs(self):
'''
Print validation losses separately on each subject's dataset.
'''
self.model.eval()
losses = []
# don't reduce the loss so we can separate it according to subjects
mse = MSELoss(reduction='none').cuda()
# loop over validation batches
for i in range(self.dataset.val_batches):
batch, sid = self.dataset.get_val_batch(i)
loss_dict, _, _ = self.model.loss(
batch, i, sid, train=False, criterion=mse)
loss = [loss_dict[k] for k in loss_dict if 'valcriterion' in k]
loss = loss[0].detach()
losses.append((sid, loss))
sid = torch.cat(tuple([loss[0] for loss in losses]))
loss = torch.cat(tuple([loss[1] for loss in losses]))
path = os.path.join(self.args.result_dir, 'val_loss_subs.txt')
with open(path, 'w') as f:
for i in range(self.args.subjects):
sub_loss = torch.mean(loss[sid == i]).item()
f.write(str(sub_loss) + '\n')
def save_validation_timepoints(self):
'''
Print validation losses separately on each subject's dataset.
'''
self.model.eval()
accs = []
# loop over validation batches
for i in range(self.dataset.val_batches):
batch, sid = self.dataset.get_val_batch(i)
_, _, acc = self.model.loss(batch, i, sid, train=False)
accs.append((batch[:, -2, 0].cpu(), acc.detach().cpu()))
sid = torch.cat(tuple([loss[0] for loss in accs]))
loss = torch.cat(tuple([loss[1] for loss in accs]))
path = os.path.join(self.args.result_dir, 'val_loss_timepoints.txt')
with open(path, 'w') as f:
for i in range(self.args.sample_rate):
time_loss = torch.mean(loss[sid == i]).item()
f.write(str(time_loss) + '\n')
def confusion_matrix(self):
'''
Compute confusion matrix of model predictions and save to file.
'''
_, outputs, targets = self.evaluate()
if outputs is None or targets is None:
return
outputs = outputs.detach().cpu().numpy()
targets = targets.detach().cpu().numpy()
mat = confusion_matrix(targets, outputs)
path = os.path.join(self.args.result_dir, 'confusion_matrix')
np.save(path, mat)
def save_validation_channels(self):
'''
Evaluate model for each channel separately.
Needs an update to work.
'''
self.model.eval()
mse = MSELoss(reduction='none').cuda()
losses = []
outputs = []
for i in range(self.dataset.val_batches):
batch, sid = self.dataset.get_val_batch(i)
loss, output, _, loss2 = self.model.loss(
batch, i, sid, train=False, criterion=mse)
losses.append(torch.mean(loss.detach(), (0, 2)))
outputs.append(output.detach())
loss = torch.mean(torch.stack(tuple(losses)), 0)
one_loss = torch.mean(loss)
outputs = torch.cat(tuple(outputs)).permute(1, 0, 2)
outputs = outputs.reshape(outputs.shape[0], -1)
var = torch.std(outputs, 1)
one_var = torch.std(torch.flatten(outputs))
path = os.path.join(self.args.result_dir, 'val_loss_var.txt')
with open(path, 'w') as f:
f.write(str(one_loss.item()) + '\t' + str(one_var.item()))
path = os.path.join(self.args.result_dir, 'val_loss_ch.txt')
with open(path, 'w') as f:
for i in range(loss.shape[0]):
f.write(str(loss[i].item()) + '\t' + str(var[i].item()))
f.write('\n')
def pca_sensor_loss(self):
'''
Loss between pca and non-pca data.
Needs an update to work.
'''
self.model.eval()
self.loss.dict = {}
mse = MSELoss().cuda()
self.args.num_channels = list(range(128))
self.args.load_data = self.args.load_data2
self.pca_data = self.args.dataset(self.args)
outputs = []
targets = []
for i in range(self.dataset.val_batches):
batch, _ = self.dataset.get_val_batch(i)
batch_pca, _ = self.pca_data.get_val_batch(i)
loss, output, target, loss2 = self.model.loss(
batch_pca, i, _, train=False)
self.loss.append(loss)
outputs.append(output.detach())
targets.append(batch[:, :, -output.shape[2]:])
self.loss.print('Validation loss: ')
outputs = torch.cat(tuple(outputs)).permute(0, 2, 1)
outputs = outputs.reshape(-1, outputs.shape[2]).cpu().numpy()
outputs = self.dataset.pca_model.inverse_transform(outputs)
outputs = torch.Tensor(outputs).cuda()
targets = torch.cat(tuple(targets)).permute(0, 2, 1)
targets = targets.reshape(-1, outputs.shape[1])
loss = mse(outputs, targets)
print(loss.item())
def lda_baseline(self,
filewrite=True,
run_test=True,
save_model=True,
reinit=True):
'''
Train a separate linear model across time windows.
'''
hw = self.args.halfwin
times = self.dataset.x_test_t.shape[2]
train_accs = []
val_accs = []
test_accs = []
print('Val data shape: ', self.dataset.x_val_t.shape)
if isinstance(self.model, LDA_average_trials):
times = times//4
for i in range(hw, times-hw+1):
# select input slice
x_t = self.dataset.x_train_t.clone()
x_v = self.dataset.x_val_t.clone()
end = hw-1 if self.args.halfwin_uneven else hw
# train model on a specific time window
acc, _, _ = self.model.run(x_t,
x_v,
(i-hw, i+end),
sid_train=self.dataset.sub_id['train'],
sid_val=self.dataset.sub_id['val'])
print(acc)
val_accs.append(str(acc))
if run_test:
acc, _, _ = self.model.eval(
x_t, (i-hw, i+end), sid=self.dataset.sub_id['train'])
train_accs.append(str(acc))
x_t = self.dataset.x_test_t.clone()
acc, _, _ = self.model.eval(
x_t, (i-hw, i+end), sid=self.dataset.sub_id['test'])
test_accs.append(str(acc))
if save_model:
# save each model
with open(self.model_path + str(i), 'wb') as file:
pickle.dump(self.model, file)
# re-initialize model
if reinit and i < times-hw:
self.model.init_model()
if filewrite:
path = os.path.join(self.args.result_dir, 'val_loss.txt')
with open(path, 'w') as f:
f.write('\n'.join(val_accs))
path = os.path.join(self.args.result_dir, 'train_loss.txt')
with open(path, 'w') as f:
f.write('\n'.join(train_accs))
path = os.path.join(self.args.result_dir, 'test_loss.txt')
with open(path, 'w') as f:
f.write('\n'.join(test_accs))
return val_accs
def lda_crossval(self):
'''
Loop over subjects in dataset and train lda model in cross-validation.
'''
# copy train and val data
x_train = self.dataset.x_train_t.clone()
train_sid = self.dataset.sub_id['train'].clone()
for i in range(self.args.subjects):
# select i-th subject
self.dataset.x_train_t = x_train[train_sid != i].clone()
self.dataset.x_val_t = x_train[train_sid == i].clone()
self.dataset.x_test_t = self.dataset.x_val_t
self.dataset.sub_id['train'] = train_sid[train_sid != i].clone()
# set correct number of train and val batches
bs = self.args.batch_size
self.dataset.bs['train'] = self.dataset.find_bs(
bs, self.dataset.x_train_t.shape[0])
self.dataset.bs['val'] = self.dataset.find_bs(
bs, self.dataset.x_val_t.shape[0])
self.dataset.bs['test'] = self.dataset.find_bs(
bs, self.dataset.x_test_t.shape[0])
self.dataset.train_batches = int(
self.dataset.x_train_t.shape[0] / self.dataset.bs['train'])
self.dataset.val_batches = int(
self.dataset.x_val_t.shape[0] / self.dataset.bs['val'])
self.dataset.test_batches = int(
self.dataset.x_test_t.shape[0] / self.dataset.bs['test'])
# train model
if isinstance(self.model, LDA):
self.lda_baseline(
filewrite=False, run_test=False, save_model=False)
else:
self.train()
def lda_crossval_pairs(self):
'''
Loop over subjects in dataset and train lda model in cross-validation.
'''
# copy train and val data
x_train = self.dataset.x_train_t.clone()
accs = np.zeros((self.args.subjects, self.args.subjects))
for i in range(self.args.subjects):
# select i-th subject
ids = self.dataset.sub_id['train'] == i
self.dataset.x_train_t = x_train[ids].clone()
self.dataset.x_val_t = x_train[ids].clone()
# train model
self.lda_baseline(filewrite=False,
run_test=False,
save_model=False,
reinit=False)
# evaluate model on all other subjects
for j in range(self.args.subjects):
x_val = x_train[self.dataset.sub_id['train'] == j].clone()
acc, _, _ = self.model.eval(x_val)
accs[i, j] = acc
# save accs
path = os.path.join(self.args.result_dir, 'accs.npy')
np.save(path, accs)
def lda_channel(self):
'''
Train a separate lda_baseline model for each channel.
'''
# copy self.datasset.x
x_train = self.dataset.x_train_t.clone()
x_val = self.dataset.x_val_t.clone()
x_test = self.dataset.x_test_t.clone()
accs = []
num_ch = self.args.num_channels
for ch in range(int(num_ch/3)):
current_chs = [ch*3, ch*3+1, ch*3+2, num_ch]
self.dataset.x_train_t = x_train[:, current_chs, :]
self.dataset.x_val_t = x_val[:, current_chs, :]
self.dataset.x_test_t = x_test[:, current_chs, :]
self.args.num_channels = 3
acc = self.lda_baseline()
accs.append(acc[0])
path = os.path.join(self.args.result_dir, 'val_loss.txt')
with open(path, 'w') as f:
f.write('\n'.join(accs))
def lda_pairwise(self):
'''
Train LDA for pairwise classification.
'''
accuracies = []
nc = self.args.num_classes
chn = self.args.num_channels
x_t = self.dataset.x_train_t.clone()
x_v = self.dataset.x_val_t.clone()
# do a first pass to fit PCA
self.lda_baseline()
for c1 in range(nc):
for c2 in range(c1+1, nc):
# set labels for pairwise classification
c1_inds = x_t[:, chn, 0] == c1
c2_inds = x_t[:, chn, 0] == c2
self.dataset.x_train_t = x_t.clone()
self.dataset.x_train_t[c1_inds, chn, :] = 0
self.dataset.x_train_t[c2_inds, chn, :] = 1
# select trials from these 2 classes
inds = (c1_inds) | (c2_inds)
self.dataset.x_train_t = self.dataset.x_train_t[inds, :, :]
# repeat for validation data
c1_inds = x_v[:, chn, 0] == c1
c2_inds = x_v[:, chn, 0] == c2
self.dataset.x_val_t = x_v.clone()
self.dataset.x_val_t[c1_inds, chn, :] = 0
self.dataset.x_val_t[c2_inds, chn, :] = 1
inds = (c1_inds) | (c2_inds)
self.dataset.x_val_t = self.dataset.x_val_t[inds, :, :]
accs = self.lda_baseline(filewrite=False,
run_test=False,
save_model=False)
accuracies.append(';'.join(accs))
path = os.path.join(self.args.result_dir, 'val_loss.txt')
with open(path, 'w') as f:
f.write('\n'.join(accuracies))
def lda_eval(self):
'''
Evaluate any linear classifier on each subject separately.
'''
path = os.path.join(self.args.result_dir, 'val_loss_subs.txt')
with open(path, 'w') as f:
for i in range(self.args.subjects):
inds = self.dataset.sub_id['val'] == i
x_val = self.dataset.x_val_t[inds, :, :]
acc, _, _ = self.model.eval(x_val)
print(acc)
f.write(str(acc) + '\n')
def lda_eval_train_subs(self):
'''
Evaluate any linear classifier on each subject separately.
'''
path = os.path.join(self.args.result_dir, 'train_loss_subs.txt')
with open(path, 'w') as f:
for i in range(self.args.subjects):
inds = self.dataset.sub_id['train'] == i
x_val = self.dataset.x_train_t[inds, :, :]
acc, _, _ = self.model.eval(x_val)
print(acc)
f.write(str(acc) + '\n')
def lda_eval_train(self):
'''
Evaluate any linear classifier on the train data of another dataset.
'''
self.model.loaded(self.args)
path = os.path.join(self.args.result_dir, 'train.txt')
with open(path, 'w') as f:
x_train = self.dataset.x_train_t
acc, _, _ = self.model.eval(
x_train, sid=self.dataset.sub_id['train'])
print(acc)
f.write(str(acc) + '\n')
def lda_eval_train_ensemble(self):
'''
Run ensemble of individual classifiers on the
train data of another dataset.
'''
# load models
models = []
for path in self.args.load_models:
with open(path, 'rb') as file:
model = pickle.load(file)
model.loaded(self.args)
models.append(model)
path = os.path.join(self.args.result_dir, 'left_out_train.txt')
with open(path, 'w') as f:
x_train = self.dataset.x_train_t
class_probs = []
y_val = None
for model in models:
class_prob, y_val = model.predict(x_train)
class_prob = np.argmax(class_prob, axis=1)
class_probs.append(class_prob)
class_probs = np.array(class_probs)
# majority vote
y_preds = []
for i in range(class_probs.shape[1]):
y_pred = np.argmax(np.bincount(class_probs[:, i]))
y_preds.append(y_pred)
'''
# aggregate probabilities
class_probs = np.mean(class_probs, axis=0)
y_preds = np.argmax(class_probs, axis=1)
'''
y_preds = np.array(y_preds)
acc = np.mean(y_preds == y_val)
print(acc)
f.write(str(acc) + '\n')
def repeat_baseline(self):
'''
Simple baseline that repeats current timestep as prediction for next.
'''
for i in range(self.dataset.val_batches):
batch, sid = self.dataset.get_val_batch(i)
self.loss.append(self.model.repeat_loss(batch))
self.loss.print('valloss')
def AR_analysis(self, params):
'''
Analysie the frequency properties of multivariate AR filters (params)
'''
# TODO: this is individual filters but we might also be interested in
# looking at the sum of filters for a specific output channel
raise NotImplementedError
sr = self.args.sr_data
filters = params.reshape(params.shape[0], -1).transpose()
num_filt = min(filters.shape[0], self.args.kernel_limit)
fig_fir, axs_fir = plt.subplots(num_filt+1, figsize=(15, num_filt*6))
fig_iir, axs_iir = plt.subplots(num_filt+1, figsize=(15, num_filt*6))
for i in range(num_filt):
# frequency spectra as FIR filter
w, h = signal.freqz(b=filters[i], fs=sr, worN=5*sr)
axs_fir[i].plot(w, np.abs(h))
self.plot_freqs(axs_fir[i])
# frequency spectra as IIR filter
filter_coeff = np.append(-1, filters[i])
w, h = signal.freqz(b=1, a=filter_coeff, fs=sr, worN=5*sr)
axs_iir[i].plot(w, np.abs(h))
self.plot_freqs(axs_iir[i])
path = os.path.join(self.args.result_dir, 'AR_FIR.svg')
fig_fir.savefig(path, format='svg', dpi=1200)
plt.close('all')
path = os.path.join(self.args.result_dir, 'AR_IIR.svg')
fig_iir.savefig(path, format='svg', dpi=1200)
plt.close('all')
computation = 'ji,ij->i' if self.args.uni else 'jii,ij->i'
shape = (self.args.num_channels, self.args.generate_length)
data = np.random.normal(0, 1, shape)
# generate in IIR mode
for t in range(params.shape[0], data.shape[1]):
inputs = data[:, t-params.shape[0]:t]
data[:, t] += np.einsum(computation, params, inputs[:, ::-1])
path = os.path.join(self.args.result_dir, 'generatedAR.mat')
savemat(path, {'X': data})
def AR_baseline(self):
'''
Train and validate an either uni or multivariate autoregressive model.
'''
ts = self.args.timesteps
self.AR_order = np.arange(self.args.order + 1)
# prepare data tensors
x_train = self.dataset.x_train[:self.args.num_channels, :]
x_train = x_train.reshape(self.args.num_channels, -1, 1)
x_val = self.dataset.x_val[:self.args.num_channels, :]
outputs = np.zeros((x_val.shape[0], x_val.shape[1], ts))
target = np.zeros((x_val.shape[0], x_val.shape[1], ts))
func = self.AR_uni if self.args.uni else self.AR_multi
outputs, target, filters = func(x_train, x_val, outputs, target, ts)
if self.args.do_anal:
self.AR_analysis(filters)
# save outputs and targets as numpy arrays
path = os.path.join(self.args.result_dir, 'outputs.npy')
np.save(path, outputs)
path = os.path.join(self.args.result_dir, 'target.npy')
np.save(path, target)
outputs = torch.Tensor(outputs).float().cuda()
target = torch.Tensor(target).float().cuda()
# save validation loss and generated variance for all future timesteps
path = os.path.join(self.args.result_dir, 'timestep_AR.txt')
with open(path, 'w') as file:
for i in range(ts):
loss = self.model.ar_loss(outputs[:, :, i], target[:, :, i])
var = np.std(outputs[:, :, i].reshape(-1).cpu().numpy())
file.write(str(loss.item()) + '\t' + str(var) + '\n')
print('AR validation loss ts', i+1, ': ', loss.item(),
' Variance: ', var)
path = os.path.join(self.args.result_dir,
'ts' + str(i) + 'AR.txt')
with open(path, 'w') as f:
for ch in range(self.args.num_channels):
loss = self.model.ar_loss(outputs[ch, :, i],
target[ch, :, i])
out = outputs[ch, :, i].reshape(-1).cpu().numpy()
var = np.std(out)
f.write(str(loss.item()) + '\t' + str(var) + '\n')
def AR_multi(self, x_train, x_val, generated, target, ts, ch='multi'):
'''
Train and validate a multivariate AR model.
'''
# load or train new model
path = os.path.join(self.args.AR_load_path, 'ARch' + ch)
if self.args.save_AR:
model = sails.modelfit.OLSLinearModel.fit_model(x_train,
self.AR_order)
pickle.dump(model, open(path, 'wb'))
else:
model = pickle.load(open(path, 'rb'))
coeff = model.parameters[:, :, 1:]
# generate prediction for each timestep
for t in range(model.order, x_val.shape[1] - ts):
# at each timestep predict in the future recursively up to ts
for i in range(ts):
# true input + generated past so far
concat = (x_val[:, t-model.order+i:t], generated[:, t, :i])
inputs = np.concatenate(concat, axis=1)[:, ::-1]
target[:, t, i] = x_val[:, t+i]
generated[:, t, i] = np.einsum('iij,ij->i', coeff, inputs)
return generated, target, coeff.transpose(2, 0, 1)
def AR_uni(self, x_train, x_val, generated, target, ts):
'''
Train and validate a univariate AR model.
'''
filters = []
# create a separate AR model for each channel.
for ch in range(x_val.shape[0]):
gen, targ, params = self.AR_multi(x_train[ch:ch+1, :, :],
x_val[ch:ch+1, :],
generated[ch:ch+1, :, :],
target[ch:ch+1, :, :],
ts,
str(ch))
generated[ch:ch+1, :, :] = gen
target[ch:ch+1, :, :] = targ
filters.append(params)
filters = np.concatenate(tuple(filters), axis=1)
return generated, target, filters.reshape(-1, x_val.shape[0])
def recursive(self):
'''
Evaluate a trained model for recursive multi-step prediction.
'''
raise NotImplementedError
self.model.eval()