File size: 10,689 Bytes
1403119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
import argparse
import os
import time
import torch
import torch.backends.cudnn as cudnn
import torch.nn.init as init
import torch.optim as optim
import torch.utils.data
from glob import glob
torch.autograd.set_detect_anomaly(True)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(device)
parser = argparse.ArgumentParser()
parser.add_argument('--train', help='number of the train set to load', required=True)
parser.add_argument('--timestamps', help='evaluate test data every x iterations', required=True)
parser.add_argument('--beta', help='multiplication fact for rotation loss', required=True)
parser.add_argument('--iterations', help='iterations to train for', required=True)
parser.add_argument('--batchsize', help='batchsize', required=True)
parser.add_argument('--size', help='sequence length', required=True)
parser.add_argument('--rnn_size', help='network hidden size', required=False, default=10)
parser.add_argument('--rot', help='0: keep rel as is, 1: rotate rel with abs', required=False, default=0)
parser.add_argument('--m', help='1: APR + PRP, 2: APR[s] + PRP[s], 3: SfM + PRP, 4: APR + PRP[s], 5: APR[s] + PRP, 6: SfM + PRP[s]', required=False, default=1)
parser.add_argument('--net', help='Network to use', required=False, default="lstm")
parser.add_argument('--stack', help='Number of layers', required=False, default="2")
parser.add_argument('--run_num', help='Id of the run', required=False, default="0")

args = parser.parse_args()
train_num = int(args.train)
TIMESTAMP = int(args.timestamps)
BETA = float(args.beta)
ITERATIONS = int(args.iterations)
batchSize = int(args.batchsize)
time_size = int(args.size)
rnn_size = int(args.rnn_size)
backrot = int(args.rot)
mode = int(args.m)
net_name = args.net
stacks = int(args.stack)
run_num = int(args.run_num)
all_folders = glob("...")  # Collects all previous trainings (the folder names start with the training number)
all_folders = np.array([int(x.split("/")[-1].split("_")[0]) for x in all_folders])
if run_num in all_folders:
	# if the number already exists, then skipp it
	print("Skipped: ", run_num, train_num, TIMESTAMP, BETA, ITERATIONS, batchSize, time_size,
							rnn_size, backrot, mode, net_name, stacks)
	exit()
print("Running: ", run_num, train_num, TIMESTAMP, BETA, ITERATIONS, batchSize, time_size, rnn_size,
						backrot, mode, net_name, stacks)

# Choose and create the network specified in the arguments
if net_name == "lstm":
	from lstm import *
	model = LSTM_stack(14, rnn_size, device, stacks)
	model.train()
	model = model.to(device)
elif net_name == "cfn":
	from cfn import *
	model = CFN_stack(14, rnn_size, device, stacks)
	model.train()
	model.to(device)
elif net_name == "gru":
	from gru import *
	model = GRU_stack(14, rnn_size, device, stacks)
	model.train()
	model.to(device)
elif net_name == "mgu":
	from mgu import *
	model = MGU_stack(14, rnn_size, device, stacks)
	model.train()
	model.to(device)
elif net_name == "qrnn":
	from qrnn import *
	model = fakeQRNN_stack(14, rnn_size, device, stacks)
	model.train()
	model.to(device)
elif net_name == "ran":
	from ran import *
	model = RAN_stack(14, rnn_size, device, stacks)
	model.train()
	model.to(device)
elif net_name == "sru":
	from sru import *
	model = SRU_stack(14, rnn_size, device, stacks)
	model.train()
	model.to(device)
elif net_name == "trnn":
	from trnn import *
	model = TRNN_stack(14, rnn_size, device, stacks)
	model.train()
	model.to(device)
import utilities_comb as utilities

