-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathCME-CASIA-B.py
4272 lines (4196 loc) · 177 KB
/
CME-CASIA-B.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 tensorflow as tf
from tensorflow.python.layers.core import Dense
import numpy as np
import time
import matplotlib as mpl
import copy
import os
from tensorflow.python.ops import rnn_cell_impl
# mpl.use('Agg')
# import matplotlib.pyplot as plt
import os
# Number of Epochs
epochs = 100
# Batch Size
batch_size = 128
# RNN Size k = 256
rnn_size = 256
# Number of Layers, 2-layer LSTM
num_layers = 2
# Time Steps of Input, f = 6 skeleton frames
time_steps = 6
# Length of Series, J = 20 body joints in a sequence
series_length = 20
# Learning Rate
learning_rate = 0.0005
lr_decay = 0.95
momentum = 0.5
lambda_l2_reg = 0.02
dataset = False
attention = False
manner = False
gpu = False
permutation_flag = False
permutation_test_flag = False
permutation_test_2_flag = False
permutation = 0
test_permutation = 0
test_2_permutation = 0
Reverse = True
use_attention = True
Bi_LSTM = False
AGEs = True
Frozen = False
tf.app.flags.DEFINE_string('attention', 'LA', "(LA) Locality-oriented Attention Alignment or BA (Basic Attention Alignment)")
tf.app.flags.DEFINE_string('manner', 'sc', "average prediction (ap) or sequence-level concatenation (sc)")
tf.app.flags.DEFINE_string('dataset', 'CASIA_B', "Dataset: BIWI or IAS, CASIA_B or KGBD")
tf.app.flags.DEFINE_string('length', '50', "For CVE setup on CASIA B, 50, 60 or 70")
tf.app.flags.DEFINE_string('gpu', '0', "GPU number")
tf.app.flags.DEFINE_string('frozen', '0', "Freeze CAGEs for contrastive learning")
tf.app.flags.DEFINE_string('c_reid', '0', "Peform re-id use projection vectors")
tf.app.flags.DEFINE_string('t', '0.15', "Temperature for contrastive learning")
tf.app.flags.DEFINE_string('train_flag', '1', "Choose to train (1) or test (0)")
tf.app.flags.DEFINE_string('view', 'None', "Choose different views for CASIA B")
tf.app.flags.DEFINE_string('transfer', 'None', "Choose a dataset's encoding model to transfer encoding")
tf.app.flags.DEFINE_string('model', 'rev_rec', "prediction, sorting, rev_rec (Rev. Rec.), rev_rec_plus(Rev. Rec. Plus)")
tf.app.flags.DEFINE_string('double_pretext', '', "rev_rec+pred, rev_rec+sort")
# tf.app.flags.DEFINE_string('p_num', '', "number of persons for training")
tf.app.flags.DEFINE_string('probe_type', 'nm.nm', "probe type (nm, cl, bg)")
tf.app.flags.DEFINE_string('norm', '1', "1 or 0")
FLAGS = tf.app.flags.FLAGS
config = tf.ConfigProto()
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
temperature = 0.1
config.gpu_options.allow_growth = True
view = 'view_'
probe_type = ''
transfer = 'None'
Model = 'rev_rec'
pre_task = 'rev_rec'
# revise 1
double_pretext = ''
p_num = ''
CASIA_scale = ''
multi_view_results = ''
normalize = False
LSTM_layer = ''
view_num = ''
change = '_test_adj_2'
change = '_mid_match'
gallery_num = '0'
def main(_):
global permutation_test_flag, permutation_flag, probe_type, \
batch_size, learning_rate, normalize, LSTM_layer, gallery_num
global attention, dataset, series_length, epochs, time_steps, gpu, manner, frames_ps, \
temperature, Frozen, C_reid, temperature, train_flag, view, use_attention, transfer, Model, pre_task
attention, dataset, gpu, manner, length, Frozen, C_reid, temperature, train_flag, \
view_num, transfer, Model, double_pretext, probe_type_t, norm_t = FLAGS.attention, \
FLAGS.dataset, FLAGS.gpu, FLAGS.manner, \
FLAGS.length, FLAGS.frozen, FLAGS.c_reid, \
FLAGS.t, FLAGS.train_flag, FLAGS.view, \
FLAGS.transfer, FLAGS.model, FLAGS.double_pretext, \
FLAGS.probe_type, FLAGS.norm
if attention not in ['BA', 'LA']:
raise Exception('Attention must be BA or LA.')
if manner not in ['sc']:
raise Exception('Training manner must be sc.')
if dataset not in ['CASIA_B']:
raise Exception('Dataset must be CASIA_B.')
if not gpu.isdigit() or int(gpu) < 0:
raise Exception('GPU number must be a positive integer.')
# if length not in ['4', '6', '8', '10', '40', '20']:
# raise Exception('Length number must be 4, 6, 8, 10, 20 or 40.')
if Frozen not in ['0']:
raise Exception('Frozen state must be 0.')
if C_reid not in ['0']:
raise Exception('C_reid state must be 0.')
if train_flag not in ['0', '1', '2']:
raise Exception('Train_flag must be 0, 1, or 2 (Only Evaluation).')
if view_num not in ['None']:
raise Exception('View_num must be None for CME setup.')
if transfer not in ['None']:
raise Exception('Transfer dataset must be None.')
if Model not in ['rev_rec', 'rev_rec_plus', 'prediction', 'sorting']:
raise Exception('Model must be prediction, sorting, rev_rec or rev_rec_plus')
# Revise 1
if double_pretext not in ['', 'rev_rec+pred', 'rev_rec+sort', 'pred+sort']:
raise Exception('Model must be '' (default), rev_rec+pred, rev_rec+sort, pred+sort')
# old
# if p_num not in ['', '24', '62', '74']:
# raise Exception('Number must be 24, 62, 74')
if double_pretext != '' and Model != 'rev_rec_plus':
raise Exception('Model must be rev_rec_plus')
if probe_type_t not in ['nm.nm', 'cl.cl', 'bg.bg', 'cl.nm', 'bg.nm']:
raise Exception('[Probe].[Gallery] must be nm.nm (default), cl.cl, bg.bg, cl.nm, bg.nm')
os.environ['CUDA_VISIBLE_DEVICES'] = gpu
# os.environ['CUDA_VISIBLE_DEVICES'] = '0,1,2,3'
folder_name = dataset + '_' + attention
series_length = 20
setting = ''
LSTM_layer = ''
if dataset == 'CASIA_B':
series_length = 14
view += view_num
if gallery_num == '':
gallery_num = view_num
if norm_t == '1':
normalize = True
probe_type = probe_type_t
if view_num == 'None':
view = ''
if num_layers == 4:
LSTM_layer = '_L4'
if dataset == 'KS20':
series_length = 25
view += view_num
if view_num == 'None':
view = ''
if transfer != 'None':
train_flag = '0'
time_steps = int(length)
temperature = float(temperature)
pre_task = Model
frames_ps = dataset + '_match/' + str(time_steps) + setting + '/'
epochs = 400
if dataset != 'KS20' and dataset != 'CASIA_B':
view = ''
# if dataset == 'KGBD':
# epochs = 100
if dataset == 'CASIA_B':
epochs = 100
# Obtain CAGEs
# Train self-supervised gait encoding model on X, Y, Z
if dataset == 'KGBD':
temperature = 0.5
elif dataset != 'CASIA_B':
temperature = 0.1
epochs = 400
if Model == 'rev_rec_plus':
# rev_rec uses 'LA' and other two pretext tasks use 'BA'
attention = 'BA'
print(
' ## Dataset: %s\n ## Attention: %s\n ## Re-ID Manner: %s\n ## Sequence Length: %s\n'
' ## Tempearture: %s\n ## Pretext Task: %s\n ## Probe set: %s\n ## Gallery set: %s\n ## GPU: %s\n' %
(dataset, attention, manner, str(time_steps), str(temperature), Model, probe_type.split('.')[0],
probe_type.split('.')[1], str(gpu)))
if train_flag == '1':
print(' ## Training Gait Encoding Model: True')
else:
print(' ## Training Gait Encoding Model: False')
print(' ## Training Recognition Network: True\n')
if train_flag == '1' and Model != 'rev_rec_plus':
try:
os.mkdir('./Models/Gait_Encoding_models')
except:
pass
folder_name = './Models/Gait_Encoding_models/' + folder_name
for i in ['x', 'y', 'z']:
try:
os.mkdir(folder_name + '_' + i + '_' + str(time_steps) + '_' + str(temperature) + '_' + Frozen + view + 'pre_' + pre_task + LSTM_layer + change)
print("### LSTM layers", LSTM_layer)
except:
pass
train(folder_name + '_' + i + '_' + str(time_steps) + '_' + str(temperature)+ '_' + Frozen + view + 'pre_' + pre_task + LSTM_layer + change, i, train_dataset=dataset)
elif train_flag == '1' and Model == 'rev_rec_plus':
print(' ## Training Three Types of Gait Encoding Model: (1) Rev. Rec. (2) Prediction (3) Sorting, and Combine CAGEs to Train RN')
attention = 'LA'
folder_name = dataset + '_' + attention
try:
os.mkdir('./Models/Gait_Encoding_models')
except:
pass
folder_name = './Models/Gait_Encoding_models/' + folder_name
# Rev. Rec.
pre_task = 'rev_rec'
for i in ['x', 'y', 'z']:
try:
os.mkdir(folder_name + '_' + i + '_' + str(time_steps) + '_' + str(temperature) + '_' + Frozen + view + 'pre_' + pre_task)
except:
pass
train(folder_name + '_' + i + '_' + str(time_steps) + '_' + str(temperature)+ '_' + Frozen + view + 'pre_' + pre_task, i, train_dataset=dataset)
# Prediction
attention = 'BA'
folder_name = dataset + '_' + attention
folder_name = './Models/Gait_Encoding_models/' + folder_name
pre_task = 'prediction'
for i in ['x', 'y', 'z']:
try:
os.mkdir(folder_name + '_' + i + '_' + str(time_steps) + '_' + str(temperature) + '_' + Frozen + view + 'pre_' + pre_task)
except:
pass
train(folder_name + '_' + i + '_' + str(time_steps) + '_' + str(temperature)+ '_' + Frozen + view + 'pre_' + pre_task, i, train_dataset=dataset)
# Sorting
attention = 'BA'
folder_name = dataset + '_' + attention
folder_name = './Models/Gait_Encoding_models/' + folder_name
pre_task = 'sorting'
for i in ['x', 'y', 'z']:
try:
os.mkdir(folder_name + '_' + i + '_' + str(time_steps) + '_' + str(temperature) + '_' + Frozen + view + 'pre_' + pre_task)
except:
pass
train(folder_name + '_' + i + '_' + str(time_steps) + '_' + str(temperature)+ '_' + Frozen + view + 'pre_' + pre_task, i, train_dataset=dataset)
pre_task = 'rev_rec_plus'
print('Generate CAGEs')
if dataset == 'IAS':
X, X_y, t_X, t_X_y, t_2_X, t_2_X_y, t_X_att = encoder_classify(dataset + '_' + attention + 'x',
'x', 'att', dataset)
Y, Y_y, t_Y, t_Y_y, t_2_Y, t_2_Y_y, t_Y_att = encoder_classify(dataset + '_' + attention + 'y',
'y', 'att', dataset)
Z, Z_y, t_Z, t_Z_y, t_2_Z, t_2_Z_y, t_Z_att = encoder_classify(dataset + '_' + attention + 'z',
'z', 'att', dataset)
else:
X, X_y, t_X, t_X_y, t_X_att = encoder_classify(dataset + '_' + attention + 'x', 'x', 'att', dataset)
Y, Y_y, t_Y, t_Y_y, t_Y_att = encoder_classify(dataset + '_' + attention + 'y', 'y', 'att', dataset)
Z, Z_y, t_Z, t_Z_y, t_Z_att = encoder_classify(dataset + '_' + attention + 'z', 'z', 'att', dataset)
assert X_y.tolist() == Y_y.tolist() and Y_y.tolist() == Z_y.tolist()
assert t_X_y.tolist() == t_Y_y.tolist() and t_Y_y.tolist() == t_Z_y.tolist()
X = np.column_stack([X,Y,Z])
y = X_y
t_X = np.column_stack([t_X, t_Y, t_Z])
t_y = t_X_y
if dataset == 'IAS':
t_2_X = np.column_stack([t_2_X, t_2_Y, t_2_Z])
t_2_y = t_2_X_y
if train_flag == '0' or train_flag == '1':
# direct evaluation
print('Using CAGEs to match pedestrians')
encoder_match_union_directly(X, y, t_X, t_y, './Models/CAGEs_RN_models',
dataset + '_' + attention + '_RN_' + manner + '_' + str(
time_steps) + '_' + str(temperature) + '_' + str(
Frozen) + view + 'pre_' + Model + LSTM_layer + change, dataset)
def get_inputs():
inputs = tf.placeholder(tf.float32, [batch_size, time_steps, series_length], name='inputs')
targets = tf.placeholder(tf.float32, [batch_size, time_steps, series_length], name='targets')
learning_rate = tf.Variable(0.001, trainable=False, dtype=tf.float32, name='learning_rate')
learning_rate_decay_op = learning_rate.assign(learning_rate * 0.5)
target_sequence_length = tf.placeholder(tf.int32, (None, ), name='target_sequence_length')
max_target_sequence_length = tf.reduce_max(target_sequence_length, name='max_target_len')
source_sequence_length = tf.placeholder(tf.int32, (None, ), name='source_sequence_length')
keep_prob = tf.placeholder(tf.float32, name='keep_prob')
return inputs, targets, learning_rate, learning_rate_decay_op, target_sequence_length, max_target_sequence_length, source_sequence_length, keep_prob
def get_data_CASIA_B(dimension, fr):
global view, probe_type
if view != '':
view_num = view.split('_')[1]
if view != '':
view_dir = view + '/'
else:
view_dir = ''
input_data = np.load('Datasets/'+ frames_ps + view_dir + 'CASIA_B_train_npy_data/source_' + dimension + '_CASIA_B_' + str(fr) + '.npy')
input_data = input_data.reshape([-1,time_steps, series_length])
input_data = input_data.tolist()
targets = np.load('Datasets/'+ frames_ps + view_dir +'CASIA_B_train_npy_data/target_' + dimension + '_CASIA_B_' + str(fr) + '.npy')
if time_steps == 25:
targets = targets[:targets.shape[0]//(time_steps*series_length) * (time_steps*series_length)]
targets = targets.reshape([-1,time_steps, series_length])
targets = targets.tolist()
return input_data, targets
def pad_batch(batch_data, pad_int):
'''
padding the first skeleton of target sequence with zeros —— Z
transform the target sequence (1,2,3,...,f) to (Z,1,2,3,...,f-1) as input to decoder in training
parameters:
- batch_data
- pad_int: position (0)
'''
max_sentence = max([len(sentence) for sentence in batch_data])
return [sentence + [pad_int] * (max_sentence - len(sentence)) for sentence in batch_data]
def get_batches(targets, sources, batch_size, source_pad_int, target_pad_int):
for batch_i in range(0, len(sources) // batch_size):
start_i = batch_i * batch_size
sources_batch = sources[start_i:start_i + batch_size]
targets_batch = targets[start_i:start_i + batch_size]
# transform the target sequence (1,2,3,...,f) to (Z,1,2,3,...,f-1) as input to decoder in training
pad_sources_batch = np.array(pad_batch(sources_batch, source_pad_int))
pad_targets_batch = np.array(pad_batch(targets_batch, target_pad_int))
# record the lengths of sequence (not neccessary)
targets_lengths = []
for target in targets_batch:
targets_lengths.append(len(target))
source_lengths = []
for source in sources_batch:
source_lengths.append(len(source))
yield pad_targets_batch, pad_sources_batch, targets_lengths, source_lengths
def get_batches_plain(targets, sources, batch_size, source_pad_int, target_pad_int):
for batch_i in range(0, len(sources) // batch_size):
start_i = batch_i * batch_size
sources_batch = sources[start_i:start_i + batch_size]
targets_batch = sources[start_i:start_i + batch_size]
# transform the target sequence (1,2,3,...,f) to (Z,1,2,3,...,f-1) as input to decoder in training
pad_sources_batch = np.array(pad_batch(sources_batch, source_pad_int))
pad_targets_batch = np.array(pad_batch(targets_batch, target_pad_int))
# record the lengths of sequence (not neccessary)
targets_lengths = []
for target in targets_batch:
targets_lengths.append(len(target))
source_lengths = []
for source in sources_batch:
source_lengths.append(len(source))
yield pad_targets_batch, pad_sources_batch, targets_lengths, source_lengths
def GE(input_data, rnn_size, num_layers, source_sequence_length, encoding_embedding_size):
'''
Gait Encoder (GE)
Parameters:
- input_data: skeleton sequences (X,Y,Z series)
- rnn_size: 256
- num_layers: 2
- source_sequence_length:
- encoding_embedding_size: embedding size
'''
encoder_embed_input = input_data
def get_lstm_cell(rnn_size):
lstm_cell = tf.contrib.rnn.LSTMCell(rnn_size, initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2))
# if use_dropout:
# lstm_cell = tf.contrib.rnn.DropoutWrapper(lstm_cell, output_keep_prob=0.5)
return lstm_cell
if Bi_LSTM:
fw_cell = tf.contrib.rnn.MultiRNNCell([get_lstm_cell(rnn_size) for _ in range(num_layers)])
bw_cell = tf.contrib.rnn.MultiRNNCell([get_lstm_cell(rnn_size) for _ in range(num_layers)])
encoder_output, encoder_state = \
tf.nn.bidirectional_dynamic_rnn(fw_cell, bw_cell, encoder_embed_input, sequence_length=source_sequence_length, dtype=tf.float32)
weights = fw_cell.variables
# print(encoder_state)
# print('1')
# print(encoder_output)
# exit(1)
else:
cell = tf.contrib.rnn.MultiRNNCell([get_lstm_cell(rnn_size) for _ in range(num_layers)])
encoder_output, encoder_state = tf.nn.dynamic_rnn(cell, encoder_embed_input,
sequence_length=source_sequence_length, dtype=tf.float32)
weights = cell.variables
if Bi_LSTM:
# print(encoder_state)
# exit(1)
c_1 = encoder_state[1][1][0] + encoder_state[0][1][0]
h_1 = encoder_state[1][1][1] + encoder_state[0][1][1]
c_0 = encoder_state[1][0][0] + encoder_state[0][0][0]
h_0 = encoder_state[1][0][1] + encoder_state[0][0][1]
# bidirectional_rnn/fw/fw/transpose_1:0
# ReverseSequence: 0
return encoder_output[0], (rnn_cell_impl.LSTMStateTuple(c_0, h_0), rnn_cell_impl.LSTMStateTuple(c_1, h_1)), weights, source_sequence_length
else:
return encoder_output, encoder_state, weights, source_sequence_length
def GD(decoding_embedding_size, num_layers, rnn_size,
target_sequence_length, source_sequence_length, max_target_sequence_length, encoder_output, encoder_state, decoder_input):
'''
Gait Decoder (GD)
parameters:
- decoding_embedding_size: embedding size
- num_layers: 2
- rnn_size: 256
- target_sequence_length: 6
- max_target_sequence_length: 6
- encoder_state: gait encoded state
- decoder_input:
'''
decoder_embed_input = decoder_input
def get_decoder_cell(rnn_size):
decoder_cell = tf.contrib.rnn.LSTMCell(rnn_size,
initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2))
return decoder_cell
cell = tf.contrib.rnn.MultiRNNCell([get_decoder_cell(rnn_size) for _ in range(num_layers)])
if use_attention:
attention_mechanism = tf.contrib.seq2seq.LuongAttention(num_units=rnn_size, memory=encoder_output,
memory_sequence_length=source_sequence_length)
cell = tf.contrib.seq2seq.AttentionWrapper(cell=cell, attention_mechanism=attention_mechanism,
attention_layer_size=rnn_size, alignment_history=True, output_attention=True,
name='Attention_Wrapper')
# FC layer
output_layer = Dense(series_length,
use_bias=True,
kernel_initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.1))
with tf.variable_scope("decode"):
training_helper = tf.contrib.seq2seq.TrainingHelper(inputs=decoder_embed_input,
sequence_length=target_sequence_length,
time_major=False)
if not use_attention:
training_decoder = tf.contrib.seq2seq.BasicDecoder(cell,
training_helper,
encoder_state,
output_layer)
else:
decoder_initial_state = cell.zero_state(batch_size=batch_size, dtype=tf.float32).clone(
cell_state=encoder_state)
training_decoder = tf.contrib.seq2seq.BasicDecoder(cell,
training_helper,
initial_state=decoder_initial_state,
output_layer=output_layer,
)
training_decoder_output, training_decoder_state, _ = tf.contrib.seq2seq.dynamic_decode(training_decoder,
impute_finished=True,
maximum_iterations=max_target_sequence_length)
with tf.variable_scope("decode", reuse=True):
def initialize_fn():
finished = tf.tile([False], [batch_size])
start_inputs = decoder_embed_input[:, 0]
return (finished, start_inputs)
def sample_fn(time, outputs, state):
del time, state
return tf.constant([0] * batch_size)
def next_inputs_fn(time, outputs, state, sample_ids):
del sample_ids
finished = time >= tf.shape(decoder_embed_input)[1]
all_finished = tf.reduce_all(finished)
next_inputs = tf.cond(
all_finished,
lambda: tf.zeros_like(outputs),
lambda: outputs)
return (finished, next_inputs, state)
predicting_helper = tf.contrib.seq2seq.CustomHelper(initialize_fn=initialize_fn,
sample_fn=sample_fn,
next_inputs_fn=next_inputs_fn)
if not use_attention:
predicting_decoder = tf.contrib.seq2seq.BasicDecoder(cell,
predicting_helper,
encoder_state,
output_layer)
else:
decoder_initial_state = cell.zero_state(batch_size=batch_size, dtype=tf.float32).clone(
cell_state=encoder_state)
predicting_decoder = tf.contrib.seq2seq.BasicDecoder(cell,
predicting_helper,
initial_state=decoder_initial_state,
output_layer=output_layer)
predicting_decoder_output, predicting_decoder_state, _ = tf.contrib.seq2seq.dynamic_decode(predicting_decoder,
impute_finished=True,
maximum_iterations=max_target_sequence_length)
return training_decoder_output, predicting_decoder_output, training_decoder_state, predicting_decoder_state
def process_decoder_input(data, batch_size):
'''
transform the target sequence (1,2,3,...,f) to (Z,1,2,3,...,f-1) as input to decoder in training
'''
ending = tf.strided_slice(data, [0, 0, 0], [batch_size, -1, series_length], [1, 1, 1])
decoder_input = tf.concat([tf.fill([batch_size, time_steps, series_length], 0.), ending], 1)
return decoder_input
def encoder_decoder(input_data, targets, lr, target_sequence_length,
max_target_sequence_length, source_sequence_length,
encoder_embedding_size, decoder_embedding_size,
rnn_size, num_layers):
encoding_embedding_size = 128
decoding_embedding_size = 128
encoder_output, encoder_state, weights, source_sequence_length = GE(input_data,
rnn_size,
num_layers,
source_sequence_length,
encoding_embedding_size)
decoder_input = process_decoder_input(targets, batch_size)
lstm_weights_1 = tf.Variable(weights[0], dtype=tf.float32, name='lstm_weights_layer_1')
lstm_weights_2 = tf.Variable(weights[3], dtype=tf.float32, name='lstm_weights_layer_2')
training_decoder_output, predicting_decoder_output, training_state, predicting_state = GD(
decoding_embedding_size,
num_layers,
rnn_size,
target_sequence_length,
source_sequence_length,
max_target_sequence_length,
encoder_output,
encoder_state,
decoder_input)
if use_attention:
attention_matrices = training_state.alignment_history.stack()
return training_decoder_output, predicting_decoder_output, lstm_weights_1, lstm_weights_2, attention_matrices
else:
return training_decoder_output, predicting_decoder_output, lstm_weights_1, lstm_weights_2
def train(folder_name, dim, train_dataset=False):
global series_length, time_steps, dataset, attention, Frozen, epochs
if train_dataset == 'KGBD':
input_data_, targets_ = get_data_KGBD(dim, fr=time_steps)
epochs = 150
elif train_dataset == 'IAS':
input_data_, targets_ = get_data_IAS(dim, fr=time_steps)
elif train_dataset == 'BIWI':
input_data_, targets_, t_input_data_, t_targets_ = get_data_BIWI(dim, fr=time_steps)
elif train_dataset == 'CASIA_B':
input_data_, targets_ = get_data_CASIA_B(dim, fr=time_steps)
if normalize:
# normalized joint 0
input_data_ = np.array(input_data_)
targets_ = np.array(targets_)
input_data_ = (input_data_ - np.tile(np.expand_dims(input_data_[:, :, 0], axis=-1), [1, 1, series_length]))
targets_ = (targets_ - np.tile(np.expand_dims(targets_[:, :, 0], axis=-1), [1, 1, series_length]))
else:
input_data_= np.array(input_data_).reshape([-1, time_steps*series_length])
targets_ = np.array(targets_).reshape([-1, time_steps*series_length])
# print(input_data_.shape, np.min(input_data_, axis=0).shape)
# print(targets_.shape, np.min(targets_, axis=0).shape)
# exit()
input_data_ = (input_data_ - np.min(input_data_, axis=0)) / \
(np.max(input_data_, axis=0) - np.min(input_data_, axis=0) + 1)
targets_ = (targets_ - np.min(targets_, axis=0)) / \
(np.max(targets_, axis=0) - np.min(targets_, axis=0) + 1)
input_data_ = np.array(input_data_).reshape([-1, time_steps, series_length])
targets_ = np.array(targets_).reshape([-1, time_steps, series_length])
input_data_ = input_data_.tolist()
targets_ = targets_.tolist()
# # if dim == 'z':
# print(input_data_.shape, targets_.shape)
# print(input_data_[0])
# return
elif train_dataset == 'KS20':
input_data_, targets_ = get_data_KS20(dim, fr=time_steps)
else:
raise Error('No dataset is chosen!')
if not Reverse:
targets_ = copy.deepcopy(input_data_)
if train_dataset == 'BIWI':
t_targets_ = copy.deepcopy(t_input_data_)
train_graph = tf.Graph()
encoding_embedding_size = 128
decoding_embedding_size = 128
with train_graph.as_default():
input_data, targets, lr, lr_decay_op, target_sequence_length, max_target_sequence_length, source_sequence_length, keep_prob = get_inputs()
if use_attention:
training_decoder_output, predicting_decoder_output, lstm_weights_1, lstm_weights_2, attention_matrices = encoder_decoder(input_data,
targets,
lr,
target_sequence_length,
max_target_sequence_length,
source_sequence_length,
encoding_embedding_size,
decoding_embedding_size,
rnn_size,
num_layers)
else:
training_decoder_output, predicting_decoder_output, lstm_weights_1, lstm_weights_2 = encoder_decoder(input_data,
targets,
lr,
target_sequence_length,
max_target_sequence_length,
source_sequence_length,
encoding_embedding_size,
decoding_embedding_size,
rnn_size,
num_layers)
training_decoder_output = training_decoder_output.rnn_output
predicting_output = tf.identity(predicting_decoder_output.rnn_output, name='predictions')
training_output = tf.identity(predicting_decoder_output.rnn_output, name='train_output')
train_loss = tf.reduce_mean(tf.nn.l2_loss(training_decoder_output - targets))
real_loss = tf.identity(train_loss, name='real_loss')
encoder_output = train_graph.get_tensor_by_name('rnn/transpose_1:0')
if use_attention:
attention_matrices = tf.identity(attention_matrices, name='train_attention_matrix')
# Locality-oriented attention loss
if attention == 'LA' or attention == 'LA-R':
objective_attention = np.ones(shape=[time_steps, time_steps])
for index, _ in enumerate(objective_attention.tolist()):
if not Reverse:
pt = index
else:
pt = time_steps - 1 - index
D = time_steps
objective_attention[index][pt] = 1
for i in range(1, D+1):
if pt + i <= time_steps - 1:
objective_attention[index][min(pt + i, time_steps - 1)] = np.exp(-(i)**2/(2*(D/2)**2))
if pt-i >= 0:
objective_attention[index][max(pt-i, 0)] = np.exp(-(i)**2/(2*(D/2)**2))
objective_attention[index][pt] = 1
objective_attention = np.tile(objective_attention, [batch_size, 1, 1])
objective_attention = objective_attention.swapaxes(1,0)
att_loss = tf.reduce_mean(tf.nn.l2_loss(attention_matrices - attention_matrices * objective_attention))
train_loss += att_loss
if Frozen == '0':
attention_trans = tf.transpose(attention_matrices, [1, 0, 2])
AGEs = tf.matmul(attention_trans, encoder_output)
AGEs = tf.reshape(AGEs, [batch_size, -1])
first_size = rnn_size * time_steps
# C_input = tf.placeholder(tf.float32, [None, first_size], name='C_input')
C_lr = tf.Variable(0.0005, trainable=False, dtype=tf.float32, name='learning_rate')
# learning_rate_1:0
W1 = tf.Variable(tf.random_normal([first_size, rnn_size]), name='W1')
b1 = tf.Variable(tf.zeros(shape=[rnn_size, ]), name='b1')
Wx_plus_b1 = tf.matmul(AGEs, W1) + b1
l1 = tf.nn.relu(Wx_plus_b1)
W = tf.Variable(tf.random_normal([rnn_size, rnn_size]), name='W')
b = tf.Variable(tf.zeros(shape=[rnn_size, ], name='b'))
contrast_v = tf.matmul(l1, W) + b
# print (encoder_output)
# print(attention_trans)
# print(AGEs)
# print(contrast_v)
# exit(1)
# add_2:0
# with tf.name_scope("C_train"):
t = temperature
C_optimizer = tf.train.AdamOptimizer(learning_rate, name="Adam_C")
z1 = contrast_v[1:]
z2 = contrast_v[:-1]
z = tf.concat((z1, z2), axis=0)
unorm_sim = tf.matmul(z, tf.transpose(z))
z_norm = tf.sqrt(tf.reduce_sum(tf.pow(z, 2), axis=1))
z_norm = tf.expand_dims(z_norm, axis=1)
norm_matrix = tf.matmul(z_norm, tf.transpose(z_norm))
sim = unorm_sim / (t * norm_matrix)
C_loss = tf.zeros(1)
sample_num = batch_size - 1
for i in range(sample_num):
C_loss = C_loss - tf.log(
tf.exp(sim[i, i + sample_num]) / (tf.reduce_sum(tf.exp(sim[i, :])) - tf.exp(sim[i, i])))
C_loss = C_loss - tf.log(tf.exp(sim[i + sample_num, i]) / (
tf.reduce_sum(tf.exp(sim[i + sample_num, :])) - tf.exp(
sim[i + sample_num, i + sample_num])))
C_loss = C_loss / (2 * sample_num)
# C_train_op = C_optimizer.minimize(C_loss)
train_loss += C_loss
# print (C_lr, C_loss, contrast_v)
# <tf.Variable 'learning_rate_1:0' shape=() dtype=float32_ref>
# Tensor("C_train/truediv_255:0", shape=(1,), dtype=float32)
# Tensor("add_2:0", shape=(128, 256), dtype=float32)
# exit(1)
else:
h_s = tf.reshape(encoder_output, [batch_size, -1])
first_size = rnn_size * time_steps
C_lr = tf.Variable(0.0005, trainable=False, dtype=tf.float32, name='learning_rate')
W1 = tf.Variable(tf.random_normal([first_size, rnn_size]), name='W1')
b1 = tf.Variable(tf.zeros(shape=[rnn_size, ]), name='b1')
Wx_plus_b1 = tf.matmul(h_s, W1) + b1
l1 = tf.nn.relu(Wx_plus_b1)
W = tf.Variable(tf.random_normal([rnn_size, rnn_size]), name='W')
b = tf.Variable(tf.zeros(shape=[rnn_size, ], name='b'))
contrast_v = tf.matmul(l1, W) + b
t = temperature
C_optimizer = tf.train.AdamOptimizer(learning_rate, name="Adam_C")
z1 = contrast_v[1:]
z2 = contrast_v[:-1]
z = tf.concat((z1, z2), axis=0)
unorm_sim = tf.matmul(z, tf.transpose(z))
z_norm = tf.sqrt(tf.reduce_sum(tf.pow(z, 2), axis=1))
z_norm = tf.expand_dims(z_norm, axis=1)
norm_matrix = tf.matmul(z_norm, tf.transpose(z_norm))
sim = unorm_sim / (t * norm_matrix)
C_loss = tf.zeros(1)
sample_num = batch_size - 1
for i in range(sample_num):
C_loss = C_loss - tf.log(
tf.exp(sim[i, i + sample_num]) / (tf.reduce_sum(tf.exp(sim[i, :])) - tf.exp(sim[i, i])))
C_loss = C_loss - tf.log(tf.exp(sim[i + sample_num, i]) / (
tf.reduce_sum(tf.exp(sim[i + sample_num, :])) - tf.exp(
sim[i + sample_num, i + sample_num])))
C_loss = C_loss / (2 * sample_num)
train_loss += C_loss
l2 = lambda_l2_reg * sum(
tf.nn.l2_loss(tf_var)
for tf_var in tf.trainable_variables()
if not ("noreg" in tf_var.name or "Bias" in tf_var.name)
)
# train_loss += att_loss
cost = tf.add(l2, train_loss, name='cost')
with tf.name_scope("optimization"):
# Optimizer
optimizer = tf.train.AdamOptimizer(lr, name='Adam')
# Gradient Clipping
gradients = optimizer.compute_gradients(cost)
capped_gradients = [(tf.clip_by_value(grad, -5., 5.), var) for grad, var in gradients if grad is not None]
train_op = optimizer.apply_gradients(capped_gradients, name='train_op')
# Contrast learning after freezing AGEs
if Frozen == '1':
first_size = rnn_size * time_steps
C_input = tf.placeholder(tf.float32, [None, first_size], name='C_input')
lr = tf.Variable(0.0005, trainable=False, dtype=tf.float32, name='learning_rate')
# learning_rate_1:0
W1 = tf.Variable(tf.random_normal([first_size, rnn_size]), name='W1')
b1 = tf.Variable(tf.zeros(shape=[rnn_size, ]), name='b1')
Wx_plus_b1 = tf.matmul(C_input, W1) + b1
l1 = tf.nn.relu(Wx_plus_b1)
W = tf.Variable(tf.random_normal([rnn_size, rnn_size]), name='W')
b = tf.Variable(tf.zeros(shape=[rnn_size, ], name='b'))
contrast_v = tf.matmul(l1, W) + b
# add_16:0
with tf.name_scope("C_train"):
t = temperature
C_optimizer = tf.train.AdamOptimizer(learning_rate, name="Adam_C")
z1 = contrast_v[1:]
z2 = contrast_v[:-1]
# cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y_input))
# (batch_size-1, )
z = tf.concat((z1, z2), axis=0)
unorm_sim = tf.matmul(z, tf.transpose(z))
z_norm = tf.sqrt(tf.reduce_sum(tf.pow(z, 2), axis=1))
z_norm = tf.expand_dims(z_norm, axis=1)
# z_norm = z_norm.unsqueeze(1)
norm_matrix = tf.matmul(z_norm, tf.transpose(z_norm))
# norm_matrix = z_norm.mm(z_norm.t())
sim = unorm_sim / (t * norm_matrix)
# print (z, unorm_sim, z_norm, norm_matrix, sim)
# exit(1)
# sim = unorm_sim / (self.t * norm_matrix)
# # print(sim[batch_size+2, 5])
# # print(sim[5, batch_size+2])
# # exit(1)
# loss = torch.zeros(1, requires_grad=True)
C_loss = tf.zeros(1)
# loss = Variable(loss.type(Tensor))
# sample_num = z1.size(0)
sample_num = batch_size - 1
# for i in range(sample_num):
# loss = loss - torch.log(
# torch.exp(sim[i, i + sample_num]) / (torch.sum(torch.exp(sim[i, :])) - torch.exp(sim[i, i])))
# loss = loss - torch.log(torch.exp(sim[i + sample_num, i]) / (
# torch.sum(torch.exp(sim[i + sample_num, :])) - torch.exp(
# sim[i + sample_num, i + sample_num])))
for i in range(sample_num):
C_loss = C_loss - tf.log(
tf.exp(sim[i, i + sample_num]) / (tf.reduce_sum(tf.exp(sim[i, :])) - tf.exp(sim[i, i])))
C_loss = C_loss - tf.log(tf.exp(sim[i + sample_num, i]) / (
tf.reduce_sum(tf.exp(sim[i + sample_num, :])) - tf.exp(
sim[i + sample_num, i + sample_num])))
C_loss = C_loss / (2 * sample_num)
# gradients = optimizer.compute_gradients(cost)
# capped_gradients = [(tf.clip_by_value(grad, -5., 5.), var) for grad, var in gradients if grad is not None]
C_train_op = C_optimizer.minimize(C_loss)
# correct_pred = tf.equal(tf.argmax(pred, 1),tf.argmax(y_input, 1))
# accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
input_data_ = np.array(input_data_)
targets_ = np.array(targets_)
# just not permuated first
# permutation = np.random.permutation(input_data_.shape[0])
# input_data_= input_data_[permutation]
# targets_ = targets_[permutation]
train_source = input_data_
train_target = targets_
train_source = train_source.tolist()
train_target =train_target.tolist()
# input_data_ = input_data_.tolist()
# targets_ = targets_.tolist()
valid_source = train_source[:batch_size]
valid_target = train_target[:batch_size]
# print(len(train_source), len(train_target), len(valid_source), len(valid_target))
(valid_targets_batch, valid_sources_batch, valid_targets_lengths, valid_sources_lengths) = next(
get_batches(valid_target, valid_source, batch_size, source_pad_int=0, target_pad_int=0))
display_step = 50
checkpoint = "./" + folder_name + "/trained_model.ckpt"
best_checkpoint = './' + folder_name + '/best_model.ckpt'
with tf.Session(graph=train_graph, config=config) as sess:
sess.run(tf.global_variables_initializer())
print('Begin Training on Dimension [' + dim.upper() + ']')
train_loss = []
test_loss = []
c_train_loss = []
losses = [0, 0, 0]
loss_cnt = 0
conv_cnt = 0
best_val = 100000
over_flag = False
if use_attention:
alignment_history = train_graph.get_tensor_by_name('train_attention_matrix:0')
encoder_output = train_graph.get_tensor_by_name('rnn/transpose_1:0')
for epoch_i in range(1, epochs + 1):
if over_flag:
break
for batch_i, (targets_batch, sources_batch, targets_lengths, sources_lengths) in enumerate(
get_batches(train_target, train_source, batch_size, source_pad_int=0, target_pad_int=0)):
# print (sources_batch[5, 3:, :])
# print (sources_batch[6, :3, :])
# print (sources_batch[9, 3:, :])
# print (sources_batch[10, :3, :])
# exit(1)
if use_attention:
if Frozen == '0':
_, loss, c_loss, att, en_outputs, att_history = sess.run(
[train_op, real_loss, C_loss, attention_matrices, encoder_output, alignment_history],
{input_data: sources_batch,
targets: targets_batch,
lr: learning_rate,
C_lr: learning_rate,
target_sequence_length: targets_lengths,
source_sequence_length: sources_lengths,
keep_prob: 0.5})
else:
_, loss, att, en_outputs, att_history = sess.run([train_op, real_loss, attention_matrices, encoder_output, alignment_history],
{input_data: sources_batch,
targets: targets_batch,
lr: learning_rate,
target_sequence_length: targets_lengths,
source_sequence_length: sources_lengths,
keep_prob: 0.5})
att_batch = []
for index in range(en_outputs.shape[0]):
t1 = np.reshape(en_outputs[index], [-1]).tolist()
if use_attention and AGEs:
weights = att_history[:, index, :]
f_o = en_outputs[index, :, :]
att_op = np.matmul(weights, f_o)
# if manner == 'sc':
att_op = np.reshape(att_op, [-1]).tolist()
att_batch.append(att_op)
att_batch = np.array(att_batch)
_, c_loss, c_vec = sess.run([C_train_op, C_loss, contrast_v],
{C_input: att_batch,
lr: learning_rate
})
# print(c_loss)
# else:
# X.extend(att_op.tolist())
else:
_, loss = sess.run([train_op, real_loss],
{input_data: sources_batch,
targets: targets_batch,
lr: learning_rate,
target_sequence_length: targets_lengths,
source_sequence_length: sources_lengths,
keep_prob: 0.5})
# if batch_i % display_step == 0:
if epoch_i % 1 == 0:
if Frozen == '0':
validation_loss, c_loss = sess.run(
[real_loss, C_loss],
{input_data: valid_sources_batch,
targets: valid_targets_batch,
lr: learning_rate,
C_lr: learning_rate,
target_sequence_length: valid_targets_lengths,
source_sequence_length: valid_sources_lengths,
keep_prob: 1.0})
else:
validation_loss = sess.run(
[real_loss],
{input_data: valid_sources_batch,
targets: valid_targets_batch,
lr: learning_rate,
target_sequence_length: valid_targets_lengths,
source_sequence_length: valid_sources_lengths,
keep_prob: 1.0})
# if epoch_i % 25 == 0 and validation_loss[0] < best_val:
# saver = tf.train.Saver()
# saver.save(sess, best_checkpoint)
# print('The Best Model Saved Again')
# best_val = validation_loss[0]
train_loss.append(loss)
if Frozen == '1':
c_train_loss.append(c_loss[0])
test_loss.append(validation_loss[0])
losses[loss_cnt % 3] = validation_loss[0]
print(
'Epoch {:>3}/{} Batch {:>4}/{} - Training Loss: {:>6.3f} - Validation loss: {:>6.3f} - Contrastive loss: {:>6.3f}'
.format(epoch_i,
epochs,
batch_i,
len(train_source) // batch_size,
loss,
validation_loss[0],
c_loss[0]))
else:
c_train_loss.append(c_loss[0])
test_loss.append(validation_loss)
losses[loss_cnt % 3] = validation_loss
print(
'Epoch {:>3}/{} Batch {:>4}/{} - Training Loss: {:>6.3f} - Validation loss: {:>6.3f} - Contrastive loss: {:>6.3f}'
.format(epoch_i,
epochs,
batch_i,
len(train_source) // batch_size,
loss,
validation_loss,
c_loss[0]))
loss_cnt += 1
# print(losses)
if conv_cnt > 0 and validation_loss[0] >= max(losses):
over_flag = True
break
if (round(losses[(loss_cnt - 1) % 3], 5) == round(losses[loss_cnt % 3], 5)) and (round(losses[(loss_cnt - 2) % 3], 5)\
== round(losses[loss_cnt % 3], 5)) :
sess.run(lr_decay_op)
conv_cnt += 1
saver = tf.train.Saver()
saver.save(sess, checkpoint)
print('Model Trained and Saved')
np.save(folder_name + '/train_loss.npy', np.array(train_loss))
np.save(folder_name + '/test_loss.npy', np.array(test_loss))
np.save(folder_name + '/c_train_loss.npy', np.array(c_train_loss))
def encoder_classify(model_name, dimension, type, dataset):
global manner, transfer, LSTM_layer, gallery_num, view
if view != '':
view_num = view.split('_')[1]
number = ord(dimension) - ord('x') + 1
print('Run the gait encoding model to obtain CAGEs (%d / 3)' % number)
global epochs, series_length, attention, Frozen, C_reid
epochs = 200
if view != '':
view_dir = view + '/'
else:
if probe_type != '':
gallery_dir = probe_type.split('.')[1] + '/'
probe_dir = probe_type.split('.')[0] + '/'
# w_dir = probe_type + '/'
else:
view_dir = ''
_input_data = np.load(
'Datasets/' + frames_ps + dataset + '_test_npy_data/' + gallery_dir + 't_source_' + dimension + '_' + dataset + '_' + str(
time_steps) + '.npy')
if time_steps == 25:
_input_data = _input_data[:_input_data.shape[0] // (time_steps * series_length) * (time_steps * series_length)]
_input_data = _input_data.reshape([-1, time_steps, series_length])
if Model == 'rev_rec' or Model == 'rev_rec_plus':
_targets = np.load(
'Datasets/' + frames_ps + dataset + '_test_npy_data/' + gallery_dir + 't_target_' + dimension + '_' + dataset + '_' + str(
time_steps) + '.npy')
_targets = _targets.reshape([-1, time_steps, series_length])
# prediction
elif Model == 'prediction':
_targets = np.concatenate((_input_data[1:, :, :], _input_data[-1, :, :].reshape([1, time_steps, series_length])),
axis=0)
# _input_data = _input_data[:-1]
# permutation
elif Model == 'sorting':
_targets = copy.deepcopy(_input_data)
for i in range(_input_data.shape[0]):
permutation_ = np.random.permutation(time_steps)
_input_data[i] = _input_data[i, permutation_]
if dataset == 'IAS':
t_input_data = np.load(
'Datasets/' + frames_ps + dataset + '_test_npy_data/t_source_' + dimension + '_' + dataset + '-A_' + str(
time_steps) + '.npy')
t_input_data = t_input_data.reshape([-1, time_steps, series_length])
if Model == 'rev_rec' or Model == 'rev_rec_plus':
t_targets = np.load(