-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsted_train.py
234 lines (204 loc) · 9.94 KB
/
sted_train.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
import models
import datasets
import utils
import trainer
import torch.optim as optim
import numpy as np
import torch
import pandas as pd
import argparse
import copy
import csv
parser = argparse.ArgumentParser()
parser.add_argument('-model_save_path',
help='Path to save the encoder and decoder models',
default='./STED_model_save/')
parser.add_argument(
'-data_path', help='Path to bounding box statistics and precomputed DTP features',
default='./sted_feature/')
args = parser.parse_args()
batch_size = 1024
learning_rate = 1e-3
weight_decay = 0
num_workers = 8
num_epochs = 20
layers_enc = 1
layers_dec = 1
dropout_p = 0
num_hidden = 512
normalize = True
device = torch.device("cuda")
model_save_path = args.model_save_path
data_path = args.data_path
for detector in ['yolo']:
for fold in [1, 2, 3]:
print(detector + ' fold ' + str(fold))
# def encoder and decoder
encoder = models.EncoderRNN(device, num_hidden, layers_enc)
encoder = encoder.to(device)
encoder = encoder.float()
decoder = models.DecoderRNN(device, num_hidden, dropout_p, layers_dec)
decoder = decoder.to(device)
decoder = decoder.float()
path = data_path + detector + '_features/fold' + str(fold) + '/'
print('Loading data')
try:
train_boxes = np.load(
path + 'fold_' + str(fold) + '_train_dtp_box_statistics.npy')
val_boxes = np.load(path + 'fold_' + str(fold) +
'_val_dtp_box_statistics.npy')
test_boxes = np.load(path + 'fold_' + str(fold) +
'_test_dtp_box_statistics.npy')
train_labels = np.load(
path + 'fold_' + str(fold) + '_train_dtp_targets.npy')
val_labels = np.load(
path + 'fold_' + str(fold) + '_val_dtp_targets.npy')
test_labels = np.load(
path + 'fold_' + str(fold) + '_test_dtp_targets.npy')
train_dtp_features = np.load(
path + 'fold_' + str(fold) + '_train_dtp_features.npy')
val_dtp_features = np.load(
path + 'fold_' + str(fold) + '_val_dtp_features.npy')
test_dtp_features = np.load(
path + 'fold_' + str(fold) + '_test_dtp_features.npy')
except Exception:
print('Failed to load data from ' + str(data_path))
exit()
# Normalize boxes
for i in range(8):
val_boxes[:, i, ] = (val_boxes[:, i, ] - train_boxes[:, i, ].mean()) / \
train_boxes[:, i, ].std()
test_boxes[:, i, ] = (test_boxes[:, i, ] - train_boxes[:, i, ].mean()) / \
train_boxes[:, i, ].std()
train_boxes[:, i, ] = (train_boxes[:, i, ] - train_boxes[:,
i, ].mean()) / train_boxes[:, i, ].std()
loss_function = torch.nn.SmoothL1Loss()
train_set = datasets.Simple_BB_Dataset(
train_boxes, train_labels, train_dtp_features)
train_loader = torch.utils.data.DataLoader(train_set, batch_size=batch_size,
shuffle=True, num_workers=num_workers)
val_set = datasets.Simple_BB_Dataset(
val_boxes, val_labels, val_dtp_features)
val_loader = torch.utils.data.DataLoader(val_set, batch_size=batch_size,
shuffle=False, num_workers=num_workers)
test_set = datasets.Simple_BB_Dataset(
test_boxes, test_labels, test_dtp_features)
test_loader = torch.utils.data.DataLoader(test_set, batch_size=batch_size,
shuffle=False, num_workers=num_workers)
optimizer_encoder = optim.Adam(
encoder.parameters(), lr=learning_rate, weight_decay=weight_decay)
optimizer_decoder = optim.Adam(
decoder.parameters(), lr=learning_rate, weight_decay=weight_decay)
best_ade = np.inf
for epoch in range(num_epochs):
print('----------- EPOCH ' + str(epoch) + ' -----------')
print('Training...')
trainer.train_seqseq(encoder, decoder, device, train_loader, optimizer_encoder, optimizer_decoder,
epoch, loss_function, learning_rate)
print('Validating...')
val_predictions, val_targets, val_ade, val_fde = trainer.test_seqseq(
encoder, decoder, device, val_loader, loss_function, return_predictions=True)
if epoch == 4:
optimizer_encoder = optim.Adam(
encoder.parameters(), lr=1e-4, weight_decay=weight_decay)
optimizer_decoder = optim.Adam(
decoder.parameters(), lr=1e-4, weight_decay=weight_decay)
if epoch == 9:
optimizer_encoder = optim.Adam(
encoder.parameters(), lr=5e-5, weight_decay=weight_decay)
optimizer_decoder = optim.Adam(
decoder.parameters(), lr=5e-5, weight_decay=weight_decay)
if epoch == 14:
optimizer_encoder = optim.Adam(
encoder.parameters(), lr=2.5e-5, weight_decay=weight_decay)
optimizer_decoder = optim.Adam(
decoder.parameters(), lr=2.5e-5, weight_decay=weight_decay)
if val_ade < best_ade:
best_encoder, best_decoder = copy.deepcopy(
encoder), copy.deepcopy(decoder)
best_ade = val_ade
best_fde = val_fde
print('Best validation ADE: ', np.round(best_ade, 1))
print('Best validation FDE: ', np.round(best_fde, 1))
print('Saving model weights to ', model_save_path)
torch.save(encoder.state_dict(), model_save_path +
'/encoder_' + detector + str(fold) + '_gru.weights')
torch.save(decoder.state_dict(), model_save_path +
'/decoder_' + detector + str(fold) + '_gru.weights')
print('Testing...')
encoder.eval()
decoder.eval()
predictions, targets, ade, fde = trainer.test_seqseq(
encoder, decoder, device, test_loader, loss_function, return_predictions=True, phase='Test')
print('Getting IOU metrics')
# Predictions are reletive to constant velocity. To compute AIOU / FIOU, we need the constant velocity predictions.
test_cv_preds = pd.read_csv(
'./outputs/constant_velocity/test_' + detector + '_fold_' + str(fold) + '.csv')
results_df = pd.DataFrame()
results_df['vid'] = test_cv_preds['vid'].copy()
results_df['filename'] = test_cv_preds['filename'].copy()
results_df['frame_num'] = test_cv_preds['frame_num'].copy()
# First 3 columns are file info. Remaining columns are bounding boxes.
test_cv_preds = test_cv_preds.iloc[:, 3:].values.reshape(
len(test_cv_preds), -1, 4)
predictions = predictions.reshape(-1, 240, order='A')
predictions = predictions.reshape(-1, 4, 60)
predictions = utils.xywh_to_x1y1x2y2(predictions)
predictions = np.swapaxes(predictions, 1, 2)
predictions = np.around(predictions).astype(int)
predictions = test_cv_preds - predictions
gt_df = pd.read_csv('./outputs/ground_truth/test_' +
detector + '_fold_' + str(fold) + '.csv')
gt_boxes = gt_df.iloc[:, 3:].values.reshape(len(gt_df), -1, 4)
aiou = utils.calc_aiou(gt_boxes, predictions)
fiou = utils.calc_fiou(gt_boxes, predictions)
print('AIOU: ', round(aiou * 100, 1))
print('FIOU: ', round(fiou * 100, 1))
'''
print('Saving prediction to csv!')
for i in range(1, 61):
results_df["x1_" + str(i)] = 0
results_df["y1_" + str(i)] = 0
results_df["x2_" + str(i)] = 0
results_df["y2_" + str(i)] = 0
for i in range(predictions.shape[0]):
for j in range(predictions.shape[1]):
results_df['x1_' + str(j + 1)][i] = predictions[i][j][0]
results_df['y1_' + str(j + 1)][i] = predictions[i][j][1]
results_df['x2_' + str(j + 1)][i] = predictions[i][j][2]
results_df['y2_' + str(j + 1)][i] = predictions[i][j][3]
if i % 100 == 0:
print('Processing: ', i)
results_df.to_csv('./outputs/sted/test_' + detector + '_fold_' + str(fold) + '.csv', index = False)
print(predictions[0][0][0],' ',predictions[0][0][1],' ',predictions[0][0][2],' ', predictions[0][0][3])
print(results_df[0]['x1_1'],' ',results_df[0]['y1_1'],' ',results_df[0]['x2_1'],' ',results_df[0]['y2_1'])
'''
print('Saving prediction to csv!')
test_cv_preds = pd.read_csv(
'./outputs/constant_velocity/test_' + detector + '_fold_' + str(fold) + '.csv')
fp = open(
'./outputs/sted/test_' + detector + '_fold_' +
str(fold) + '.csv', 'w')
csv_writer = csv.writer(fp)
header = ["vid", "filename", "frame_num"]
for i in range(1, 61):
header.append("x1_" + str(i))
header.append("y1_" + str(i))
header.append("x2_" + str(i))
header.append("y2_" + str(i))
csv_writer.writerow(header)
print("len of predictions: ", predictions.shape[0])
for i in range(predictions.shape[0]):
tmp = []
tmp.append(test_cv_preds['vid'][i])
tmp.append(test_cv_preds['filename'][i])
tmp.append(test_cv_preds['frame_num'][i])
for j in range(predictions.shape[1]):
tmp.append(predictions[i][j][0])
tmp.append(predictions[i][j][1])
tmp.append(predictions[i][j][2])
tmp.append(predictions[i][j][3])
if i % 100 == 0:
print('Processing: ', i)
csv_writer.writerow(tmp)
fp.close()