-
Notifications
You must be signed in to change notification settings - Fork 3
/
online_finetuning.py
1381 lines (1060 loc) · 56.4 KB
/
online_finetuning.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
## streaming data + updating prototypes
import time
import numpy as np
import tensorflow as tf
import sys
import pickle
import os
import copy
from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score,accuracy_score
from sklearn import utils
import matplotlib.pyplot as plt
import itertools
import csv
from sklearn.decomposition import PCA
from inc_pca import IncPCA
from sklearn import metrics
from enum import Enum
import librosa.display
import sys
from scipy import stats
import datetime
from scipy.fftpack import dct
import _pickle as cp
import copy
import os
from collections import Counter
import random
from imblearn.over_sampling import SMOTE
from subprocess import call
from models import *
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data
from torch.utils.data import TensorDataset
#os.environ["CUDA_VISIBLE_DEVICES"]="1"
from data_handler import *
import shutil
from prototype_memory import *
from proto_net import *
from utils import *
from losses import *
import argparse
import json
import faulthandler; faulthandler.enable()
def plotCNNStatistics(statistics_path):
statistics_dict = cPickle.load(open(statistics_path, 'rb'))
# Plot
fig, ax = plt.subplots(1, 1, figsize=(15, 8))
lines = []
bal_alpha = 0.3
test_alpha = 1.0
bal_map = np.array([statistics['Trainloss'].cpu().data.numpy() for statistics in statistics_dict['Trainloss']]) # (N, classes_num)
test_map = np.array([statistics['Testloss'] for statistics in statistics_dict['Testloss']]) # (N, classes_num)
test_f1 = np.array([statistics['test_f1'] for statistics in statistics_dict['test_f1']]) # (N, classes_num)
basetrain_map = np.array([statistics['BaseTrainloss'].cpu().data.numpy() for statistics in statistics_dict['BaseTrainloss']])
basetrain_f1 = np.array([statistics['BaseTrain_f1'] for statistics in statistics_dict['BaseTrain_f1']])
line, = ax.plot(bal_map, color='r', alpha=bal_alpha)
line, = ax.plot(test_map, color='r', alpha=test_alpha)
lines.append(line)
ax.grid(color='b', linestyle='solid', linewidth=0.3)
plt.legend(labels=['Training Loss','Testing Loss'], loc=2)
fig, ax = plt.subplots(1, 1, figsize=(15, 8))
line, = ax.plot(test_f1, color='r', alpha=test_alpha)
ax.yaxis.set_ticks(np.arange(0, 1.01, 0.05))
ax.yaxis.set_ticklabels(np.around(np.arange(0, 1.01, 0.05), decimals=2))
plt.ylabel('Test Average Fscore')
fig, ax = plt.subplots(1, 1, figsize=(15, 8))
line, = ax.plot(basetrain_map, color='r', alpha=test_alpha)
plt.ylabel('Base Train Loss')
fig, ax = plt.subplots(1, 1, figsize=(15, 8))
line, = ax.plot(basetrain_f1, color='r', alpha=test_alpha)
ax.yaxis.set_ticks(np.arange(0, 1.01, 0.05))
ax.yaxis.set_ticklabels(np.around(np.arange(0, 1.01, 0.05), decimals=2))
plt.ylabel('Base train Average Fscore')
def plotForgettingScore(statistics_path):
statistics_dict = cPickle.load(open(statistics_path, 'rb'))
# Plot
fig, ax = plt.subplots(1, 1, figsize=(15, 8))
lines = []
bal_alpha = 0.3
test_alpha = 1.0
bal_map = np.array([statistics['Forgetting Score'] for statistics in statistics_dict['ForgettingScore']]) # (N, classes_num)
line, = ax.plot(bal_map, color='r', alpha=bal_alpha)
lines.append(line)
ax.grid(color='b', linestyle='solid', linewidth=0.3)
plt.legend(labels=['Forgetting Score'], loc=2)
parser = argparse.ArgumentParser(description="Offline ProtoNet")
parser.add_argument('--data', default='Opportunity')
parser.add_argument('--baseClasses', type=int, default = 5)
parser.add_argument('--newClasses', type=int, default = 0)
parser.add_argument('--percentage', type=float, default = 1.)
parser.add_argument('--batch_size', type=int, default = 200)
parser.add_argument('--window_length_PAMAP2', type=float, default = 1.)
parser.add_argument('--window_step_PAMAP2', type=float, default = 0.5)
parser.add_argument('--epochs', type=int, default = 100)
parser.add_argument('--support', type=int, default = 10)
parser.add_argument('--online_epochs', type=int, default=1)
parser.add_argument('--random_stream', action='store_true', default=False)
parser.add_argument('--cuda_device', type=str, default='0')
parser.add_argument('--window_length_USC_HAD', type=float, default = 1.)
parser.add_argument('--window_step_USC_HAD', type=float, default = 0.5)
parser.add_argument('--window_length_Skoda', type=int, default=98)
parser.add_argument('--window_step_Skoda', type=int, default=49)
parser.add_argument('--window_length_WISDM', type=float, default=5.)
parser.add_argument('--window_step_WISDM', type=float, default=2.5)
parser.add_argument('--WISDM_device', type=str, default='phone')
parser.add_argument('--window_length_HAPT', type=float, default=2.56)
parser.add_argument('--seed', type=int, default=1)
parser.add_argument('--contrastive_loss', action='store_true', default=False)
parser.add_argument('--margin', type=int, default=1)
params = parser.parse_args()
seed = params.seed
torch.backends.cudnn.deterministic = True
random.seed(seed)
if params.data =='Skoda':
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
else:
torch.manual_seed(1)
torch.cuda.manual_seed(1)
np.random.seed(seed)
os.environ["CUDA_VISIBLE_DEVICES"]=params.cuda_device
if params.data == 'Opportunity':
##################### Opportunity Dataset ##########################
print("Downloading opportunity dataset...")
if not os.path.exists("OpportunityUCIDataset.zip"):
call(
'wget "https://archive.ics.uci.edu/ml/machine-learning-databases/00226/OpportunityUCIDataset.zip"',
shell=True
)
print("Downloading done.\n")
else:
print("Dataset already downloaded. Did not download twice.\n")
print("Extracting...")
if not os.path.exists("oppChallenge_gestures.data"):
from preprocess_Oppdata import generate_data
generate_data("OpportunityUCIDataset.zip", "oppChallenge_gestures.data", "gestures")
print("Extracting successfully done to oppChallenge_gestures.data.")
else:
print("Dataset already extracted. Did not extract twice.\n")
#--------------------------------------------
# Dataset-specific constants and functions
#--------------------------------------------
# Hardcoded number of sensor channels employed in the OPPORTUNITY challenge
NB_SENSOR_CHANNELS = 113
NB_SENSOR_CHANNELS_WITH_FILTERING = 149
# Hardcoded number of classes in the gesture recognition problem
NUM_CLASSES = 18
# Hardcoded length of the sliding window mechanism employed to segment the data
SLIDING_WINDOW_LENGTH =24
# Hardcoded step of the sliding window mechanism employed to segment the data
SLIDING_WINDOW_STEP = int(SLIDING_WINDOW_LENGTH/2)
# Batch Size
BATCH_SIZE = params.batch_size
BATCH_SIZE_VAL = params.batch_size
print("Loading data...")
X_train, y_train, X_test, y_test = load_dataset('oppChallenge_gestures.data')
print(np.shape(y_train))
assert (NB_SENSOR_CHANNELS_WITH_FILTERING == X_train.shape[1] or NB_SENSOR_CHANNELS == X_train.shape[1])
X_train, y_train_segments = rearrange(X_train, y_train.reshape((-1,1)), SLIDING_WINDOW_LENGTH, SLIDING_WINDOW_STEP)
X_test, y_test_segments = rearrange(X_test, y_test.reshape((-1,1)), SLIDING_WINDOW_LENGTH, SLIDING_WINDOW_STEP)
#sys.exit()
# Data is reshaped
X_train = X_train.reshape((-1, SLIDING_WINDOW_LENGTH, NB_SENSOR_CHANNELS)) # for input to Conv1D
X_test = X_test.reshape((-1, SLIDING_WINDOW_LENGTH, NB_SENSOR_CHANNELS)) # for input to Conv1D
print(" ..after sliding and reshaping, train data: inputs {0}, targets {1}".format(X_train.shape, y_train_segments.shape))
print(" ..after sliding and reshaping, test data : inputs {0}, targets {1}".format(X_test.shape, y_test_segments.shape))
print(np.shape(X_train))
print(Counter(y_train_segments))
# remove null class
X_train = X_train[y_train_segments != 0]
X_test = X_test[y_test_segments != 0]
y_train_segments = y_train_segments[y_train_segments != 0]
y_train_segments = y_train_segments -1
y_test_segments = y_test_segments[y_test_segments != 0]
y_test_segments = y_test_segments - 1
print(Counter(y_train_segments))
classes = np.unique(y_test_segments)
elif params.data == 'PAMAP2':
################ PAMAP2 Dataset #############################
NB_SENSOR_CHANNELS = 52
NUM_CLASSES = 12
SAMPLING_FREQ = 100 # 100Hz
#SLIDING_WINDOW_LENGTH = int(5.12 * SAMPLING_FREQ)
SLIDING_WINDOW_LENGTH = int(params.window_length_PAMAP2*SAMPLING_FREQ)
#SLIDING_WINDOW_STEP = int(1*SAMPLING_FREQ)
SLIDING_WINDOW_STEP = int(params.window_step_PAMAP2*SAMPLING_FREQ)
print("Extracting...")
if not os.path.exists("./PAMAP2_Dataset/PAMAP2_Train_Test_{}_{}_normalized.data".format(SLIDING_WINDOW_LENGTH,SLIDING_WINDOW_STEP)):
print('PAMAP2_Train_Test.data not found. Please run python3 PAMAP2_preprocessing.py to extract data')
raise FileNotFoundError
else:
print("Loading data...")
X_train, y_train_segments, X_test, y_test_segments = load_dataset("./PAMAP2_Dataset/PAMAP2_Train_Test_{}_{}_normalized.data".format(SLIDING_WINDOW_LENGTH,SLIDING_WINDOW_STEP))
print(" ..train data: inputs {0}, targets {1}".format(X_train.shape, y_train_segments.shape))
print(" ..test data : inputs {0}, targets {1}".format(X_test.shape, y_test_segments.shape))
print(Counter(y_train_segments))
classes = np.unique(y_train_segments)
NUM_CLASSES = len(classes)
# Batch Size
BATCH_SIZE = params.batch_size
BATCH_SIZE_VAL = params.batch_size
elif params.data == 'DSADS':
################ DSADS Dataset #############################
NB_SENSOR_CHANNELS =45
NUM_CLASSES = 19
SAMPLING_FREQ = 25 # 100Hz
SLIDING_WINDOW_LENGTH = int(5*SAMPLING_FREQ)
print("Extracting...")
if not os.path.exists("./DSADS_Train_Test_normalized.data"):
print('DSADS_Train_Test_normalized.data not found. Please run python3 DSADS_preprocessing.py to extract data')
raise FileNotFoundError
else:
print("Loading data...")
X_train, y_train_segments, X_test, y_test_segments = load_dataset("./DSADS_Train_Test_normalized.data")
print(" ..train data: inputs {0}, targets {1}".format(X_train.shape, y_train_segments.shape))
print(" ..test data : inputs {0}, targets {1}".format(X_test.shape, y_test_segments.shape))
print(Counter(y_train_segments))
classes = np.unique(y_train_segments)
NUM_CLASSES = len(classes)
# Batch Size
BATCH_SIZE = params.batch_size
BATCH_SIZE_VAL = params.batch_size
elif params.data == 'USC-HAD':
################ DSADS Dataset #############################
NB_SENSOR_CHANNELS =6
NUM_CLASSES = 12
SAMPLING_FREQ = 100 # 100Hz
SLIDING_WINDOW_LENGTH = int(params.window_length_USC_HAD*SAMPLING_FREQ)
#SLIDING_WINDOW_STEP = int(1*SAMPLING_FREQ)
SLIDING_WINDOW_STEP = int(params.window_step_USC_HAD*SAMPLING_FREQ)
print("Extracting...")
if not os.path.exists("./USC-HAD/USC_HAD_Train_Test_{}_{}.data".format(SLIDING_WINDOW_LENGTH,SLIDING_WINDOW_STEP)):
print('USC_HAD_Train_Test not found. Please run python3 USC_HAD_processing.py to extract data')
raise FileNotFoundError
else:
print("Loading data...")
X_train, y_train_segments, X_test, y_test_segments = load_dataset("./USC-HAD/USC_HAD_Train_Test_{}_{}.data".format(SLIDING_WINDOW_LENGTH,SLIDING_WINDOW_STEP))
print(" ..train data: inputs {0}, targets {1}".format(X_train.shape, y_train_segments.shape))
print(" ..test data : inputs {0}, targets {1}".format(X_test.shape, y_test_segments.shape))
print(Counter(y_train_segments))
classes = np.unique(y_train_segments)
NUM_CLASSES = len(classes)
# Batch Size
BATCH_SIZE = params.batch_size
BATCH_SIZE_VAL = params.batch_size
elif params.data == 'Skoda':
################ DSADS Dataset #############################
NB_SENSOR_CHANNELS =30
NUM_CLASSES = 11
#SAMPLING_FREQ = 98 # 100Hz
SLIDING_WINDOW_LENGTH = int(params.window_length_Skoda)
#SLIDING_WINDOW_STEP = int(1*SAMPLING_FREQ)
SLIDING_WINDOW_STEP = int(params.window_step_Skoda)
print("Extracting...")
if not os.path.exists("./Skoda_data/Skoda_Train_Test_{}_{}.data".format(SLIDING_WINDOW_LENGTH,SLIDING_WINDOW_STEP)):
print('Skdoa_Train_Test not found. Please run python3 Skdoa_processing.py to extract data')
raise FileNotFoundError
else:
print("Loading data...")
X_train, y_train_segments, X_test, y_test_segments = load_dataset("./Skoda_data/Skoda_Train_Test_{}_{}.data".format(SLIDING_WINDOW_LENGTH,SLIDING_WINDOW_STEP))
print(" ..train data: inputs {0}, targets {1}".format(X_train.shape, y_train_segments.shape))
print(" ..test data : inputs {0}, targets {1}".format(X_test.shape, y_test_segments.shape))
print(Counter(y_train_segments))
classes = np.unique(y_train_segments)
NUM_CLASSES = len(classes)
# Batch Size
BATCH_SIZE = params.batch_size
BATCH_SIZE_VAL = params.batch_size
elif params.data == 'WISDM':
################ DSADS Dataset #############################
NB_SENSOR_CHANNELS =8
NUM_CLASSES = 18
SAMPLING_FREQ = 20 # 20Hz
SLIDING_WINDOW_LENGTH = int(params.window_length_WISDM*SAMPLING_FREQ)
#SLIDING_WINDOW_STEP = int(1*SAMPLING_FREQ)
SLIDING_WINDOW_STEP = int(params.window_step_WISDM*SAMPLING_FREQ)
print("Extracting...")
if not os.path.exists("./wisdm-dataset/WISDM_{}_Train_Test_{}_{}.data".format(params.WISDM_device,SLIDING_WINDOW_LENGTH,SLIDING_WINDOW_STEP)):
print('WISDM_Train_Test not found. Please run python3 WISDM_processing.py to extract data')
raise FileNotFoundError
else:
print("Loading data...")
X_train, y_train_segments, X_test, y_test_segments = load_dataset("./wisdm-dataset/WISDM_{}_Train_Test_{}_{}_avg.data".format(params.WISDM_device, SLIDING_WINDOW_LENGTH,SLIDING_WINDOW_STEP))
print(" ..train data: inputs {0}, targets {1}".format(X_train.shape, y_train_segments.shape))
print(" ..test data : inputs {0}, targets {1}".format(X_test.shape, y_test_segments.shape))
print(Counter(y_train_segments))
classes = np.unique(y_train_segments)
NUM_CLASSES = len(classes)
# Batch Size
BATCH_SIZE = params.batch_size
BATCH_SIZE_VAL = params.batch_size
elif params.data == 'HAPT':
################ DSADS Dataset #############################
NB_SENSOR_CHANNELS =6
NUM_CLASSES = 12
SAMPLING_FREQ = 50 # 100Hz
SLIDING_WINDOW_LENGTH = int(params.window_length_HAPT*SAMPLING_FREQ)
#SLIDING_WINDOW_STEP = int(1*SAMPLING_FREQ)
SLIDING_WINDOW_STEP = int(SLIDING_WINDOW_LENGTH/2)
print("Extracting...")
if not os.path.exists("./HAPT_data/HAPT_Train_Test_{}_{}.data".format(SLIDING_WINDOW_LENGTH,SLIDING_WINDOW_STEP)):
print('HAPT_Train_Test not found. Please run python3 HAPT_processing.py to extract data')
raise FileNotFoundError
else:
print("Loading data...")
X_train, y_train_segments, X_test, y_test_segments = load_dataset("./HAPT_data/HAPT_Train_Test_{}_{}.data".format(SLIDING_WINDOW_LENGTH,SLIDING_WINDOW_STEP))
print(" ..train data: inputs {0}, targets {1}".format(X_train.shape, y_train_segments.shape))
print(" ..test data : inputs {0}, targets {1}".format(X_test.shape, y_test_segments.shape))
print(Counter(y_train_segments))
classes = np.unique(y_train_segments)
NUM_CLASSES = len(classes)
# Batch Size
BATCH_SIZE = params.batch_size
BATCH_SIZE_VAL = params.batch_size
"""
Get Base Data and Streaming Data
"""
## streaming data
baseClassesNb = params.baseClasses
percentage = params.percentage #.05 # 20%
dataHandler = DataHandler(nb_baseClasses=baseClassesNb, seed=seed, train={'data':X_train,'label':y_train_segments}, ClassPercentage=percentage)
dataHandler.streaming_data(nb_NewClasses=params.newClasses)
baseData = copy.deepcopy(dataHandler.getBaseData())
baseClasses = np.unique(baseData['label'])
NewClasses = dataHandler.NewClasses
newClassesNb = len(NewClasses)
mapping = {}
for i in np.arange(baseClassesNb + newClassesNb):
if i >= baseClassesNb:
mapping[NewClasses[i-baseClassesNb]] = i
else:
mapping[baseClasses[i]] = i
for x in range(len(baseData['label'])):
baseData['label'][x] = mapping[baseData['label'][x]]
print(mapping)
## select base classes in test data
X_test_select = []
y_test_select = []
for c in baseClasses:
d,l = X_test[y_test_segments == c,:], y_test_segments[y_test_segments == c]
X_test_select.extend(d)
y_test_select.extend(l)
for x in range(len(y_test_select)):
y_test_select[x] = mapping[y_test_select[x]]
## select new classes in test data
X_test_newClasses = []
y_test_newClasses = []
for c in NewClasses:
d,l = X_test[y_test_segments == c,:], y_test_segments[y_test_segments == c]
X_test_newClasses.extend(d)
y_test_newClasses.extend(l)
for x in range(len(y_test_newClasses)):
y_test_newClasses[x] = mapping[y_test_newClasses[x]]
y_train = tf.keras.utils.to_categorical(baseData['label'], num_classes=baseClassesNb, dtype='int32')
y_test = tf.keras.utils.to_categorical(y_test_select, num_classes=baseClassesNb, dtype='int32')
y_test_newClasses_cat = tf.keras.utils.to_categorical(y_test_newClasses, num_classes=baseClassesNb + newClassesNb, dtype='int32')
#model = InceptionNN(NUM_CLASSES)
extractor = DeepConvLSTM(n_classes=len(np.unique(baseData['label'])), NB_SENSOR_CHANNELS = NB_SENSOR_CHANNELS, SLIDING_WINDOW_LENGTH = SLIDING_WINDOW_LENGTH)
model = ProtoNet(extractor,128,baseClassesNb+newClassesNb)
if torch.cuda.is_available():
model.cuda()
torch.backends.cudnn.deterministic = True
random.seed(seed)
if params.data =='Skoda':
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
else:
torch.manual_seed(1)
torch.cuda.manual_seed(1)
np.random.seed(seed)
# Statistics
statistics_path = './statistics/OnlineProtoNet_DeepConvLSTM_{}_baseClasses_{}_percentage_{}_online_epochs_{}_random_stream_{}.pkl'.format(params.data, params.baseClasses, params.percentage, params.online_epochs, params.random_stream)
forgetting_path = './forgetting_score/OnlineFinetuning_DeepConvLSTM_{}_baseClasses_{}_percentage_{}_online_epochs_{}_random_stream_{}.pkl'.format(params.data, params.baseClasses, params.percentage, params.online_epochs, params.random_stream)
if not os.path.exists(os.path.dirname(statistics_path)):
os.makedirs(os.path.dirname(statistics_path))
statistics_container = StatisticsContainer(statistics_path)
if not os.path.exists(os.path.dirname(forgetting_path)):
os.makedirs(os.path.dirname(forgetting_path))
forgetting_container = ForgettingContainer(forgetting_path)
## pretrain base model
x_train_tensor = torch.from_numpy(np.array(baseData['data'])).float()
y_train_tensor = torch.from_numpy(np.array(y_train)).float()
x_test_tensor = torch.from_numpy(np.array(X_test_select)).float()
x_test_newclasses_tensor = torch.from_numpy(np.array(X_test_newClasses)).float()
y_test_tensor = torch.from_numpy(np.array(y_test)).float()
y_test_newClasses_tensor = torch.from_numpy(np.array(y_test_newClasses_cat)).float()
train_data = TensorDataset(x_train_tensor, y_train_tensor)
test_data = TensorDataset(x_test_tensor, y_test_tensor)
test_newClasses_data = TensorDataset(x_test_newclasses_tensor, y_test_newClasses_tensor)
train_loader = torch.utils.data.DataLoader(dataset=train_data,
batch_size=BATCH_SIZE,
num_workers=1, pin_memory=False, shuffle = True,drop_last=False)
test_loader = torch.utils.data.DataLoader(dataset=test_data,
batch_size=BATCH_SIZE_VAL,
num_workers=1, pin_memory=False, shuffle = True,drop_last=False)
if newClassesNb > 1:
test_newClasses_loader = torch.utils.data.DataLoader(dataset=test_newClasses_data,
batch_size=BATCH_SIZE_VAL,
num_workers=1, pin_memory=False, shuffle = True,drop_last=False)
optimizer = optim.Adam(model.parameters(), lr=1e-3,betas=(0.9, 0.999), eps=1e-08, weight_decay=0., amsgrad=True)
#optimizer = optim.SGD(model.parameters(), lr=1e-3)
if params.contrastive_loss:
ContrastiveLoss = OnlineContrastiveLoss(model, PairSelector(balance=False), margin=params.margin)
n_epochs = params.epochs
n_support = params.support ## HARD CODED
iteration = 0
for epoch in range(n_epochs):
model.train()
running_loss = 0.0
n_steps = 0
for d in train_loader:
# get the inputs; data is a list of [inputs, labels]
inputs, labels = d
x_support, y_support, x_query, y_query = extract_sample(len(np.unique(np.argmax(labels,axis=1))), n_support, n_support, inputs, np.argmax(labels, axis = 1), seed = iteration,shuffle=True)
h = model.extractor.init_hidden(len(x_support))
query_h = model.extractor.init_hidden(len(x_query))
#print(y_support)
y_support = tf.keras.utils.to_categorical(y_support, num_classes=baseClassesNb, dtype='int32')
#print(y_support)
#sys.exit()
y_support = torch.from_numpy(y_support).float().cuda()
x_support = x_support.cuda()
x_query = x_query.cuda()
y_query = tf.keras.utils.to_categorical(y_query, num_classes=baseClassesNb, dtype='int32')
y_query = torch.from_numpy(y_query).float().cuda()
h = tuple([each.data for each in h])
query_h = tuple([each.data for each in query_h])
# zero the parameter gradients
optimizer.zero_grad()
log_p,h = model.forward_offline(x_support,y_support,x_query,h,query_h)
#print(np.argmax(log_p.data.cpu().numpy(),axis=1),np.argmax(y_query.data.cpu().numpy(),axis=1))
loss = F.binary_cross_entropy(log_p, y_query)
if params.contrastive_loss:
_,_,z_query = model.extractor(x_query,query_h, x_query.size(0))
loss += ContrastiveLoss(z_query, y_query)
running_loss += loss
loss.backward()
optimizer.step()
n_steps += 1
print('[Epoch %d]' % (epoch + 1))
epoch_train_loss = running_loss / n_steps
print('Train loss: {}'.format(epoch_train_loss))
eval_output = []
true_output = []
test_output = []
true_test_output = []
model.eval()
with torch.no_grad():
print('TESTING !!')
running_test_loss = 0.0
n_steps = 0
for d in test_loader:
inputs, labels = d
val_h = model.extractor.init_hidden(len(inputs))
support_h = model.extractor.init_hidden(len(x_train_tensor))
####### Testing without selecting random support ########################################################################
#inputs , labels = order_classes(inputs,np.argmax(labels, axis = 1),iteration)
#labels = tf.keras.utils.to_categorical(labels,num_classes=baseClassesNb,dtype='int32')
#labels = torch.from_numpy(labels).float()
inputs = inputs.cuda()
#labels = torch.from_numpy(tf.keras.utils.to_categorical(np.argmax(labels, axis = 1), num_classes=baseClassesNb, dtype='int32')).float()
labels = labels.cuda()
val_h = tuple([each.data for each in val_h])
support_h = tuple([each.data for each in support_h])
#print(np.shape(x_support), np.shape(x_query))
# zero the parameter gradients
#print(np.shape(labels))
#log_p,val_h = model.forward_offline(inputs,labels,inputs,support_h,val_h)
log_p,val_h = model.forward_inference(x_train_tensor.cuda(),y_train_tensor.cuda(),inputs,support_h,val_h)
#print(log_p, y_query)
#clipwise_output = model(inputs,inputs.shape[0])
#print("....",np.shape(clipwise_output))
#clipwise_output = outputs['clipwise_output']
test_loss = F.binary_cross_entropy(log_p, labels)
test_output.append(log_p.data.cpu().numpy())
true_test_output.append(labels.data.cpu().numpy())
running_test_loss += test_loss
n_steps += 1
##########################################################################################################################
test_oo = np.argmax(np.vstack(test_output), axis = 1)
true_test_oo = np.argmax(np.vstack(true_test_output), axis = 1)
accuracy = metrics.accuracy_score(true_test_oo, test_oo)
precision, recall, fscore,_ = metrics.precision_recall_fscore_support(true_test_oo, test_oo, labels=np.unique(true_test_oo), average='macro')
try:
auc_test = metrics.roc_auc_score(np.vstack(true_test_output), np.vstack(test_output), labels=np.unique(true_test_oo), average='macro')
except ValueError:
auc_test = None
epoch_test_loss = running_test_loss / n_steps
print('Test loss: {}'.format(epoch_test_loss))
print('TEST average_precision: {}'.format(precision))
print('TEST average f1: {}'.format(fscore))
print('TEST average recall: {}'.format(recall))
print('TEST auc: {}'.format(accuracy))
trainLoss = {'Trainloss': epoch_train_loss}
#trainLoss = {'Trainloss': loss}
statistics_container.append(iteration, trainLoss, data_type='Trainloss')
testLoss = {'Testloss': epoch_test_loss}
#testLoss = {'Testloss': test_loss}
statistics_container.append(iteration, testLoss, data_type='Testloss')
test_f1 = {'test_f1':fscore}
statistics_container.append(iteration, test_f1, data_type='test_f1')
statistics_container.dump()
iteration += 1
#plotCNNStatistics(statistics_path)
model.eval()
#model.extractor.eval()
embeddings_list = dict()
embeddings_list['embeddings'] = []
embeddings_list['labels'] = []
with torch.no_grad():
iteration = 0
for tr_input, y_tr in train_loader:
tr_h = model.extractor.init_hidden(len(tr_input))
# tr_input , y_tr = order_classes(tr_input,np.argmax(y_tr, axis = 1),iteration)
# y_tr = tf.keras.utils.to_categorical(y_tr,num_classes=baseClassesNb,dtype='int32')
# y_tr = torch.from_numpy(y_tr).float()
tr_input = tr_input.cuda()
#labels = torch.from_numpy(tf.keras.utils.to_categorical(np.argmax(labels, axis = 1), num_classes=baseClassesNb, dtype='int32')).float()
y_tr = y_tr.cuda()
tr_h = tuple(each.data for each in tr_h)
_,tr_h, embeddings = model.extractor(tr_input, tr_h, len(y_tr))
embeddings_list['embeddings'].extend(embeddings.data.cpu().numpy())
embeddings_list['labels'].extend(y_tr.data.cpu().numpy())
labels = torch.from_numpy(np.array(embeddings_list['labels'])).float()
z_proto = torch.from_numpy(np.array(embeddings_list['embeddings'])).float().cuda()
labels = labels.cuda()
model.update_protoMemory(z_proto,labels)
## save prototypes
json_dict = copy.deepcopy(model.memory.prototypes)
for key in model.memory.prototypes.keys():
print(key, type(key))
if type(key) is not str:
json_dict[str(key)] = str(json_dict[key])
del json_dict[key]
with open("./prototypes_json/Debugging_{}_Data_OfflineShuffle_ModelAdaptation.json".format(percentage), "w") as write_file:
str_ = json.dumps(json_dict)
write_file.write(str_)
##ge get train performance on base training data
model.eval()
eval_output = []
true_output = []
train_output = []
true_train_output = []
with torch.no_grad():
print('Getting Performance on Base Data !!')
running_train_loss = 0.0
n_steps = 0
for d in train_loader:
inputs, labels = d
val_h = model.extractor.init_hidden(len(inputs))
####### Testing without selecting random support ########################################################################
#inputs , labels = order_classes(inputs,np.argmax(labels, axis = 1),iteration)
#labels = tf.keras.utils.to_categorical(labels,num_classes=baseClassesNb,dtype='int32')
#labels = torch.from_numpy(labels).float()
inputs = inputs.cuda()
#labels = torch.from_numpy(tf.keras.utils.to_categorical(np.argmax(labels, axis = 1), num_classes=baseClassesNb, dtype='int32')).float()
labels = labels.cuda()
val_h = tuple([each.data for each in val_h])
#print(np.shape(x_support), np.shape(x_query))
# zero the parameter gradients
#print(np.shape(labels))
#log_p,val_h = model.forward_offline(inputs,labels,inputs,support_h,val_h)
log_p,val_h = model.forward_offline(inputs, labels,inputs,val_h,val_h)
#print(log_p, y_query)
#clipwise_output = model(inputs,inputs.shape[0])
#print("....",np.shape(clipwise_output))
#clipwise_output = outputs['clipwise_output']
train_loss = F.binary_cross_entropy(log_p, labels)
train_output.append(log_p.data.cpu().numpy())
true_train_output.append(labels.data.cpu().numpy())
running_train_loss += train_loss
n_steps += 1
##########################################################################################################################
train_oo = np.argmax(np.vstack(train_output), axis = 1)
true_train_oo = np.argmax(np.vstack(true_train_output), axis = 1)
accuracy = metrics.accuracy_score(true_train_oo, train_oo)
precision, recall, fscore,_ = metrics.precision_recall_fscore_support(true_train_oo, train_oo, labels=np.unique(true_train_oo), average='macro')
try:
auc_test = metrics.roc_auc_score(np.vstack(true_train_output), np.vstack(train_output), labels=np.unique(true_train_oo), average='macro')
except ValueError:
auc_test = None
epoch_train_loss = running_train_loss / n_steps
print("----------------------------------------------------------------------")
print('Base Train loss: {}'.format(epoch_train_loss))
print('Base Train average_precision: {}'.format(precision))
print('Base Train average f1: {}'.format(fscore))
print('Base Train average recall: {}'.format(recall))
print('Base Train auc: {}'.format(accuracy))
print("----------------------------------------------------------------------")
trainLoss = {'BaseTrainloss': epoch_train_loss}
baseTrainF1 = {'BaseTrain_f1': fscore}
#trainLoss = {'Trainloss': loss}
statistics_container.append(iteration, trainLoss, data_type='BaseTrainloss')
statistics_container.append(iteration, baseTrainF1, data_type='BaseTrain_f1')
statistics_container.dump()
C = confusion_matrix(true_train_oo, train_oo)
labels = copy.deepcopy(true_train_oo)
for i in range(len(true_train_oo)):
labels[i] = list(mapping.keys())[true_train_oo[i]]
plt.figure(figsize=(10,10))
plot_confusion_matrix(C, class_list=np.unique(labels), normalize=True, title='Before Streaming Old Classes Predicted Results')
#plotCNNStatistics(statistics_path)
#plt.show()
cm = plt.get_cmap('gist_rainbow')
NUM_COLORS = len(classes)
colors = [cm((1.*i)/NUM_COLORS) for i in np.arange(NUM_COLORS)]
markers=['.', 'x', 'h','1']
## OPPORTUNITY
if params.data == 'Opportunity':
LABELS = ['OpenDoor1', 'OpenDoor2','CloseDoor1','CloseDoor2','OpenFridge','CloseFridge','OpenDishwasher','CloseDishwasher','OpenDrawer1','CloseDrawer1','OpenDrawer2','CloseDrawer2','OpenDrawer3','CloseDrawer3','CleanTable','DrinkFromCup','ToogleSwitch']
elif params.data == 'PAMAP2':
## PAMAP2
LABELS = {1:'lying',2:'sitting',3:'standing',4: 'walking',5: 'running',6: 'cycling',7: 'Nordic walking',9: 'watching TV',10: 'computer work',11: 'car driving', 12: 'ascending stairs',
13:'descending stairs',16: 'vacuum cleaning',17: 'ironing',18: 'folding laundry',19: 'house cleaning',20:'playing soccer',24: 'rope jumping'}
elif params.data == 'DSADS':
LABELS = {1:'sitting',2:'standing',3:'lying on back',4: 'lying on right side',5: 'ascending stairs',6: 'descending stairs',7: 'standing in elevator still',8: 'moving around in elevator',9: 'walking in parking lot',10: 'walking on treadmill w/ speed 4km/h in flat', 11:'walking on treadmill w/ speed 4km/h in 15 deg',12: 'running on treadmill',
13:'exercising on stepper',14: 'exercising on cross trainer',15: 'cycling on exercise bike in horizontal',16: 'cycling on exercise bike in vertical',17: 'rowing',18: 'jumping',19:'playing basketbal'}
elif params.data == 'Skoda':
LABELS = {0: 'null class', 1: 'write on notepad', 2: 'open hood', 3: 'close hood',
4: 'check gaps on the front door', 5: 'open left front door',
6: 'close left front door', 7: 'close both left door', 8: 'check trunk gaps',
9: 'open and close trunk', 10: 'check steering wheel'}
elif params.data =='WISDM':
LABELS = {0:'walking',1:'jogging',2:'stairs',3:'sitting',4:'standing',5:'typing',6:'teeth',7:'soup',8:'chips',9:'pasta',10:'drinking',11:'sandwich',
12:'kicking',14:'catch',15:'dribbling', 16:'writing',17:'clapping',18:'folding'}
elif params.data == 'HAPT':
LABELS = {1:'walking',2:'walking upstairs',3:'walking downstairs',4:'sitting',5:'standing',6:'laying',7:'stand to sit',8:'sit to stand',
9:'sit to lie',10:'lie to sit',11:'stand to lie',12:'lie to stand'}
### starting streaming
N = 20
prototypes_check =copy.deepcopy(list(model.memory.prototypes.values()))
### plot prototypes before updating
pca = IncPCA(n_components=2)
pca.partial_fit(list(model.memory.prototypes.values()))
#prototypes_pca = pca.transform(list(prot_mem.prototypes.values()))
prototypes_pca = pca.transform(list(model.memory.prototypes.values()))
fig, ax = plt.subplots(figsize=(10,10))
# ax.set_xlim(-6,6)
# ax.set_ylim(-6,6)
xdata, ydata = [], []
ln, = plt.plot([],[],'ro')
xdata.extend(prototypes_pca[:,0])
ydata.extend(prototypes_pca[:,1])
annotations= set()
def plt_dynamic(x,y,labels,ax,fig,colors,markers=['.', 'x', 'h','1']):
#print(x,y,labels,x[labels==6],y[labels==6])
for k, col in zip(np.unique(labels),colors):
#print(k,x,y,labels)
xx,yy = x[labels == k], y[labels == k]
ax.plot(xx,yy, 'o',
markerfacecolor=col, markeredgecolor=col,
marker=markers[k%len(markers)],markersize=20)
#add label
if annotate and LABELS[list(mapping.keys())[k]] not in annotations:
annotations.add(LABELS[list(mapping.keys())[k]])
ax.annotate(LABELS[list(mapping.keys())[k]], (xx, yy),
horizontalalignment='center',
verticalalignment='center',
size=10, weight='bold',rotation=45,
color='k')
fig.canvas.draw()
#ytrue = np.array(list(prot_mem.prototypes.keys()), dtype=np.int32)
ytrue = np.array(list(model.memory.prototypes.keys()), dtype=np.int32)
annotate = True
#print(xdata, ydata, ytrue)
plt_dynamic(np.array(xdata), np.array(ydata), ytrue, ax,fig, colors)
plt.title("Prototypes after updating using all training data")
annotate = True
plt.show(block=False)
#val_h = model.extractor.init_hidden(N)
xdata, ydata, ytrue = [], [], []
ll=[]
#optimizer = optim.Adam(model.parameters(), lr=1e-6,betas=(0.9, 0.999), eps=1e-08, weight_decay=0., amsgrad=True)
print("Started Streaming Data ...")
support_set = []
labels_set = []
map_labels = []
counter = 1
#running_loss = 0.0
n_steps = 0
online_epochs = params.online_epochs
embeddings_list = dict()
embeddings_list['embeddings'] = []
embeddings_list['labels'] = []
embx_data, emby_data, embyTrue = [], [], []
max_f1_score = {class_k: 0. for class_k in range(len(baseClasses))}
f1_score_t = {}
while not dataHandler.endOfStream():
#print(counter)
if params.random_stream:
d, l = dataHandler.getNextData()
support_set.append(copy.deepcopy(d))
labels_set.append(copy.deepcopy(l))
map_labels.append(copy.deepcopy(mapping[l]))
else:
d, l = dataHandler.getNextBatch_controlled(N)
support_set = copy.deepcopy(d)
labels_set = copy.deepcopy(l)
map_labels = copy.deepcopy([mapping[ll] for ll in l])
print(np.shape(support_set), np.shape(labels_set), np.shape(map_labels))
model.train()
if not params.random_stream or counter % N == 0:
val_h = model.extractor.init_hidden(len(support_set))
query_h = model.extractor.init_hidden(len(support_set))
support_set = torch.from_numpy(np.array(support_set)).float()
map_labels = tf.keras.utils.to_categorical(map_labels, num_classes=baseClassesNb+newClassesNb, dtype='int32')
map_labels = torch.from_numpy(np.array(map_labels)).float()
#sys.exit()
support_set = support_set.cuda()
map_labels = map_labels.cuda()
val_h = tuple([each.data for each in val_h])
query_h = tuple([each.data for each in query_h])
optimizer.zero_grad()
log_p, val_h,_ = model.forward_online(support_set,map_labels, support_set, val_h,val_h)
#embeddings_list['embeddings'].extend(embds.data.cpu().numpy())
#embeddings_list['labels'].extend(map_labels.data.cpu().numpy())
loss = F.binary_cross_entropy(log_p, map_labels)
#running_loss += loss
loss.backward()
optimizer.step()
for j in range(1, online_epochs):
val_h = model.extractor.init_hidden(len(support_set))
support_set, map_labels, labels_set = utils.shuffle(support_set,map_labels,labels_set, random_state=j)
#sys.exit()
support_set = support_set.cuda()
map_labels = map_labels.cuda()
val_h = tuple([each.data for each in val_h])
optimizer.zero_grad()
log_p, val_h = model.forward_online_QUERY(support_set, val_h)
#embeddings_list['embeddings'].extend(embds.data.cpu().numpy())
#embeddings_list['labels'].extend(map_labels.data.cpu().numpy())
loss = F.binary_cross_entropy(log_p, map_labels)
#running_loss += loss
loss.backward()
optimizer.step()
#model.online_update_prototypes(support_set,map_labels, val_h)
support_set = []
labels_set = []
map_labels = []
eval_output = []
true_output = []
test_output = []
true_test_output = []
#h = model.extractor.init_hidden(n_support*baseClassesNb)
#print(np.shape(val_h[0]))
model.eval()
with torch.no_grad():
iteration = 0
running_test_loss = 0.0
n_test_steps = 0
for d in test_loader: