-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
6279 lines (5822 loc) · 351 KB
/
models.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
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 14 14:35:00 2019
@author: CUI
"""
import os
import gc
import datetime
import numpy as np
import pandas as pd
import random
import itertools
import zipfile
import io
import time
from copy import deepcopy
from tqdm import tqdm
from glob import glob
from natsort import natsorted
import seaborn as sns
import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import TensorBoard, ModelCheckpoint, LambdaCallback
#from keras_tqdm import TQDMCallback
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.ioff()
import matplotlib.gridspec as gridspec
#from mpl_toolkits.axes_grid1 import make_axes_locatable
# from matplotlib.ticker import NullFormatter
from skimage.metrics import structural_similarity as ssim
from libs.pconv_model import PConvUnet
from libs.lstm_model import LSTM
from libs.lstmsimple_model import LSTM as LSTMS
from libs.gru_model import GRU
from libs.grusimple_model import GRU as GRUS
from libs.nbeats_model import NBeats
from dataset.data_process import kinter, forplot_assignement_accuracy, kcentroids_equal, to_kcentroid_seq, chunkdata_for_longpredict, retrieve_traintimeseq, create_labelines_timeseq_dataset, convertdata_for_training, no_cosmic, rescale_data_by_seqs
from featuring.brandon_features import feature_transform, Mg_settings
from sklearn.metrics import confusion_matrix#, ConfusionMatrixDisplay
class_parms = None
from featuring.mts_metrics import NPMtsMetrics
from featuring.class_n2_metrics import tss_hss_all
try:
from main_classify import Settings, update_settings_fromclass
from models_classify import SP_Conv_Dense, create_class_mask
from featuring.center_stat import NPJointCenterStat#, NPCenterStat, CenterStat
from libs.class_pconv_model import NP_CategoricalCrossentropy, NP_BinaryCrossentropy, NP_CategoricalAccuracy, NP_BinaryAccuracy
from libs.countdict3k_acc import NPAccuracyOverTime3D
except:
print("Could not import libraries on centers and classification")
else:
print("successfuly imported libraries on centers and classification")
now = datetime.datetime.now
plt.rcParams.update({'font.size': 44})
plt.rcParams.update({'font.family': 'Cambria'})
def saveCompressed(fh, allow_pickle, **namedict):
with zipfile.ZipFile(fh,
mode="w",
compression=zipfile.ZIP_DEFLATED,
allowZip64=True) as zf:
for k, v in namedict.items():
buf = io.BytesIO()
np.lib.npyio.format.write_array(buf,
np.asanyarray(v),
allow_pickle=allow_pickle)
zf.writestr(k + '.npy',
buf.getvalue())
class SP_PCUNet(object):
def __init__(self, config, classes_and_inclusions_addnoclass=None,
feat_legends=None, manual_mode=True,
change_traindata=False):
if 'n_blocks' in dir(config):
self.n_blocks = config.n_blocks
self.with_features = config.with_features
self.debug = config.debug
self.given_tvt = config.given_tvt
self.model_type = config.model_type
self.with_centerloss = config.with_centerloss
self.epoch = config.epoch
self.batch_size = config.batch_size
self.batch_norm = True
self.learning_rate_BN = config.learning_rate
self.learning_rate_FINE = self.learning_rate_BN/4
self.dataset = config.dataset
self.dataset_address = config.dataset_address
self.train_ratio = config.train_ratio
self.test_ratio = config.test_ratio
self.label_length = config.label_length
self.mask_ratio = .25
self.random_ratio = False
self.labels = config.labels
self.labels = self.labels.split('_')
self.nolabel = None
self.noclass = None
self.test_labels = config.test_labels
self.test_labels = self.test_labels.split('_')
self.name = config.name
self.checkpoint_dir = config.checkpoint_dir
self.logs_dir = config.logs_dir
self.results_dir = config.results_dir
self.train1 = config.train
self.train2 = 100
self.preload_train = config.preload_train
self.testload_FINE = True
self.test = config.test
self.test_ds = config.test_ds
self.test_ds = self.test_ds.split('_')
if 'TE' in self.test_ds:
self.test_ds = self.test_ds + ['TE_%s'%ds for ds in self.test_labels]
if 'TEL' in self.test_ds:
self.test_ds = self.test_ds + ['TEL_%s'%ds for ds in self.test_labels]
self.add_classifier = config.add_classifier
self.classes = config.classes
self.classes_and_inclusions_addnoclass = classes_and_inclusions_addnoclass
self.class_inclusions = config.class_inclusions
self.add_centercount = config.add_centercount
self.predict = config.predict
self.predict_ds = config.predict_ds
self.number_predict = config.number_predict
self.show_res = config.show_res
self.show_dist_polar = config.show_dist_polar
self.backg_color = config.backg_color
self.fig_form = config.fig_form
self.frame_res = config.frame_res
self.coef_diff = 5
self.feat_legends = feat_legends
self.all_labels = list(set(self.labels+self.test_labels))
print('[%s - START] Creating the datasets..'%now().strftime('%d.%m.%Y - %H:%M:%S'))
if self.dataset in ['iris','al','pb']:
self.c_dim = 1
if self.train1 and not(self.preload_train) and not(manual_mode):
data, positions = create_labelines_timeseq_dataset(self.dataset_address, self.labels, self.label_length)
if config.cosmic_to_mean: # V2
data = no_cosmic(data, config.cosmic_t)
# mx = find_max_data(data)
# if mx != 1: # V2
# data = rescale_data(data, mx)
data = rescale_data_by_seqs(data)
self.data_pack = list(zip(data, positions)) # [(data, position)]
# partition by activity {act_lab: list of data}
activities = self.labels
self.data_pack = {a: [e for e in self.data_pack if any([a in str(ee) for ee in e[1]])] for a in activities} # {act: [(data, pos)]}
if self.given_tvt:
self.data_pack = {dt: {a: [e for e in self.data_pack[a] if any([['train', 'valid', 'test'][['TR','VAL','TE'].index(dt)] in str(ee) for ee in e[1]])] for a in self.data_pack} for dt in ['TR','VAL','TE']}# {tvt: {act: [(data, pos), ...]}}
else:
percentages = {a: {f: sum([e[0].shape[0] for e in self.data_pack[a] if f in e[1]]) for f in set([e[1][[a in str(ee) for ee in e[1]].index(True)] for e in self.data_pack[a]])} for a in self.data_pack}
percentages = {a: {f: percentages[a][f]/sum(percentages[a][ff] for ff in percentages[a]) for f in percentages[a]} for a in percentages}
for a in percentages:
events = list(percentages[a].keys())
shuffle = True
attempts = 0
max_attempts = 100
while shuffle and attempts<max_attempts:
random.shuffle(events)
attempts += 1
cumul_left = self.loop_cumul(percentages[a], events, self.train_ratio, attempts==max_attempts-1)
cumul_right = self.loop_cumul(percentages[a], events, self.test_ratio, attempts==max_attempts-1, start='right')
if cumul_left is None or cumul_right is None:
continue
if cumul_right+cumul_left>len(events):
cumul_left -= (cumul_right+cumul_left)-len(events)
assert cumul_left>0, "problem with the partition, train and test overlap, coding issue or too small amount of events"
train_events = events[:cumul_left]
test_events = events[::-1][:cumul_right]
if cumul_left+cumul_right<len(events):
valid_events = [e for e in events if e not in train_events+test_events]
assert len(valid_events)!=0, "problem during the partition, see code"
else:
print("Label %s : No separate event for validation dataset, will use an overlapping part of the training data"%a)
valid_ratio = 1-self.train_ratio-self.test_ratio
valid_events = [e for e in train_events if percentages[a][e]<valid_ratio]
if len(valid_events)!=0:
random.shuffle(valid_events)
cumul_left = self.loop_cumul(percentages[a], valid_events, valid_ratio, False)
valid_events = valid_events[:cumul_left]
else:
valid_events = [train_events[[percentages[a][e] for e in train_events].index(min([percentages[a][e] for e in train_events]))]]
self.data_pack[a] = {
'TR': [e for e in self.data_pack[a] if any(ee in e[1] for ee in train_events)],
'VAL': [e for e in self.data_pack[a] if any(ee in e[1] for ee in valid_events)],
'TE': [e for e in self.data_pack[a] if any(ee in e[1] for ee in test_events)]}# {act: {tvt: [(data, pos)]}}
shuffle = False
assert all(len(lev)>0 for lev in [train_events, test_events, valid_events]) and len([e for e in train_events if e in test_events])==0, "Did not find how to partition data"
del cumul_right, cumul_left, train_events, test_events, valid_events
self.data_pack = {dt: {a: self.data_pack[a][dt] for a in self.data_pack} for dt in ['TR','VAL','TE']}# {tvt: {act: [(data, pos), ...]}}
self.data_pack['TE'] = {
**(self.data_pack['TE']),
**{a: list(zip(*create_labelines_timeseq_dataset(self.dataset_address, [a], self.label_length))) for a in self.test_labels if a not in self.labels}}
self.data_pack = {
**{'_'.join([dt,a]): self.data_pack[dt][a] for dt in self.data_pack for a in self.data_pack[dt]},
'TR': list(itertools.chain(*(self.data_pack['TR'].values()))),
'VAL': list(itertools.chain(*(self.data_pack['VAL'].values()))),
'TE': list(itertools.chain(*(self.data_pack['TE'].values()))),}# [(data, pos)..]
self.data_pack = {k: list(zip(*(self.data_pack[k]))) for k in self.data_pack} # {k: [(data,),(position,)]}
elif not(manual_mode):
print("Loading previous dataset..")
data_info = np.load(os.path.join(self.dataset_adress,'data_longformat.npz'), allow_pickle = True)
keys = [k.replace('data_', '') for k in list(data_info.keys()) if 'data_' in k]
self.data_pack = {k: (data_info['data_'+k], data_info['position_'+k]) for k in keys}
data_info.close()
change_traindata = False
if not(manual_mode):
self.data_train = {k: convertdata_for_training(list(self.data_pack[k][0]), list(self.data_pack[k][1]), self.label_length, self.mask_ratio) for k in self.data_pack}
self.generators = {
k: [AugmentingDataGenerator().flow_from_data(
np.array(self.data_train[k][0]),
np.array(list(zip(*(self.data_train[k][1])))[0]),
self.mask_ratio,
self.random_ratio,
batch_size=self.batch_size
), # 1st is data for model
len(self.data_train[k][0]), # 2nd is length of data
{p:l for p,l in zip(
list(zip(*(self.data_train[k][1])))[0],
[self.label_from_pos(p) for p in list(
zip(*(self.data_train[k][1])))[2]])} # 3rd is dict{pos:lab} info
]for k in self.data_train}
self.generators = {
**self.generators,
'show': [AugmentingDataGenerator().flow_from_data(
np.array(self.data_train['TR'][0])[:self.batch_size],
np.array(list(zip(*(self.data_train['TR'][1])))[0])[:self.batch_size],
self.mask_ratio,
self.random_ratio,
batch_size=self.batch_size
), # 1st is data for model
self.batch_size, # 2nd is length of data
{p:l for p,l in zip(
list(zip(*(self.data_train['TR'][1])))[0],
[self.label_from_pos(p) for p in list(
zip(*(self.data_train['TR'][1])))[2]])} # 3rd is dict{pos:lab} info
]}
self.test_generators = {
k: [AugmentingDataGenerator().flow_from_data(
np.array(self.data_train[k][0]),
np.array(list(zip(*(self.data_train[k][1])))[0]),
self.mask_ratio,
self.random_ratio,
batch_size=self.batch_size,
seed=1
), # 1st is data for model
len(self.data_train[k][0]), # 2nd is length of data
{p:l for p,l in zip(
list(zip(*(self.data_train[k][1])))[0],
[self.label_from_pos(p) for p in list(
zip(*(self.data_train[k][1])))[2]])} # 3rd is dict{pos:lab} info
]for k in self.data_train}
if not os.path.exists(os.path.join(self.checkpoint_dir, 'input_data')):
os.makedirs(os.path.join(self.checkpoint_dir, 'input_data'))
# if change_traindata:
if True:
saveCompressed(open(os.path.join(self.dataset_address,'data_longformat.npz'), 'wb'),
**{'data_'+u: v[0] for u,v in self.data_pack.items()},
**{'position_'+u: v[1] for u,v in self.data_pack.items()},
allow_pickle=True)
# Metrics
if self.add_classifier:
if self.classes_and_inclusions_addnoclass is None:
self.classes_and_inclusions_addnoclass = [
(self.classes, self.class_inclusions, self.noclass)]
self.classifier = []
counter_classes = {}
self.classes = None
self.class_inclusions = None
clsn_nolab_nocls = lambda u,v,w:'%s_nolabel-%s_noclass-%s'%(u,v,w)
for classes, class_inclusions, addnoclass in self.classes_and_inclusions_addnoclass:
class_parms = Settings()
assert class_parms is not None, "Could not import the classification settings"
class_parms.skip_data = True
class_parms.nolabel = self.nolabel
if addnoclass is not None:
class_parms.noclass = addnoclass
else:
class_parms.noclass = self.noclass
class_parms.train1 = False
class_parms.train2 = False
class_parms.inference_only = True
class_parms.testload_FINE = self.testload_FINE
class_parms = update_settings_fromclass(class_parms, classes, class_inclusions)
# skip_data to not load unnecessary data
self.classifier += [SP_Conv_Dense(class_parms, skip_data=True,
c_dim=self.c_dim)]
# Load model with pretrained parameters
self.classifier[-1].model_instance(False, True)
key_name = clsn_nolab_nocls(self.classifier[-1].name,
self.nolabel,
self.classifier[-1].noclass)
counter_classes[key_name] = [c for c in self.classifier[-1].classes]
if self.classifier[-1].noclass is not None:
counter_classes[key_name] += [self.classifier[-1].noclass]
self.classifier = {clsn_nolab_nocls(clsfier.name, self.nolabel, clsfier.noclass): clsfier for clsfier in self.classifier}
else:
self.classifier = {'noclassifier': None}
counter_classes = {'noclassifier': ['NoClass']}
print('counter_classes', counter_classes)
assert counter_classes.keys()==self.classifier.keys(), "error in the code"
# usual mts metrics
self.mts_metrics = {}
if 'TEL' in self.test_ds:
self.glob_mts_metrics = {}
counter_labels = self.all_labels
if self.nolabel is not None:
counter_labels += [self.nolabel]
for ccn, cc in counter_classes.items():
self.mts_metrics[ccn] = NPMtsMetrics(counter_labels, cc, cc)
self.mts_metrics[ccn].reset()
if 'TEL' in self.test_ds:
self.glob_mts_metrics[ccn] = NPMtsMetrics(counter_labels, cc, cc)
self.glob_mts_metrics[ccn].reset()
if self.add_classifier:
self.atc_metric = {}
for ccn, cc in counter_classes.items():
self.atc_metric[ccn] = NPAccuracyOverTime3D(counter_labels, cc, cc)
# stat and info metrics on centers
if self.add_centercount:
self.center_counter_pio = {}
if 'TEL' in self.test_ds:
self.glob_center_counter_pio = {}
for ccn, cc in counter_classes.items():
self.center_counter_pio[ccn] = NPJointCenterStat(
counter_labels, cc, cc,
*(([str(c) for c in range(53)],)*3))
self.center_counter_pio[ccn].reset()
if 'TEL' in self.test_ds:
self.glob_center_counter_pio[ccn] = NPJointCenterStat(
counter_labels, cc, cc,
*(([str(c) for c in range(53)],)*3))
self.glob_center_counter_pio[ccn].reset()
def to_rgb(self, data):
if self.c_dim == 1:
# convert to RGB data
return np.tile(data, [1, 1, 1, 3])
return data
def cumul_side(self, percent_dict, sorted_list, threshold):
# returns a boolean list
return [sum(percent_dict[ee] for ee in sorted_list[:sorted_list.index(e)+1])<threshold for e in sorted_list]
def loop_cumul(self, percent_dict, sorted_list, threshold, max_attempt, start='left'):
if start=='right':
sorted_list = sorted_list[::-1]
if percent_dict[sorted_list[0]]<=threshold:
return sum(self.cumul_side(percent_dict, sorted_list, threshold))+1
elif max_attempt:
return 1
def label_from_pos(self, pos, predictonly=True):
try:
return self.all_labels[[l in pos for l in self.all_labels].index(True)]
except:
assert predictonly, "No Label can only be used for predictions, not train/eval or test, for pos: {}".format(pos)
return self.nolabel
def parse_lab_pos(self, pos, i, dict_poslab):
"""Outputs pos as int and vlabel as str
"""
# tf.print('parse lab pos')
# labi = tf.strings.split(tf.expand_dims(pos[i],0), '_').values[1]
posi = int(pos[i])
labi = dict_poslab[posi]
return labi, posi
def model_instance(self, train_bn, inference_only):
if inference_only:
vgg_weights = None
else:
vgg_weights = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'vgg', 'pytorch_to_keras_vgg16.h5')
# Instantiate the model
if self.model_type == 'IBMTS':
self.model = PConvUnet(
img_rows=self.label_length, img_cols=self.label_length,
c_dim=self.c_dim, with_centerloss = self.with_centerloss,
inference_only=inference_only,
vgg_weights=vgg_weights, net_name=self.name) #img_rows=512, img_cols=512, vgg_weights="imagenet", inference_only=False, net_name='default', gpus=1, vgg_device=None
if self.model_type == 'LSTM':
self.model = LSTM(
img_rows=self.label_length, img_cols=self.label_length,
c_dim=self.c_dim, with_centerloss = self.with_centerloss,
inference_only=inference_only,
vgg_weights=vgg_weights, net_name=self.name) #img_rows=512, img_cols=512, vgg_weights="imagenet", inference_only=False, net_name='default', gpus=1, vgg_device=None
if self.model_type == 'LSTMS':
self.model = LSTMS(
img_rows=self.label_length, img_cols=self.label_length,
c_dim=self.c_dim, with_centerloss = self.with_centerloss,
inference_only=inference_only,
vgg_weights=vgg_weights, net_name=self.name) #img_rows=512, img_cols=512, vgg_weights="imagenet", inference_only=False, net_name='default', gpus=1, vgg_device=None
if self.model_type == 'GRU':
self.model = GRU(
img_rows=self.label_length, img_cols=self.label_length,
c_dim=self.c_dim, with_centerloss = self.with_centerloss,
inference_only=inference_only,
vgg_weights=vgg_weights, net_name=self.name) #img_rows=512, img_cols=512, vgg_weights="imagenet", inference_only=False, net_name='default', gpus=1, vgg_device=None
if self.model_type == 'GRUS':
self.model = GRUS(
img_rows=self.label_length, img_cols=self.label_length,
c_dim=self.c_dim, with_centerloss = self.with_centerloss,
inference_only=inference_only,
vgg_weights=vgg_weights, net_name=self.name) #img_rows=512, img_cols=512, vgg_weights="imagenet", inference_only=False, net_name='default', gpus=1, vgg_device=None
if self.model_type == 'NBeats':
self.model = NBeats(n_blocks=self.n_blocks,
img_rows=self.label_length, img_cols=self.label_length,
c_dim=self.c_dim, with_centerloss = self.with_centerloss,
inference_only=inference_only,
vgg_weights=vgg_weights, net_name=self.name) #img_rows=512, img_cols=512, vgg_weights="imagenet", inference_only=False, net_name='default', gpus=1, vgg_device=None
print(" [*] Reading checkpoints...")
checkpoint_dir = os.path.join(self.checkpoint_dir, 'trained_model')
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
if train_bn:
learning_rate = self.learning_rate_BN
else:
learning_rate = self.learning_rate_FINE
if inference_only:
try:
ckpt_name = max(glob(os.path.join(
checkpoint_dir,'BN'+str(self.learning_rate_BN)+'FINE'+str(self.learning_rate_FINE)+'*')), key = os.path.getctime)
except:
try:
ckpt_name = max(glob(os.path.join(
checkpoint_dir,'BN'+str(self.learning_rate_BN)+'w*')), key = os.path.getctime)
except:
assert False, "[*] Failed to find a checkpoint, train a model first"
if ckpt_name:
print(" [*] Checkpoint found")
print(ckpt_name)
self.model.load(ckpt_name, train_bn=False)
print(" [*] Model loaded")
else:
print(" [*] Failed to find a checkpoint, train a model first")
elif self.preload_train or not(train_bn): # training from pretrained
print('pt')
search = glob(os.path.join(
checkpoint_dir,'BN'+str(self.learning_rate_BN)+'*'))
if len(search)!=0:
ckpt_name = max(search, key = os.path.getctime)
if ckpt_name:
print(" [*] Checkpoint found")
print(ckpt_name)
self.model.load(ckpt_name, train_bn=train_bn, lr=learning_rate)
print(" [*] Model loaded")
else:
print(" [*] Could not find a pretrained model, please retry")
else:
print(" [*] Failed to find a checkpoint, will train a model first")
self.set_model(train_bn=train_bn, lr=learning_rate)
print(" [*] Model is set")
else:
#setting model
self.set_model(train_bn=train_bn, lr=learning_rate)
# print('compiled3', self.model.model._is_compiled)
print(" [*] Model is set")
def plot_callback(self, samples, epoch):
"""Called at the end of each epoch, displaying our previous test images,
as well as their masked predictions and saving them to disk"""
if not os.path.exists(os.path.join(self.results_dir, 'training', 'samples')):
os.makedirs(os.path.join(self.results_dir, 'training', 'samples'))
# Parse samples
(masked, mask, pos), ori = samples
# Get samples & Display them
pred_img = self.model.predict([masked, mask])
# Clear current output and display test images
for i in range(len(ori)):
_, axes = plt.subplots(1, 3, figsize=(20, 5))
axes[0].imshow(masked[i,:,:,:].squeeze().transpose(), cmap = 'gist_heat', vmin = 0, vmax = 1)
axes[1].imshow(pred_img[i,:,:,:].squeeze().transpose() * 1., cmap = 'gist_heat', vmin = 0, vmax = 1)
axes[2].imshow(ori[i,:,:,:].squeeze().transpose() * 1., cmap = 'gist_heat', vmin = 0, vmax = 1)
axes[0].set_title('Masked Image')
axes[1].set_title('Predicted Image')
axes[2].set_title('Original Image')
self.savefig_autodpi(os.path.join(
self.results_dir, 'training', 'samples',
'Epoch_img_{}_{}_{}.png').format(i, epoch, pos[i]),
bbox_inches='tight')
plt.close()
def set_model(self, train_bn=True, lr=0.0002):
# Create UNet-like model
self.model.build_pconv_unet(train_bn)
self.model.built = True
self.model.compile(lr)
# print('compiled4', self.model.model._is_compiled)
# print('compiled4b', self.model._is_compiled)
print('[*] Model built and compiled')
def train(self, show_samples):
if not os.path.exists(os.path.join(self.results_dir, 'training')):
os.makedirs(os.path.join(self.results_dir, 'training'))
if self.train1:
self.train_phase(show_samples, True)
if self.train2:
self.train_phase(show_samples, False)
def train_phase(self, show_samples, train_bn):
print('[START] Loading Model for train - train_bn %s - inference_only %s'%(train_bn, False))
self.model_instance(train_bn, False)
# self.model.summary()
# print("test compiled1", self.model.model._is_compiled)
if train_bn:
checkpoint_phase = '/BN'+str(self.learning_rate_BN)
else:
checkpoint_phase = '/BN'+str(self.learning_rate_BN)+'FINE'+str(self.learning_rate_FINE)
checkpoint_dir = os.path.join(self.checkpoint_dir, 'trained_model')
if not os.path.exists(self.checkpoint_dir):
os.makedirs(self.checkpoint_dir)
print('[%s - START] Training Phase %i ..'%(now().strftime('%d.%m.%Y - %H:%M:%S'), 2-train_bn))
# Run training for certain amount of epochs
# print("test compiled2", self.model.model._is_compiled)
self.model.fit_generator(
self.generators['TR'][0],
steps_per_epoch=self.generators['TR'][1]//self.batch_size,
validation_data=self.generators['VAL'][0],
validation_steps=self.generators['VAL'][1]//self.batch_size,
epochs=[self.epoch,1][int(self.debug)],
verbose=0,
callbacks=[
TensorBoard(
log_dir=self.logs_dir,
write_graph=False
),
ModelCheckpoint(
checkpoint_dir+checkpoint_phase+'weights.{epoch:02d}-{loss:.2f}.h5',
monitor='val_loss',
save_best_only=False,
save_weights_only=True
),
# LambdaCallback(
# on_epoch_end=lambda epoch, logs: self.plot_callback(show_samples, epoch)
# # on_epoch_end=lambda epoch, logs: self.plot_callback(self.to_rgb(show_samples), epoch)
# ),
#TQDMCallback()
]
)
print('[%s - END] Training.'%now().strftime('%d.%m.%Y - %H:%M:%S'))
def features_feedback(self):
if os.path.isfile(os.path.join(self.checkpoint_dir, 'input_data', 'feats_fback.npz')):
feats_fback = np.load(os.path.join(self.checkpoint_dir, 'input_data', 'feats_fback.npz'), allow_pickle=True)['feats_fback']
if len(feats_fback.shape) == 2 and feats_fback.shape[1] == 2:
feats_fback = [list(a) for a in feats_fback]
else:
feats_fback = []
else:
feats_fback = []
for name, [gen, length, dict_poslab] in self.generators.items():
if name == 'show':
continue
positions_f = self.data_train[name][1]
n = 0
print('Checking and writing feedbacks about features on original %s data'%name)
for (masked, mask, pos), ori in tqdm(gen, total = np.ceil(length / self.batch_size)):
feats = [feature_transform(o.squeeze()[-int(ori.shape[1] * self.mask_ratio):, :], o.squeeze()[-int(ori.shape[1] * self.mask_ratio):, :]).transpose() for o in ori]
for posi, feati in zip(pos, feats):
if np.isnan(feati).any():
idx = np.where(np.array(list(zip(*positions_f))[0])==posi)
assert len(idx) == 1 and idx[0] and idx[0].shape == (1,), "Found no or several options for an NoClass index %s: %s"%(posi, idx)
idx = idx[0][0]
posi_f = positions_f[idx]
feats_fback.append([np.sum(np.isnan(feati)), retrieve_traintimeseq(posi_f)])
n += len(feats)
if n > length:
break
np.savez(os.path.join(
self.checkpoint_dir, 'input_data',
'feats_fback'), feats_fback = feats_fback)
def predicts(self):
if not os.path.exists(os.path.join(self.results_dir, 'prediction')):
os.makedirs(os.path.join(self.results_dir, 'prediction'))
if self.model_type in ['LSTM', 'LSTMS', 'GRU', 'GRUS', 'NBeats']:
print('[START] Loading Model for predict - train_bn %s - inference_only %s'%(True, True))
self.model_instance(True, True)
else:
print('[START] Loading Model for predict - train_bn %s - inference_only %s'%(False, True))
self.model_instance(False, True)
print('[%s - START] Predicting..'%now().strftime('%d.%m.%Y - %H:%M:%S'))
predict_ds = self.predict_ds.split('_')
for ds in predict_ds:
if 'TEL' in ds:
self.long_predicts(ds)
else:
gen = self.generators[ds][0]
print('[Predicting] %s Samples'%ds)
n = 1
for (masked, mask, pos), ori in tqdm(gen, total = int(np.ceil(self.number_predict/self.batch_size))):
n = self.predict_save_1batch(masked, mask, ori, pos, ds, n)
# Only create predictions for about 100 images
if n >= self.number_predict:
break
print('[%s - END] Predicting.'%now().strftime('%d.%m.%Y - %H:%M:%S'))
def predict_save_1batch(self, masked, mask, ori, pos, ds, n):
pred_img = self.model.predict([masked, mask])
# class prediction on input and output
class_mask = create_class_mask(ori, self.mask_ratio,
self.random_ratio)
if self.add_classifier:
pred_class_in = {}
pred_class_out = {}
in_class = {}
out_class = {}
for clsn, clsfier in self.classifier.items():
pred_class_in[clsn] = clsfier.model.predict([ori, class_mask])
in_class[clsn] = clsfier.model.np_assign_class(pred_class_in[clsn])
pred_class_out[clsn] = clsfier.model.predict([pred_img, class_mask])
out_class[clsn] = clsfier.model.np_assign_class(pred_class_out[clsn])
else:
in_class = {'noclassifier':['NoClass']*len(ori)}
out_class = {'noclassifier':['NoClass']*len(ori)}
errors, errors5 = onebatchpredict_errors(ori, pred_img, self.mask_ratio)
# Clear current output and display test images
for i in range(len(ori)):
labi, posi = self.parse_lab_pos(pos, i, self.generators[ds][2])
# print('current pos {}'.format(posi))
# print('current lab {}'.format(labi))
# print('current n {}'.format(n))
# print('max n {}'.format(self.number_predict))
mts_results = {}
for clsn in self.mts_metrics.keys():
self.mts_metrics[clsn].reset()
self.mts_metrics[clsn].update(
([labi], [in_class[clsn][i]], [out_class[clsn][i]]),
(np.expand_dims(ori[i][-int(ori.shape[1]*self.mask_ratio):],0),
np.expand_dims(pred_img[i][-int(ori.shape[1]*self.mask_ratio):],0)))
mts_results[clsn] = self.mts_metrics[clsn].result_by_no()
if self.add_centercount:
pio_centers = {}
for clsn, ccp in self.center_counter_pio.items():
ccp.reset()
ccp.fit_batch(
[labi], ([in_class[clsn][i]], [out_class[clsn][i]]),
(np.expand_dims(ori[i][:-int(ori.shape[1]*self.mask_ratio)],0),
np.expand_dims(ori[i][-int(ori.shape[1]*self.mask_ratio):],0),
np.expand_dims(pred_img[i][-int(ori.shape[1]*self.mask_ratio):],0)))
pio_centers[clsn] = ccp.result_cond_1()
else:
pio_centers = {'noclassifier':None}
psnr = -10.0 * np.log10(np.mean(np.square(pred_img[i,:,:,:].squeeze()[-int(ori.shape[1] * self.mask_ratio):,:] - ori[i,:,:,:].squeeze()[-int(ori.shape[1] * self.mask_ratio):,:])))
kcenter_accuracy = [kcentroids_equal(to_kcentroid_seq(pred_img[i,:,:,:].squeeze()[-int(ori.shape[1] * self.mask_ratio):,:], k=n_centers)[1], to_kcentroid_seq(ori[i,:,:,:].squeeze()[-int(ori.shape[1] * self.mask_ratio):,:], k=n_centers)[1]) for n_centers in range(1,7)]
# kcenter1_accuracy = kcentroids_equal(to_kcentroid_seq(pred_img[i,:,:,:].squeeze()[-int(ori.shape[1] * self.mask_ratio):,:], k=1)[1], to_kcentroid_seq(ori[i,:,:,:].squeeze()[-int(ori.shape[1] * self.mask_ratio):,:], k=1)[1])
# kcenter5_accuracy = kcentroids_equal(to_kcentroid_seq(pred_img[i,:,:,:].squeeze()[-int(ori.shape[1] * self.mask_ratio):,:], k=5)[1], to_kcentroid_seq(ori[i,:,:,:].squeeze()[-int(ori.shape[1] * self.mask_ratio):,:], k=5)[1])
meta_class_ori = '\nWeak Label '+labi
if self.add_classifier:
# meta_class_in = {}
# meta_class_out = {}
makedir = {}
for clsn in list(self.classifier.keys()):
# meta_class_in[clsn] = '\nClassified '+in_class[clsn][i]
# meta_class_out[clsn] = ' Classified '+out_class[clsn][i]
makedir[clsn] = clsn
else:
# meta_class_in = {'noclassifier':''}
# meta_class_out = {'noclassifier':''}
makedir = {'noclassifier':'noclassifier'}
for i_img in list(makedir.keys()):
n_srow = 1
plot_classes = False
if self.add_centercount:
n_srow += 1
if self.add_classifier and self.classifier[i_img].nclass>1:
plot_classes = True
n_srow += 1
widths = [1]*n_srow+[2]*4
ncols = len(widths)
heights = [1]*4
nrows = len(heights)
figsize = (10*sum(widths),10*sum(heights))
fig = plt.figure(constrained_layout=True, figsize=figsize)
spec = gridspec.GridSpec(nrows=nrows, ncols=ncols, figure=fig,
width_ratios=widths,
height_ratios=heights)
axes = {}
for row in range(nrows):
for col in range(ncols):
if self.add_centercount and col==int(plot_classes)+1 and row !=nrows-1 or plot_classes and col==1 and row in [1,2]:
axes[row, col] = fig.add_subplot(spec[row, col], polar=self.show_dist_polar)
elif not(plot_classes) or (plot_classes and col!=1):
axes[row, col] = fig.add_subplot(spec[row, col])
if self.add_classifier and not(plot_classes):
# should be a unique value
probain_unique_class = ' %s'%'\n'.join(
['%s (%.3f)'%(self.classifier[i_img].classes[ic],
pred_class_in[i_img][i][ic]) for ic in range(self.classifier[i_img].nclass)])
probaout_unique_class = ' %s'%'\n'.join(
['%s (%.3f)'%(self.classifier[i_img].classes[ic],
pred_class_out[i_img][i][ic]) for ic in range(self.classifier[i_img].nclass)])
else:
probain_unique_class = ''
probaout_unique_class = ''
if self.add_classifier:
axes[1, 0].set_title('Original Sequence\nClass Pred:%s%s'%(
in_class[i_img][i],
probain_unique_class))
axes[2, 0].set_title('Predicted Sequence PSNR=%.2f\nClass Pred:%s%s'%(
psnr,
out_class[i_img][i],
probaout_unique_class))
else:
axes[1, 0].set_title('Original Sequence')
axes[2, 0].set_title('Predicted Sequence PSNR=%.2f'%psnr)#, y =-0.01)
# Plot first column (images of spectra)
axes[0, 0].imshow(masked[i].squeeze().transpose(), cmap = 'gist_heat', vmin = 0, vmax = 1)
self.format_image_axes(axes[0, 0],
start_pred=int(self.label_length*(1-self.mask_ratio)),
time_max=len(masked[i].squeeze()),
xlabel='time',
lambda_size=masked[i].squeeze().shape[1],
mask=True)
axes[0, 0].set_title('Masked Sequence'+meta_class_ori)
# axes[0, 0].set_title('Masked Sequence'+meta_class_in[i_img])
axes[2, 0].imshow(pred_img[i].squeeze().transpose() * 1., cmap = 'gist_heat', vmin = 0, vmax = 1)
self.format_image_axes(axes[2, 0],
start_pred=int(self.label_length*(1-self.mask_ratio)),
time_max=len(pred_img[i].squeeze()),
xlabel='time',
lambda_size=pred_img[i].squeeze().shape[1])
# axes[2, 0].set_title('Predicted Sequence PSNR=%.2f'%(psnr)+meta_class_out[i_img])#, y =-0.01)
axes[1, 0].imshow(ori[i].squeeze().transpose() * 1., cmap = 'gist_heat', vmin = 0, vmax = 1)
self.format_image_axes(axes[1, 0],
start_pred=int(self.label_length*(1-self.mask_ratio)),
time_max=len(ori[i].squeeze()),
xlabel='time',
lambda_size=ori[i].squeeze().shape[1])
axes[3, 0].imshow(self.coef_diff * np.abs(ori[i].squeeze().transpose() * 1. - pred_img[i].squeeze().transpose() * 1.), vmin = 0, vmax = 1)
self.format_image_axes(axes[3, 0],
start_pred=int(self.label_length*(1-self.mask_ratio)),
time_max=len(ori[i].squeeze()),
xlabel='time',
lambda_size=ori[i].squeeze().shape[1])
axes[3, 0].set_title('%s x Difference' % str(self.coef_diff))#, y =-0.01)
addc = 0
# Plot second column (center clusters distributions)
if plot_classes:
addc += 1
probain_class = {
self.classifier[i_img].classes[ic]: pred_class_in[i_img][i][ic] for ic in range(self.classifier[i_img].nclass)}
probaout_class = {
self.classifier[i_img].classes[ic]: pred_class_out[i_img][i][ic] for ic in range(self.classifier[i_img].nclass)}
keys_in, vals_in = self.dict_to_keyval(probain_class)
keys_out, vals_out = self.dict_to_keyval(probaout_class)
assert keys_in==keys_out
# print('vals_in',vals_in)
# print('vals_out',vals_out)
# print('for rmax',vals_in+vals_out)
# print('rmax',max(vals_in+vals_out))
self.polar_bar_plot(axes[1, addc], vals_in, keys_in, bottom=.1,
count_step=0.1, count_ceil=0,
rmax=max(vals_in+vals_out),
color='tab:purple')
axes[1, addc].set_title('Class Pred IN\n')
self.polar_bar_plot(axes[2, addc], vals_out, keys_out, bottom=.1,
count_step=0.1, count_ceil=0,
rmax=max(vals_in+vals_out),
color='tab:purple')
axes[2, addc].set_title('Class Pred OUT\n')
if self.add_centercount:
addc +=1
keys_prior, vals_prior = self.dict_to_keyval(pio_centers[i_img]['centers']['c0'][labi])
keys_in, vals_in = self.dict_to_keyval(pio_centers[i_img]['centers']['c1'][labi])
keys_out, vals_out = self.dict_to_keyval(pio_centers[i_img]['centers']['c2'][labi])
assert keys_prior==keys_in==keys_out
self.polar_bar_plot(axes[0, addc], vals_prior, keys_prior, bottom=.1,
count_ceil=0.1,
rmax=max(vals_prior+vals_in+vals_out))
axes[0,addc].set_title('Center distribution PRIOR\n')
self.polar_bar_plot(axes[1,addc], vals_in, keys_in, bottom=.1,
count_ceil=0.1,
rmax=max(vals_prior+vals_in+vals_out))
axes[1, addc].set_title('Center distribution IN\n')
self.polar_bar_plot(axes[2, addc], vals_out, keys_in, bottom=.1,
count_ceil=0.1,
rmax=max(vals_prior+vals_in+vals_out))
axes[2,addc].set_title('Center distribution OUT\n')
cm, (kin, kout) = self.dict2d_to_array(
pio_centers[i_img]['centers']['c1c2'][labi],
with_keys=True)
self.plot_heatmap(
cm, kin, kout,
'Center IN VS Center OUT',
axes[3,addc], with_cbar=True, with_labels=False,
xtick_step=5, ytick_step=5, linewidths=.5,
vmin=0, vmax=np.max(cm))
# self.polar_bar_plot(axes[3, 1],
# [abs(vi-vo) for vi,vo in zip(vals_in, vals_out)],
# keys, bottom=.1, count_ceil=0.05,
# rmax=max([
# abs(vi-vo) for vi,vo in zip(
# vals_in, vals_out)]))
axes[3, addc].set_title('Center distribution ERROR\nH(in)=%.2f H(out)=%.2f I(in;out)=%.2f\n'%(
pio_centers[i_img]['info_c1c2']['entropies'][0][labi],
pio_centers[i_img]['info_c1c2']['entropies'][1][labi],
pio_centers[i_img]['info_c1c2']['mutual_info'][labi]))
# Start plotting 3rd column (or 2nd when no center): Raw CV errors (PSNR, SSIM)
axes[0, 1+addc].plot(range(1, len(errors[0,i])+1),
-10*np.log10(errors[0, i]),
label='PSNR')
self.format_axis(axes[0, 1+addc], vmin=0, vmax=40, step = 10, axis = 'y', type_labels='int')
self.format_axis(axes[0, 1+addc], vmin=0, vmax=len(errors[0, i]), step = 10, axis = 'x', ax_label='time', type_labels='int')
self.set_description(axes[0, 1+addc], legend_loc='upper center', fontsize='x-small')
axes[2, 1+addc].plot(range(1, len(errors[1,i])+1),
errors[1, i], label='SSIM')
axes[2, 1+addc].plot(range(1, len(errors[1,i])+1),
np.ones_like(errors[1, i]), label='best', linestyle=':', color='g')
self.format_axis(axes[2, 1+addc], vmin=0, vmax=1, step = 0.2, axis = 'y', type_labels='%.1f', margin=[0,1])
self.format_axis(axes[2, 1+addc], vmin=0, vmax=len(errors[1,i]), step = 10, axis = 'x', ax_label='time', type_labels='int')
self.set_description(axes[2, 1+addc], legend_loc='upper center', fontsize='x-small')
# Start plotting the other columns: Raw physical errors (centers assignment)
for j in range(1,7):
row, col = [int((j-1)%2)*2, 2+int((j-1)//2)+addc]
axes[row, col].plot(range(1, len(kcenter_accuracy[j-1])+1),
kcenter_accuracy[j-1], label='%i-Center'%j)
axes[row, col].plot(range(1, len(kcenter_accuracy[j-1])+1),
[kinter(j) for _ in range(len(kcenter_accuracy[j-1]))], label='%i-RandomBaseground'%j, linestyle=':', color='r')
axes[row, col].plot(range(1, len(kcenter_accuracy[j-1])+1),
np.ones_like(kcenter_accuracy[j-1]), label='best accuracy', linestyle=':', color='g')
self.format_axis(axes[row, col], vmin=0, vmax=1, step = 0.2, axis = 'y', type_labels='%.1f', margin=[0,1])
self.format_axis(axes[row, col], vmin=0, vmax=len(kcenter_accuracy[j-1]), step = 10, axis = 'x', ax_label='time', type_labels='int')
self.set_description(axes[row, col], legend_loc='upper center', fontsize='x-small')
# Plot 3rd column (or 2nd when no center): Avg on 5% time CV errors (PSNR, SSIM)
vmin, vstart, vstep, vend = self.adjust_xcoord(
toshow=errors5[0, i], tofit=errors[0, i])
axes[1, 1+addc].plot(np.arange(vstart, vend, vstep),
-10*np.log10(errors5[0, i]), label='PSNR')
self.format_axis(axes[1, 1+addc], vmin=0, vmax=40, step = 10, axis = 'y', type_labels='int')
self.format_axis(axes[1, 1+addc], vmin=vmin, vmax=len(errors5[0, i]), lmin=0, lmax=len(errors[0, i]), step = 10, axis = 'x', type_labels='int', ax_label='time')
self.set_description(axes[1, 1+addc], legend_loc='upper center', fontsize='x-small')
axes[3, 1+addc].plot(np.arange(vstart, vend, vstep),
errors5[1, i], label='SSIM')
axes[3, 1+addc].plot(np.arange(vstart, vend, vstep),
np.ones_like(errors5[1, i]), label='best', linestyle=':', color='g')
self.format_axis(axes[3, 1+addc], vmin=0, vmax=1, step = 0.2, axis = 'y', type_labels='%.1f', margin=[0,1])
self.format_axis(axes[3, 1+addc], vmin=vmin, vmax=len(errors5[1,i]), lmin=0, lmax=len(errors[1,i]), step = 10, axis = 'x', type_labels='int', ax_label='time')
self.set_description(axes[3, 1+addc], legend_loc='upper center', fontsize='x-small')
# Plot all the other columns: Avg on 5% time physical errors (centers assignment)
for j in range(1,7):
row, col = [int((j-1)%2)*2+1, 2+int((j-1)//2)+addc]
axes[row, col].plot(*forplot_assignement_accuracy(kcenter_accuracy[j-1], bin_size=int(self.label_length * 0.05)), label='%i-Center'%j)
axes[row, col].plot(np.arange(.5, len(kcenter_accuracy[j-1])+.5),
[kinter(j) for _ in range(len(kcenter_accuracy[j-1]))], label='%i-RandomBaseground'%j, linestyle=':', color='r')
axes[row, col].plot(np.arange(.5, len(kcenter_accuracy[j-1])+.5),
np.ones_like(kcenter_accuracy[j-1]), label='best accuracy', linestyle=':', color='g')
self.format_axis(axes[row, col], vmin=0, vmax=1, step = 0.2, axis = 'y', type_labels='%.1f', margin=[0,1])
self.format_axis(axes[row, col], vmin=0, vmax=len(kcenter_accuracy[j-1]), step = 10, axis = 'x', ax_label='time', type_labels='int')
self.set_description(axes[row, col], legend_loc='upper center', fontsize='x-small')
if not os.path.exists(os.path.join(self.results_dir, 'prediction', makedir[i_img])):
os.makedirs(os.path.join(self.results_dir, 'prediction', makedir[i_img]))
for u in range(2):
for v in range(1,5):
axes[2 * u, v+addc].set_title('time predictions')
axes[2 * u + 1, v+addc].set_title('Avg 5% time slices predictions')
# spec.tight_layout(fig)
self.savefig_autodpi(os.path.join(
self.results_dir, 'prediction', makedir[i_img],
'Dataset-{}_Sample-{}_Lab-{}_Pos-{}_spectra_polar-{}.png'.format(
ds, n, labi, posi, self.show_dist_polar)),
bbox_inches='tight')
plt.close()
if self.add_centercount:
# add sample_info
self.plot_1simp_pred_centers(pio_centers[i_img], labi,
in_class[i_img][i],
out_class[i_img][i],
save_name=os.path.join(
'prediction',
makedir[i_img],
'Dataset-{}_Sample-{}_Lab-{}_Pos-{}_detailedcentercount_polar-{}.png'.format(
ds, n, labi, posi, self.show_dist_polar)))
self.plot_mtsres(
{'by_no':mts_results[i_img]},
meta=(labi,
in_class[i_img][i],
out_class[i_img][i]),
save_name=os.path.join(
'prediction', makedir[i_img],
'Dataset-{}_Sample-{}_Lab-{}_Pos-{}_mts_results.png'.format(
ds, n, labi, posi)))
self.save_features_sequence(
ori[i,:,:,:].squeeze()[-int(ori.shape[1] * self.mask_ratio):,:],
pred_img[i,:,:,:].squeeze()[-int(ori.shape[1] * self.mask_ratio):,:],
ds, n, posi, labi, self.feat_legends, save_dir='prediction')
n += 1
return n
def plot_mtsres(self, mts_results, meta=None, glob=None, glob_meta=None,
save_name='mts_results.png'):
# mts_results = {'by_no':self.mts_metrics[clsn].result_by_no(),
# 'by_1':self.mts_metrics[clsn].result_by_1(),
# 'by_1_2':self.mts_metrics[clsn].result_by_1_2(),
# 'by_1_3':self.mts_metrics[clsn].result_by_1_3(),
# 'by_1_2_3':self.mts_metrics[clsn].result_by_1_2_3()}
# mts_results may not include only 'by_no'
# meta = (lab, clas1, clas2) is info to be used when given to plot and
# inform only on the corresponding info, can contain Nones
# glob = {'by_no':self.mts_metrics[clsn].result_by_no()} is mts global
# metrics to be ploted when given
# glob_meta = (lab, clas1, clas2) is info to be used for the glob when
# given to plot and informa only on the glob corresponding info
# Plot the multi time series usual metrics
w_box = 15 # width for one box of result
h_box = 15 # height for one box of result
test_case = False
if mts_results.keys()=={'by_no':None}.keys():
# mts_results only contains 'by_no' results (simple prediction case)
assert meta is not None, "information on data should be given"
# fig contains only one time all mts metrics (one plot for each metric)
# similar to self.plot_1simp_pred_centers
previous_font_size = plt.rcParams['font.size']
plt.rcParams.update({'font.size': int(previous_font_size*w_box/30*6/5)})
parms = self.parms_mtsres_one_label('simple_pred', (w_box, h_box),
mts_results, meta)
dict_plot_fn_keys = ['by_no']
elif 'by_no' not in mts_results.keys():
# long prediction case
assert meta is not None and meta[0] is not None, "meta info should be given for the long prediction case"
assert all(key in mts_results.keys() for key in [
'by_1', 'by_1_2', 'by_1_3', 'by_1_2_3']), "all keys except 'by_no' should be given"
assert glob is not None
assert glob.keys()=={'by_no':None}.keys(), "glob should contain only by_no result"
assert glob_meta is not None, "information on glob_data should be given"
# fig contains (key2+1)*(key3+1) plots for each mts metric plus global mts metrics
# similar to self.plot_1long_pred_centers
previous_font_size = plt.rcParams['font.size']
plt.rcParams.update({'font.size': int(previous_font_size*w_box/30*6/5)})
parms = self.parms_mtsres_one_label('long_pred', (w_box, h_box),
mts_results, meta)
dict_plot_fn_keys = ['by_no', 'by_1', 'by_1_2', 'by_1_3', 'by_1_2_3']
else:
# test or longtest case
assert all(key in mts_results.keys() for key in [
'by_no', 'by_1', 'by_1_2', 'by_1_3', 'by_1_2_3']), "all keys except should be given"
# key2 figs created and saved that each contains
# (key2+1)*(key3+1) plots for each mts metric