Download sfm_code/train_combination.py from FelixOtt/industry_datasets: direct link, hf CLI and curl.
- Browser
- Download file 10.7 kB
-
https://huggingface.co/datasets/FelixOtt/industry_datasets/resolve/main/sfm_code/train_combination.py
- Command line
-
hf download hf://datasets/FelixOtt/industry_datasets/sfm_code/train_combination.py
-
curl -L -o train_combination.py https://huggingface.co/datasets/FelixOtt/industry_datasets/resolve/main/sfm_code/train_combination.py
10.7 kB
| 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) | |