# The following deals with paths and folders for the data. It has to be adjusted to your setup.  -------------------- #
# In the end 4 file paths are defined: train_dataset_abs/train_dataset_rel, test_dataset_abs/test_dataset_rel
# Folders with the train/test data for the different methods
# Each is a dictionary with an entry for every train number
abs_datasets_sfm = {1: ..., 2: ...}
abs_datasets = {1: ..., 2: ...}
rel_datasets = {1: ..., 2: ...}
abs_synt_post_datasets = {1: ..., 2: ...}
rel_synt_post_datasets = {1: ..., 2: ...}
# Depending on the mode, the absolute and relative data is combined from different methods
if mode == 1:
	train_base_abs = abs_datasets[train_num]
	train_base_rel = rel_datasets[train_num]
	train_dataset_abs = train_base_abs + "..."
	train_dataset_rel = train_base_rel + "..."
	test_dataset_abs = train_base_abs + "..."
	test_dataset_rel = train_base_rel + "..."
elif mode == 2:
	train_base_abs = abs_synt_post_datasets[train_num]
	train_base_rel = rel_synt_post_datasets[train_num]
	train_dataset_abs = train_base_abs + "..."
	train_dataset_rel = train_base_rel + "..."
	test_dataset_abs = train_base_abs + "..."
	test_dataset_rel = train_base_rel + "..."
elif mode == 3:
	train_base_abs = abs_datasets_sfm[train_num]
	train_base_rel = rel_datasets[train_num]
	train_dataset_abs = train_base_abs + "..."
	train_dataset_rel = train_base_rel + "..."
	test_dataset_abs = train_base_abs + "..."
	test_dataset_rel = train_base_rel + "..."
elif mode == 4:
	train_base_abs = abs_datasets[train_num]
	train_base_rel = rel_synt_post_datasets[train_num]
	train_dataset_abs = train_base_abs + "..."
	train_dataset_rel = train_base_rel + "..."
	test_dataset_abs = train_base_abs + "..."
	test_dataset_rel = train_base_rel + "..."
elif mode == 5:
	train_base_abs = abs_synt_post_datasets[train_num]
	train_base_rel = rel_datasets[train_num]
	train_dataset_abs = train_base_abs + "..."
	train_dataset_rel = train_base_rel + "..."
	test_dataset_abs = train_base_abs + "..."
	test_dataset_rel = train_base_rel + "..."
elif mode == 6:
	train_base_abs = abs_datasets_sfm[train_num]
	train_base_rel = rel_synt_post_datasets[train_num]
	train_dataset_abs = train_base_abs + "..."
	train_dataset_rel = train_base_rel + "..."
	test_dataset_abs = train_base_abs + "..."
	test_dataset_rel = train_base_rel + "..."
# ------------------------------------------------------------------------------------------------------------------- #

# Creates the folders in which the results are saved
currentDate = time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime())
os.mkdir("../results/" + "%05d_" % (run_num) + str(currentDate))
os.mkdir("../results/" + "%05d_" % (run_num) + str(currentDate) + "/weights/")
# writes the current parameters in a file
parameters = open("../results/" + "%05d_" % (run_num) + str(currentDate) + "/parameters.txt", "w")
parameters.write("Modelname:    flownet" + "\n" +
                 "Dataset:      " + str(train_num) + "\n" +
                 "Timestamp:    " + str(TIMESTAMP) + "\n" +
                 "Iterations:   " + str(ITERATIONS) + "\n" +
                 "Batch size:   " + str(batchSize) + "\n" +
                 "Time_size:    " + str(time_size) + "\n" +
                 "Rnn_size:     " + str(rnn_size) + "\n" +
                 "Back_rotate:  " + str(backrot) + "\n" +
                 "Mode:         " + str(mode) + "\n" +
                 "Net name:     " + str(net_name) + "\n" +
                 "Stacks:       " + str(stacks) + "\n")
parameters.close()
outputWeightspath = "../results/" + "%05d_" % (run_num) + str(currentDate) + "/weights/" + str(train_num) + '_BS_' + str(batchSize) + '_'
log = open("../results/" + "%05d_" % (run_num) + str(currentDate) + "/log_" + str(train_num) + '_BS_' + str(batchSize) + '.txt', "w")


