-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaction_predict.py
3457 lines (3014 loc) · 155 KB
/
action_predict.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 time
import yaml
import wget
import cv2
from utils import *
import tensorflow as tf
from transformer import Encoder
from base_models import AlexNet, C3DNet, convert_to_fcn
from base_models import I3DNet
import tensorflow_addons as tfa
from tensorflow.keras import layers
from tensorflow.keras.layers import Input, Concatenate, Dense, MultiHeadAttention
from tensorflow.keras.layers import GRU, LSTM, GRUCell
from tensorflow.keras.layers import Dropout, LSTMCell, RNN
from tensorflow.keras.utils import plot_model
from tensorflow.keras.layers import Flatten, Average, Add
from tensorflow.keras.layers import ConvLSTM2D, Conv2D
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint
from tensorflow.keras.applications import vgg16, resnet50
from tensorflow.keras.layers import GlobalAveragePooling2D, GlobalMaxPooling2D, Lambda, dot, concatenate, Activation
from tensorflow.keras.optimizers import Adam, SGD, RMSprop
from tensorflow.keras import regularizers
from tensorflow.keras import backend as K
from tensorflow.keras.utils import Sequence
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.metrics import roc_auc_score, roc_curve, precision_recall_curve
from sklearn.svm import LinearSVC
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
def create_padding_mask(seqs):
# We mask only those vectors of the sequence in which we have all zeroes
# (this is more scalable for some situations).
mask = tf.cast(tf.reduce_all(tf.math.equal(seqs, 0), axis=-1), tf.float32)
return mask[:, tf.newaxis, tf.newaxis, :] # (batch_size, 1, 1, seq_len)
# TODO: Make all global class parameters to minimum , e.g. no model generation
class ActionPredict(object):
"""
A base interface class for creating prediction models
"""
def __init__(self,
global_pooling='avg',
regularizer_val=0.0001,
backbone='vgg16',
**kwargs):
"""
Class init function
Args:
global_pooling: Pooling method for generating convolutional features
regularizer_val: Regularization value for training
backbone: Backbone for generating convolutional features
"""
# Network parameters
self._regularizer_value = regularizer_val
self._regularizer = regularizers.l2(regularizer_val)
self._global_pooling = global_pooling
self._backbone = backbone
self._generator = None # use data generator for train/test
# Processing images anf generate features
def load_images_crop_and_process(self, img_sequences, bbox_sequences,
ped_ids, save_path,
data_type='train',
crop_type='none',
crop_mode='warp',
crop_resize_ratio=2,
target_dim=(224, 224),
process=True,
regen_data=False):
"""
Generate visual feature sequences by reading and processing images
Args:
img_sequences: Sequences of image na,es
bbox_sequences: Sequences of bounding boxes
ped_ids: Sequences of pedestrian ids
save_path: Path to the root folder to save features
data_type: The type of features, train/test/val
crop_type: The method to crop the images.
Options are 'none' (no cropping)
'bbox' (crop using bounding box coordinates),
'context' (A region containing pedestrian and their local surround)
'surround' (only the region around the pedestrian. Pedestrian appearance
is suppressed)
crop_mode: How to resize ond/or pad the corpped images (see utils.img_pad)
crop_resize_ratio: The ratio by which the image is enlarged to capture the context
Used by crop types 'context' and 'surround'.
target_dim: Dimension of final visual features
process: Whether process the raw images using a neural network
regen_data: Whether regenerate visual features. This will overwrite the cached features
Returns:
Numpy array of visual features
Tuple containing the size of features
"""
# load the feature files if exists
print("Generating {} features crop_type={} crop_mode={}\
\nsave_path={}, ".format(data_type, crop_type, crop_mode,
save_path))
preprocess_dict = {'vgg16': vgg16.preprocess_input, 'resnet50': resnet50.preprocess_input}
backbone_dict = {'vgg16': vgg16.VGG16, 'resnet50': resnet50.ResNet50}
preprocess_input = preprocess_dict.get(self._backbone, None)
if process:
assert (self._backbone in ['vgg16', 'resnet50']), "{} is not supported".format(self._backbone)
convnet = backbone_dict[self._backbone](input_shape=(224, 224, 3),
include_top=False, weights='imagenet') if process else None
sequences = []
bbox_seq = bbox_sequences.copy()
i = -1
for seq, pid in zip(img_sequences, ped_ids):
i += 1
update_progress(i / len(img_sequences))
img_seq = []
for imp, b, p in zip(seq, bbox_seq[i], pid):
flip_image = False
set_id = imp.split('/')[-3]
vid_id = imp.split('/')[-2]
img_name = imp.split('/')[-1].split('.')[0]
img_save_folder = os.path.join(save_path, set_id, vid_id)
# Modify the path depending on crop mode
if crop_type == 'none':
img_save_path = os.path.join(img_save_folder, img_name + '.pkl')
else:
img_save_path = os.path.join(img_save_folder, img_name + '_' + p[0] + '.pkl')
# Check whether the file exists
if os.path.exists(img_save_path) and not regen_data:
if not self._generator:
with open(img_save_path, 'rb') as fid:
try:
img_features = pickle.load(fid)
except:
img_features = pickle.load(fid, encoding='bytes')
else:
if 'flip' in imp:
imp = imp.replace('_flip', '')
flip_image = True
if crop_type == 'none':
img_data = cv2.imread(imp)
img_features = cv2.resize(img_data, target_dim)
if flip_image:
img_features = cv2.flip(img_features, 1)
else:
img_data = cv2.imread(imp)
if flip_image:
img_data = cv2.flip(img_data, 1)
if crop_type == 'bbox':
b = list(map(int, b[0:4]))
cropped_image = img_data[b[1]:b[3], b[0]:b[2], :]
img_features = img_pad(cropped_image, mode=crop_mode, size=target_dim[0])
elif 'context' in crop_type:
bbox = jitter_bbox(imp, [b], 'enlarge', crop_resize_ratio)[0]
bbox = squarify(bbox, 1, img_data.shape[1])
bbox = list(map(int, bbox[0:4]))
cropped_image = img_data[bbox[1]:bbox[3], bbox[0]:bbox[2], :]
img_features = img_pad(cropped_image, mode='pad_resize', size=target_dim[0])
elif 'surround' in crop_type:
b_org = list(map(int, b[0:4])).copy()
bbox = jitter_bbox(imp, [b], 'enlarge', crop_resize_ratio)[0]
bbox = squarify(bbox, 1, img_data.shape[1])
bbox = list(map(int, bbox[0:4]))
img_data[b_org[1]:b_org[3], b_org[0]:b_org[2], :] = 128
cropped_image = img_data[bbox[1]:bbox[3], bbox[0]:bbox[2], :]
img_features = img_pad(cropped_image, mode='pad_resize', size=target_dim[0])
else:
raise ValueError('ERROR: Undefined value for crop_type {}!'.format(crop_type))
if preprocess_input is not None:
img_features = preprocess_input(img_features)
if process:
expanded_img = np.expand_dims(img_features, axis=0)
img_features = convnet.predict(expanded_img)
# Save the file
if not os.path.exists(img_save_folder):
os.makedirs(img_save_folder)
with open(img_save_path, 'wb') as fid:
pickle.dump(img_features, fid, pickle.HIGHEST_PROTOCOL)
# if using the generator save the cached features path and size of the features
if process and not self._generator:
if self._global_pooling == 'max':
img_features = np.squeeze(img_features)
img_features = np.amax(img_features, axis=0)
img_features = np.amax(img_features, axis=0)
elif self._global_pooling == 'avg':
img_features = np.squeeze(img_features)
img_features = np.average(img_features, axis=0)
img_features = np.average(img_features, axis=0)
else:
img_features = img_features.ravel()
if self._generator:
img_seq.append(img_save_path)
else:
img_seq.append(img_features)
sequences.append(img_seq)
sequences = np.array(sequences)
# compute size of the features after the processing
if self._generator:
with open(sequences[0][0], 'rb') as fid:
feat_shape = pickle.load(fid).shape
if process:
if self._global_pooling in ['max', 'avg']:
feat_shape = feat_shape[-1]
else:
feat_shape = np.prod(feat_shape)
if not isinstance(feat_shape, tuple):
feat_shape = (feat_shape,)
feat_shape = (np.array(bbox_sequences).shape[1],) + feat_shape
else:
feat_shape = sequences.shape[1:]
return sequences, feat_shape
# Processing images anf generate features
def get_optical_flow(self, img_sequences, bbox_sequences,
ped_ids, save_path,
data_type='train',
crop_type='none',
crop_mode='warp',
crop_resize_ratio=2,
target_dim=(224, 224),
regen_data=False):
"""
Generate visual feature sequences by reading and processing images
Args:
img_sequences: Sequences of image na,es
bbox_sequences: Sequences of bounding boxes
ped_ids: Sequences of pedestrian ids
save_path: Path to the root folder to save features
data_type: The type of features, train/test/val
crop_type: The method to crop the images.
Options are 'none' (no cropping)
'bbox' (crop using bounding box coordinates),
'context' (A region containing pedestrian and their local surround)
'surround' (only the region around the pedestrian. Pedestrian appearance
is suppressed)
crop_mode: How to resize ond/or pad the corpped images (see utils.img_pad)
crop_resize_ratio: The ratio by which the image is enlarged to capture the context
Used by crop types 'context' and 'surround'.
target_dim: Dimension of final visual features
regen_data: Whether regenerate visual features. This will overwrite the cached features
Returns:
Numpy array of visual features
Tuple containing the size of features
"""
# load the feature files if exists
print("Generating {} features crop_type={} crop_mode={}\
\nsave_path={}, ".format(data_type, crop_type, crop_mode, save_path))
sequences = []
bbox_seq = bbox_sequences.copy()
i = -1
# flow size (h,w)
flow_size = read_flow_file(img_sequences[0][0].replace('images', 'optical_flow').replace('png', 'flo')).shape
img_size = cv2.imread(img_sequences[0][0]).shape
# A ratio to adjust the dimension of bounding boxes (w,h)
box_resize_coef = (flow_size[1]/img_size[1], flow_size[0]/img_size[0])
for seq, pid in zip(img_sequences, ped_ids):
i += 1
update_progress(i / len(img_sequences))
flow_seq = []
for imp, b, p in zip(seq, bbox_seq[i], pid):
flip_image = False
set_id = imp.split('/')[-3]
vid_id = imp.split('/')[-2]
img_name = imp.split('/')[-1].split('.')[0]
optflow_save_folder = os.path.join(save_path, set_id, vid_id)
ofp = imp.replace('images', 'optical_flow').replace('png', 'flo')
# Modify the path depending on crop mode
if crop_type == 'none':
optflow_save_path = os.path.join(optflow_save_folder, img_name + '.flo')
else:
optflow_save_path = os.path.join(optflow_save_folder, img_name + '_' + p[0] + '.flo')
# Check whether the file exists
if os.path.exists(optflow_save_path) and not regen_data:
if not self._generator:
ofp_data = read_flow_file(optflow_save_path)
else:
if 'flip' in imp:
ofp = ofp.replace('_flip', '')
flip_image = True
if crop_type == 'none':
ofp_image = read_flow_file(ofp)
ofp_data = cv2.resize(ofp_image, target_dim)
if flip_image:
ofp_data = cv2.flip(ofp_data, 1)
else:
ofp_image = read_flow_file(ofp)
# Adjust the size of bbox according to the dimensions of flow map
b = list(map(int, [b[0] * box_resize_coef[0], b[1] * box_resize_coef[1],
b[2] * box_resize_coef[0], b[3] * box_resize_coef[1]]))
if flip_image:
ofp_image = cv2.flip(ofp_image, 1)
if crop_type == 'bbox':
cropped_image = ofp_image[b[1]:b[3], b[0]:b[2], :]
ofp_data = img_pad(cropped_image, mode=crop_mode, size=target_dim[0])
elif 'context' in crop_type:
bbox = jitter_bbox(imp, [b], 'enlarge', crop_resize_ratio)[0]
bbox = squarify(bbox, 1, ofp_image.shape[1])
bbox = list(map(int, bbox[0:4]))
cropped_image = ofp_image[bbox[1]:bbox[3], bbox[0]:bbox[2], :]
ofp_data = img_pad(cropped_image, mode='pad_resize', size=target_dim[0])
elif 'surround' in crop_type:
b_org = b.copy()
bbox = jitter_bbox(imp, [b], 'enlarge', crop_resize_ratio)[0]
bbox = squarify(bbox, 1, ofp_image.shape[1])
bbox = list(map(int, bbox[0:4]))
ofp_image[b_org[1]:b_org[3], b_org[0]: b_org[2], :] = 0
cropped_image = ofp_image[bbox[1]:bbox[3], bbox[0]:bbox[2], :]
ofp_data = img_pad(cropped_image, mode='pad_resize', size=target_dim[0])
else:
raise ValueError('ERROR: Undefined value for crop_type {}!'.format(crop_type))
# Save the file
if not os.path.exists(optflow_save_folder):
os.makedirs(optflow_save_folder)
write_flow(ofp_data, optflow_save_path)
# if using the generator save the cached features path and size of the features
if self._generator:
flow_seq.append(optflow_save_path)
else:
flow_seq.append(ofp_data)
sequences.append(flow_seq)
sequences = np.array(sequences)
# compute size of the features after the processing
if self._generator:
feat_shape = read_flow_file(sequences[0][0]).shape
if not isinstance(feat_shape, tuple):
feat_shape = (feat_shape,)
feat_shape = (np.array(bbox_sequences).shape[1],) + feat_shape
else:
feat_shape = sequences.shape[1:]
return sequences, feat_shape
def get_data_sequence(self, data_type, data_raw, opts):
"""
Generates raw sequences from a given dataset
Args:
data_type: Split type of data, whether it is train, test or val
data_raw: Raw tracks from the dataset
opts: Options for generating data samples
Returns:
A list of data samples extracted from raw data
Positive and negative data counts
"""
print('\n#####################################')
print('Generating raw data')
print('#####################################')
d = {'center': data_raw['center'].copy(),
'box': data_raw['bbox'].copy(),
'ped_id': data_raw['pid'].copy(),
'crossing': data_raw['activities'].copy(),
'image': data_raw['image'].copy()}
balance = opts['balance_data'] if data_type == 'train' else False
obs_length = opts['obs_length']
time_to_event = opts['time_to_event']
normalize = opts['normalize_boxes']
try:
d['speed'] = data_raw['obd_speed'].copy()
except KeyError:
d['speed'] = data_raw['vehicle_act'].copy()
print('Jaad dataset does not have speed information')
print('Vehicle actions are used instead')
if balance:
self.balance_data_samples(d, data_raw['image_dimension'][0])
d['box_org'] = d['box'].copy()
d['tte'] = []
if isinstance(time_to_event, int):
for k in d.keys():
for i in range(len(d[k])):
d[k][i] = d[k][i][- obs_length - time_to_event:-time_to_event]
d['tte'] = [[time_to_event]]*len(data_raw['bbox'])
else:
overlap = opts['overlap'] # if data_type == 'train' else 0.0
olap_res = obs_length if overlap == 0 else int((1 - overlap) * obs_length)
olap_res = 1 if olap_res < 1 else olap_res
for k in d.keys():
seqs = []
for seq in d[k]:
start_idx = len(seq) - obs_length - time_to_event[1]
end_idx = len(seq) - obs_length - time_to_event[0]
seqs.extend([seq[i:i + obs_length] for i in
range(start_idx, end_idx + 1, olap_res)])
d[k] = seqs
for seq in data_raw['bbox']:
start_idx = len(seq) - obs_length - time_to_event[1]
end_idx = len(seq) - obs_length - time_to_event[0]
d['tte'].extend([[len(seq) - (i + obs_length)] for i in
range(start_idx, end_idx + 1, olap_res)])
if normalize:
for k in d.keys():
if k != 'tte':
if k != 'box' and k != 'center':
for i in range(len(d[k])):
d[k][i] = d[k][i][1:]
else:
for i in range(len(d[k])):
d[k][i] = np.subtract(d[k][i][1:], d[k][i][0]).tolist()
d[k] = np.array(d[k])
else:
for k in d.keys():
d[k] = np.array(d[k])
d['crossing'] = np.array(d['crossing'])[:, 0, :]
pos_count = np.count_nonzero(d['crossing'])
neg_count = len(d['crossing']) - pos_count
print("Negative {} and positive {} sample counts".format(neg_count, pos_count))
return d, neg_count, pos_count
def balance_data_samples(self, d, img_width, balance_tag='crossing'):
"""
Balances the ratio of positive and negative data samples. The less represented
data type is augmented by flipping the sequences
Args:
d: Sequence of data samples
img_width: Width of the images
balance_tag: The tag to balance the data based on
"""
print("Balancing with respect to {} tag".format(balance_tag))
gt_labels = [gt[0] for gt in d[balance_tag]]
num_pos_samples = np.count_nonzero(np.array(gt_labels))
num_neg_samples = len(gt_labels) - num_pos_samples
# finds the indices of the samples with larger quantity
if num_neg_samples == num_pos_samples:
print('Positive and negative samples are already balanced')
else:
print('Unbalanced: \t Positive: {} \t Negative: {}'.format(num_pos_samples, num_neg_samples))
if num_neg_samples > num_pos_samples:
gt_augment = 1
else:
gt_augment = 0
num_samples = len(d[balance_tag])
for i in range(num_samples):
if d[balance_tag][i][0][0] == gt_augment:
for k in d:
if k == 'center':
flipped = d[k][i].copy()
flipped = [[img_width - c[0], c[1]]
for c in flipped]
d[k].append(flipped)
if k == 'box':
flipped = d[k][i].copy()
flipped = [np.array([img_width - b[2], b[1], img_width - b[0], b[3]])
for b in flipped]
d[k].append(flipped)
if k == 'image':
flipped = d[k][i].copy()
flipped = [im.replace('.png', '_flip.png') for im in flipped]
d[k].append(flipped)
if k in ['speed', 'ped_id', 'crossing', 'walking', 'looking']:
d[k].append(d[k][i].copy())
gt_labels = [gt[0] for gt in d[balance_tag]]
num_pos_samples = np.count_nonzero(np.array(gt_labels))
num_neg_samples = len(gt_labels) - num_pos_samples
if num_neg_samples > num_pos_samples:
rm_index = np.where(np.array(gt_labels) == 0)[0]
else:
rm_index = np.where(np.array(gt_labels) == 1)[0]
# Calculate the difference of sample counts
dif_samples = abs(num_neg_samples - num_pos_samples)
# shuffle the indices
np.random.seed(42)
np.random.shuffle(rm_index)
# reduce the number of indices to the difference
rm_index = rm_index[0:dif_samples]
# update the data
for k in d:
seq_data_k = d[k]
d[k] = [seq_data_k[i] for i in range(0, len(seq_data_k)) if i not in rm_index]
new_gt_labels = [gt[0] for gt in d[balance_tag]]
num_pos_samples = np.count_nonzero(np.array(new_gt_labels))
print('Balanced:\t Positive: %d \t Negative: %d\n'
% (num_pos_samples, len(d[balance_tag]) - num_pos_samples))
def get_context_data(self, model_opts, data, data_type, feature_type):
print('\n#####################################')
print('Generating {} {}'.format(feature_type, data_type))
print('#####################################')
process = model_opts.get('process', True)
aux_name = [self._backbone]
if not process:
aux_name.append('raw')
aux_name = '_'.join(aux_name).strip('_')
eratio = model_opts['enlarge_ratio']
dataset = model_opts['dataset']
data_gen_params = {'data_type': data_type, 'crop_type': 'none',
'target_dim': model_opts.get('target_dim', (224, 224))}
if 'local_box' in feature_type:
data_gen_params['crop_type'] = 'bbox'
data_gen_params['crop_mode'] = 'pad_resize'
elif 'local_context' in feature_type:
data_gen_params['crop_type'] = 'context'
data_gen_params['crop_resize_ratio'] = eratio
elif 'surround' in feature_type:
data_gen_params['crop_type'] = 'surround'
data_gen_params['crop_resize_ratio'] = eratio
elif 'scene_context' in feature_type:
data_gen_params['crop_type'] = 'none'
save_folder_name = feature_type
if 'flow' not in feature_type:
save_folder_name = '_'.join([feature_type, aux_name])
if 'local_context' in feature_type or 'surround' in feature_type:
save_folder_name = '_'.join([save_folder_name, str(eratio)])
data_gen_params['save_path'], _ = get_path(save_folder=save_folder_name,
dataset=dataset, save_root_folder='data/features')
if 'flow' in feature_type:
return self.get_optical_flow(data['image'],
data['box_org'],
data['ped_id'],
**data_gen_params)
else:
return self.load_images_crop_and_process(data['image'],
data['box_org'],
data['ped_id'],
process=process,
**data_gen_params)
def get_data(self, data_type, data_raw, model_opts):
"""
Generates data train/test/val data
Args:
data_type: Split type of data, whether it is train, test or val
data_raw: Raw tracks from the dataset
model_opts: Model options for generating data
Returns:
A dictionary containing, data, data parameters used for model generation,
effective dimension of data (the number of rgb images to be used calculated accorfing
to the length of optical flow window) and negative and positive sample counts
"""
self._generator = model_opts.get('generator', False)
data_type_sizes_dict = {}
process = model_opts.get('process', True)
dataset = model_opts['dataset']
data, neg_count, pos_count = self.get_data_sequence(data_type, data_raw, model_opts)
data_type_sizes_dict['box'] = data['box'].shape[1:]
if 'speed' in data.keys():
data_type_sizes_dict['speed'] = data['speed'].shape[1:]
# Store the type and size of each image
_data = []
data_sizes = []
data_types = []
for d_type in model_opts['obs_input_type']:
if 'local' in d_type or 'context' in d_type:
features, feat_shape = self.get_context_data(model_opts, data, data_type, d_type)
elif 'pose' in d_type:
path_to_pose, _ = get_path(save_folder='poses',
dataset=dataset,
save_root_folder='data/features')
features = get_pose(data['image'],
data['ped_id'],
data_type=data_type,
file_path=path_to_pose,
dataset=model_opts['dataset'])
feat_shape = features.shape[1:]
else:
features = data[d_type]
feat_shape = features.shape[1:]
_data.append(features)
data_sizes.append(feat_shape)
data_types.append(d_type)
# create the final data file to be returned
if self._generator:
_data = (DataGenerator(data=_data,
labels=data['crossing'],
data_sizes=data_sizes,
process=process,
global_pooling=self._global_pooling,
input_type_list=model_opts['obs_input_type'],
batch_size=model_opts['batch_size'],
shuffle=data_type != 'test',
to_fit=data_type != 'test'), data['crossing']) # set y to None
else:
_data = (_data, data['crossing'])
return {'data': _data,
'ped_id': data['ped_id'],
'image': data['image'],
'tte': data['tte'],
'data_params': {'data_types': data_types, 'data_sizes': data_sizes},
'count': {'neg_count': neg_count, 'pos_count': pos_count}}
def log_configs(self, config_path, batch_size, epochs,
lr, model_opts):
# TODO: Update config by adding network attributes
"""
Logs the parameters of the model and training
Args:
config_path: The path to save the file
batch_size: Batch size of training
epochs: Number of epochs for training
lr: Learning rate of training
model_opts: Data generation parameters (see get_data)
"""
# Save config and training param files
with open(config_path, 'wt') as fid:
yaml.dump({'model_opts': model_opts,
'train_opts': {'batch_size':batch_size, 'epochs': epochs, 'lr': lr}},
fid, default_flow_style=False)
# with open(config_path, 'wt') as fid:
# fid.write("####### Model options #######\n")
# for k in opts:
# fid.write("%s: %s\n" % (k, str(opts[k])))
# fid.write("\n####### Network config #######\n")
# # fid.write("%s: %s\n" % ('hidden_units', str(self._num_hidden_units)))
# # fid.write("%s: %s\n" % ('reg_value ', str(self._regularizer_value)))
# fid.write("\n####### Training config #######\n")
# fid.write("%s: %s\n" % ('batch_size', str(batch_size)))
# fid.write("%s: %s\n" % ('epochs', str(epochs)))
# fid.write("%s: %s\n" % ('lr', str(lr)))
print('Wrote configs to {}'.format(config_path))
def class_weights(self, apply_weights, sample_count):
"""
Computes class weights for imbalanced data used during training
Args:
apply_weights: Whether to apply weights
sample_count: Positive and negative sample counts
Returns:
A dictionary of class weights or None if no weights to be calculated
"""
if not apply_weights:
return None
total = sample_count['neg_count'] + sample_count['pos_count']
# formula from sklearn
#neg_weight = (1 / sample_count['neg_count']) * (total) / 2.0
#pos_weight = (1 / sample_count['pos_count']) * (total) / 2.0
# use simple ratio
neg_weight = sample_count['pos_count']/total
pos_weight = sample_count['neg_count']/total
print("### Class weights: negative {:.3f} and positive {:.3f} ###".format(neg_weight, pos_weight))
return {0: neg_weight, 1: pos_weight}
def get_callbacks(self, learning_scheduler, model_path):
"""
Creates a list of callabcks for training
Args:
learning_scheduler: Whether to use callbacks
Returns:
A list of call backs or None if learning_scheduler is false
"""
callbacks = None
# Set up learning schedulers
if learning_scheduler:
callbacks = []
if 'early_stop' in learning_scheduler:
default_params = {'monitor': 'val_loss',
'min_delta': 1.0, 'patience': 5,
'verbose': 1}
default_params.update(learning_scheduler['early_stop'])
callbacks.append(EarlyStopping(**default_params))
if 'plateau' in learning_scheduler:
default_params = {'monitor': 'val_loss',
'factor': 0.2, 'patience': 5,
'min_lr': 1e-08, 'verbose': 1}
default_params.update(learning_scheduler['plateau'])
callbacks.append(ReduceLROnPlateau(**default_params))
if 'checkpoint' in learning_scheduler:
default_params = {'filepath': model_path, 'monitor': 'val_loss',
'save_best_only': True, 'save_weights_only': False,
'save_freq': 'epoch', 'verbose': 2}
default_params.update(learning_scheduler['checkpoint'])
callbacks.append(ModelCheckpoint(**default_params))
return callbacks
def get_optimizer(self, optimizer):
"""
Return an optimizer object
Args:
optimizer: The type of optimizer. Supports 'adam', 'sgd', 'rmsprop'
Returns:
An optimizer object
"""
assert optimizer.lower() in ['adam', 'sgd', 'rmsprop', 'adamw'], \
"{} optimizer is not implemented".format(optimizer)
if optimizer.lower() == 'adam':
return Adam
elif optimizer.lower() == 'sgd':
return SGD
elif optimizer.lower() == 'rmsprop':
return RMSprop
elif optimizer.lower() == 'adamw':
return tfa.optimizers.AdamW
def train(self, data_train,
data_val=None,
batch_size=32,
epochs=60,
lr=0.000005,
optimizer='adamw',
learning_scheduler=None,
model_opts=None):
"""
Trains the models
Args:
data_train: Training data
data_val: Validation data
batch_size: Batch size for training
epochs: Number of epochs to train
lr: Learning rate
optimizer: Optimizer for training
learning_scheduler: Whether to use learning schedulers
model_opts: Model options
Returns:
The path to the root folder of models
"""
learning_scheduler = learning_scheduler or {}
# Set the path for saving models
model_folder_name = time.strftime("%d%b%Y-%Hh%Mm%Ss")
path_params = {'save_folder': os.path.join(self.__class__.__name__, model_folder_name),
'save_root_folder': 'data/models/',
'dataset': model_opts['dataset']}
model_path, _ = get_path(**path_params, file_name='model.h5')
# Read train data
data_train = self.get_data('train', data_train, {**model_opts, 'batch_size': batch_size})
if data_val is not None:
data_val = self.get_data('val', data_val, {**model_opts, 'batch_size': batch_size})['data']
if self._generator:
data_val = data_val[0]
# Create model
train_model = self.get_model(data_train['data_params'])
# Train the model
class_w = self.class_weights(model_opts['apply_class_weights'], data_train['count'])
optimizer_params = {"learning_rate": lr}
if optimizer == "adamw":
optimizer_params["weight_decay"] = 1e-4
optimizer = self.get_optimizer(optimizer)(**optimizer_params)
train_model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])
callbacks = self.get_callbacks(learning_scheduler, model_path)
history = train_model.fit(x=data_train['data'][0],
y=None if self._generator else data_train['data'][1],
batch_size=batch_size,
epochs=epochs,
validation_data=data_val,
class_weight=class_w,
verbose=1,
callbacks=callbacks)
if 'checkpoint' not in learning_scheduler:
print('Train model is saved to {}'.format(model_path))
train_model.save(model_path)
# Save data options and configurations
model_opts_path, _ = get_path(**path_params, file_name='model_opts.pkl')
with open(model_opts_path, 'wb') as fid:
pickle.dump(model_opts, fid, pickle.HIGHEST_PROTOCOL)
config_path, _ = get_path(**path_params, file_name='configs.yaml')
self.log_configs(config_path, batch_size, epochs,
lr, model_opts)
# Save training history
history_path, saved_files_path = get_path(**path_params, file_name='history.pkl')
with open(history_path, 'wb') as fid:
pickle.dump(history.history, fid, pickle.HIGHEST_PROTOCOL)
return saved_files_path
# Test Functions
def test(self, data_test, model_path=''):
"""
Evaluates a given model
Args:
data_test: Test data
model_path: Path to folder containing the model and options
save_results: Save output of the model for visualization and analysis
Returns:
Evaluation metrics
"""
with open(os.path.join(model_path, 'configs.yaml'), 'r') as fid:
opts = yaml.safe_load(fid)
# try:
# model_opts = pickle.load(fid)
# except:
# model_opts = pickle.load(fid, encoding='bytes')
test_model = load_model(os.path.join(model_path, 'model.h5'), custom_objects={"Encoder": Encoder})
test_model.summary()
test_data = self.get_data('test', data_test, {**opts['model_opts'], 'batch_size': 1})
test_results = test_model.predict(test_data['data'][0],
batch_size=1, verbose=1)
acc = accuracy_score(test_data['data'][1], np.round(test_results))
f1 = f1_score(test_data['data'][1], np.round(test_results))
auc = roc_auc_score(test_data['data'][1], np.round(test_results))
roc = roc_curve(test_data['data'][1], test_results)
precision = precision_score(test_data['data'][1], np.round(test_results))
recall = recall_score(test_data['data'][1], np.round(test_results))
pre_recall = precision_recall_curve(test_data['data'][1], test_results)
# THIS IS TEMPORARY, REMOVE BEFORE RELEASE
with open(os.path.join(model_path, 'test_output.pkl'), 'wb') as picklefile:
pickle.dump({'tte': test_data['tte'],
'pid': test_data['ped_id'],
'gt':test_data['data'][1],
'y': test_results,
'image': test_data['image']}, picklefile)
print('acc:{:.2f} auc:{:.2f} f1:{:.2f} precision:{:.2f} recall:{:.2f}'.format(acc, auc, f1, precision, recall))
save_results_path = os.path.join(model_path, '{:.2f}'.format(acc) + '.yaml')
if not os.path.exists(save_results_path):
results = {'acc': acc,
'auc': auc,
'f1': f1,
'roc': roc,
'precision': precision,
'recall': recall,
'pre_recall_curve': pre_recall}
with open(save_results_path, 'w') as fid:
yaml.dump(results, fid)
return acc, auc, f1, precision, recall
def get_model(self, data_params):
"""
Generates a model
Args:
data_params: Data parameters to use for model generation
Returns:
A model
"""
raise NotImplementedError("get_model should be implemented")
# Auxiliary function
def _gru(self, name='gru', r_state=False, r_sequence=False):
"""
A helper function to create a single GRU unit
Args:
name: Name of the layer
r_state: Whether to return the states of the GRU
r_sequence: Whether to return a sequence
Return:
A GRU unitCA
"""
return GRU(units=self._num_hidden_units,
return_state=r_state,
return_sequences=r_sequence,
stateful=False,
name=name)
def _lstm(self, name='lstm', r_state=False, r_sequence=False):
"""
A helper function to create a single LSTM unit
Args:
name: Name of the layer
r_state: Whether to return the states of the LSTM
r_sequence: Whether to return a sequence
Return:
A LSTM unit
"""
return LSTM(units=self._num_hidden_units,
return_state=r_state,
return_sequences=r_sequence,
stateful=False,
kernel_regularizer=self._regularizer,
recurrent_regularizer=self._regularizer,
bias_regularizer=self._regularizer,
name=name)
def create_stack_rnn(self, size, r_state=False, r_sequence=False):
"""
Creates a stack of recurrent cells
Args:
size: The size of stack
r_state: Whether to return the states of the GRU
r_sequence: Whether the last stack layer to return a sequence
Returns:
A stacked recurrent model
"""
cells = []
for i in range(size):
cells.append(self._rnn_cell(units=self._num_hidden_units,
kernel_regularizer=self._regularizer,
recurrent_regularizer=self._regularizer,
bias_regularizer=self._regularizer, ))
return RNN(cells, return_sequences=r_sequence, return_state=r_state)
class SingleRNN(ActionPredict):
""" A simple recurrent network """
def __init__(self,
num_hidden_units=256,
cell_type='gru', **kwargs):
"""
Class init function
Args:
num_hidden_units: Number of recurrent hidden layers
cell_type: Type of RNN cell
"""
super().__init__(**kwargs)
# Network parameters
self._num_hidden_units = num_hidden_units
self._rnn_type = cell_type
def get_model(self, data_params):
network_inputs = []
data_sizes = data_params['data_sizes']
data_types = data_params['data_types']
core_size = len(data_sizes)
_rnn = self._gru if self._rnn_type == 'gru' else self._lstm
for i in range(core_size):
network_inputs.append(Input(shape=data_sizes[i],
name='input_' + data_types[i]))
if len(network_inputs) > 1:
inputs = Concatenate(axis=2)(network_inputs)
else:
inputs = network_inputs[0]
encoder_output = _rnn(name='encoder')(inputs)
encoder_output = Dense(1, activation='sigmoid',
name='output_dense')(encoder_output)
net_model = Model(inputs=network_inputs,
outputs=encoder_output)
return net_model
class StackedRNN(ActionPredict):
""" A stacked recurrent prediction model based on
Yue-Hei et al. "Beyond short snippets: Deep networks for video classification."
CVPR, 2015." """
def __init__(self,
num_hidden_units=256,
cell_type='gru', **kwargs):
"""
Class init function
Args:
num_hidden_units: Number of recurrent hidden layers
cell_type: Type of RNN cell
"""
super().__init__(**kwargs)
# Network parameters
self._num_hidden_units = num_hidden_units
self._rnn = self._gru if cell_type == 'gru' else self._lstm
self._rnn_cell = GRUCell if cell_type == 'gru' else LSTMCell
def get_model(self, data_params):
network_inputs = []
data_sizes = data_params['data_sizes']
data_types = data_params['data_types']
core_size = len(data_sizes)
for i in range(core_size):
network_inputs.append(Input(shape=data_sizes[i], name='input_' + data_types[i]))
if len(network_inputs) > 1:
inputs = Concatenate(axis=2)(network_inputs)
else:
inputs = network_inputs[0]
encoder_output = self.create_stack_rnn(core_size)(inputs)
encoder_output = Dense(1, activation='sigmoid',
name='output_dense')(encoder_output)