def getError(posx, posq, actualx, actualq):
	""" Calculates the position and rotation error """
	q1 = actualq / np.linalg.norm(actualq)
	q2 = posq / np.linalg.norm(posq)
	d = abs(np.sum(np.multiply(q1, q2)))
	theta = 2 * np.arccos(d) * 180 / np.pi
	errx = np.linalg.norm(actualx - posx)
	return errx, theta


def rmse_p(y_true, y_pred):
	return torch.sqrt(torch.sum(torch.square(y_pred-y_true), axis=-1))


def rmse_q(y_true, y_pred):
	return BETA * torch.sqrt(torch.sum(torch.square(y_true-y_pred), axis=-1))


class rmse_wrap(torch.nn.Module):
	""" Wrapper for dealing with the position loss and rotation loss. The rotation loss is multiplied with BETA. """
	def __init__(self):
		super(rmse_wrap, self).__init__()
	def __call__(self, output, target):
		loss1 = rmse_p(output[:, :3], target[:, :3])
		loss2 = rmse_q(output[:, 3:], target[:, 3:])
		return loss1 + loss2


# For keeping track of the total run time
s_time = time.time()
# Loads the training/test data
pred_abs, pred_rel, gt_abs, gt_rel = utilities.get_training_data(train_dataset_abs, train_dataset_rel, backrot)
pred_abs_test, pred_rel_test, gt_abs_test, gt_rel_test = utilities.get_training_data(test_dataset_abs, test_dataset_rel, backrot)
# Generator for creating batches of size batchSize
data_gen = utilities.gen_data_batch(pred_abs, pred_rel, gt_abs, gt_rel, batchSize, time_size)
optimizer = optim.Adam(model.parameters())
criterion = rmse_wrap().to(device)
# train for ITERATIONS
for i in range(ITERATIONS):
	print(i)
	# Load the next batch and put in on the device
	X_batch, Y_batch = next(data_gen)
	X_batch = X_batch.transpose((1, 0, 2))
	X_batch = torch.tensor(X_batch)        
	Y_batch = torch.from_numpy(Y_batch)
	inputs = X_batch.to(device)
	labels = Y_batch.to(device)
	# predict on the current input data
	preds = model(inputs).float()
	# Loss function
	cost = criterion(preds, labels).mean()
	optimizer.zero_grad()
	cost.backward(retain_graph=True)
	optimizer.step()
	model.zero_grad()
	model.detach_hidden()
	print(cost)
	if (i+1) % int(TIMESTAMP) == 0:  # every TIMESTAMP steps: evaluate the network on the test data
		model.eval()
		hidden1_copy = model.cell1.hidden
		model.cell1.hidden = None
		if stacks == 2:
			hidden2_copy = model.cell2.hidden
			model.cell2.hidden = None
		# create a generator for the test data (Batchsize = 1)
		datagen = utilities.limited_gen_data(pred_abs_test, pred_rel_test, gt_abs_test, gt_rel_test, time_size)
		posxs = []
		posqs = []
		for ims, xs, qs in datagen:  # Iterate over the test data and evaluate it
			inputs = np.zeros((1, time_size, 14)).astype("float32")
			inputs[0, :] = ims
			inputs = inputs.transpose((1, 0, 2))
			inputs = torch.tensor(inputs).to(device)
			out = model(inputs).float()
			posx = out[0][:3].detach().cpu().numpy()
			posq = out[0][3:].detach().cpu().numpy()
			actualx = xs
			actualq = qs
			errx, theta = getError(posx, posq, actualx, actualq)
			posxs.append(errx)
			posqs.append(theta)
		# Write the results into a file
		print('Median error ' + str(np.median(posxs)) + ' m and ' + str(np.nanmedian(posqs)) + ' degrees')
		log.write("Median error %f m and %f degrees \n" % (np.median(posxs), np.nanmedian(posqs)))
		log.flush()
		torch.save(model.state_dict(), outputWeightspath + str(i) + '.h5')
		model.cell1.hidden = hidden1_copy
		if stacks == 2:
			model.cell2.hidden = hidden2_copy
		model.train()
print("Total time: ", time.time() - s_time)