Download sfm_code/train_posnet.py from FelixOtt/industry_datasets: direct link, hf CLI and curl.
- Browser
- Download file 5.07 kB
-
https://huggingface.co/datasets/FelixOtt/industry_datasets/resolve/main/sfm_code/train_posnet.py
- Command line
-
hf download hf://datasets/FelixOtt/industry_datasets/sfm_code/train_posnet.py
-
curl -L -o train_posnet.py https://huggingface.co/datasets/FelixOtt/industry_datasets/resolve/main/sfm_code/train_posnet.py
5.07 kB
| import time | |
| import keras | |
| import argparse | |
| from keras import backend as K | |
| from tqdm import tqdm | |
| import numpy as np | |
| import tensorflow as tf | |
| from keras.backend.tensorflow_backend import set_session | |
| import os | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('--model', help='name of the model to load', required=True) | |
| parser.add_argument('--train', help='name of the train set to load', required=True) | |
| parser.add_argument('--test', help='name of the test 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('--loss', help='loss', required=True) | |
| args = parser.parse_args() | |
| modelname = args.model | |
| DATASET = args.train | |
| DATASET_TEST = args.test | |
| TIMESTAMP = int(args.timestamps) | |
| BETA = int(args.beta) | |
| ITERATIONS = int(args.iterations) | |
| batchSize = int(args.batchsize) | |
| loss_name = args.loss | |
| config = tf.ConfigProto() | |
| config.gpu_options.allow_growth = True | |
| sess = tf.Session(config=config) | |
| set_session(sess) | |
| # Load and create the model with no pretrained values | |
| startweight = None | |
| import cnn_mTD_2048 as cnn | |
| model = cnn.create_cnn_lstm(startweight) | |
| import utilities_pos as utilities | |
| # Obtain the current date and create a folder to save the results in | |
| traindataset = DATASET | |
| testdataset = DATASET_TEST | |
| currentDate = time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime()) | |
| os.mkdir("../results/" + str(currentDate)) | |
| os.mkdir("../results/" + str(currentDate) + "/weights/") | |
| parameters = open("../results/" + str(currentDate) + "/parameters.txt", "w") | |
| parameters.write("Modelname: " + str(modelname) + "\n" + | |
| "Dataset: " + str(DATASET) + "\n" + | |
| "Dataset test: " + str(DATASET_TEST) + "\n" + | |
| "Timestamp: " + str(TIMESTAMP) + "\n" + | |
| "Beta: " + str(BETA) + "\n" + | |
| "Iterations: " + str(ITERATIONS) + "\n" + | |
| "Batch size: " + str(batchSize) + "\n" + | |
| "Loss: " + str(loss_name)) | |
| parameters.close() | |
| outputWeightspath = "../results/" + str(currentDate) + "/weights/" + DATASET.split("/")[-1].split(".txt")[0] + '_b_' + str(BETA) + '_BS_' + str(batchSize) + '_' | |
| log = open("../results/" + str(currentDate) + "/log_" + DATASET.split("/")[-1].split(".txt")[0] + '_b_' + str(BETA) + '_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 | |
| # different loss functions to use | |
| def rmse_p(y_true, y_pred): | |
| return K.sqrt(K.sum(K.square(y_pred-y_true), axis=-1)) | |
| def rmse_q(y_true, y_pred): | |
| return BETA * K.sqrt(K.sum(K.square(y_true-y_pred), axis=-1)) | |
| def mse_p(y_true, y_pred): | |
| return K.mean(K.square(y_pred-y_true), axis=-1) | |
| def mse_q(y_true, y_pred): | |
| return BETA * K.mean(K.square(y_pred-y_true), axis=-1) | |
| # compile the model with the chosen loss function | |
| sgd = keras.optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0) | |
| run_opts = tf.RunOptions(report_tensor_allocations_upon_oom = True) | |
| if loss_name == "rmse": | |
| model.compile(optimizer=sgd, loss=[rmse_p, rmse_q], options=run_opts) | |
| elif loss_name == "mse": | |
| model.compile(optimizer=sgd, loss=[mse_p, mse_q], options=run_opts) | |
| # load the training and test data and create the training generator | |
| datasource, _ = utilities.get_training_data(traindataset) | |
| testdatasource, _ = utilities.get_training_data(testdataset) | |
| data_gen = utilities.gen_data_batch(datasource, batchSize) | |
| # train for ITERATIONS | |
| for i in range(ITERATIONS): | |
| print(i) | |
| X_batch, Y_batch = next(data_gen) | |
| history = model.fit(X_batch, Y_batch, nb_epoch=1, batch_size=batchSize) | |
| if i % int(TIMESTAMP) == 0: # every TIMESTAMP iterations evaluate on the test data | |
| datagen = utilities.limited_gen_data(testdatasource) | |
| posxs = [] | |
| posqs = [] | |
| for ims,xs,qs in tqdm(datagen): | |
| inputs = np.zeros([1, 3, 224, 224, 3]) | |
| inputs[0,:] = ims | |
| out = model.predict(inputs) | |
| posx = out[0][0][1] | |
| posq = out[1][0][1] | |
| actualx = xs[1] | |
| actualq = qs[1] | |
| errx, theta = getError(posx, posq, actualx, actualq) | |
| posxs.append(errx) | |
| posqs.append(theta) | |
| # print and save the result and the model weights | |
| print('Median error ' + str(np.median(posxs)) + ' m and ' + str(np.median(posqs)) + ' degrees') | |
| print("Iteration: " + str(i) + "\n\t" + "Loss is: " + str(history.history['loss'][0])) | |
| log.write("Iteration: " + str(i) + "\n\t" + "Loss is: " + str(history.history['loss'][0]) + "\n") | |
| log.write("Median error %f m and %f degrees \n" % (np.median(posxs), np.median(posqs))) | |
| log.flush() | |
| model.save_weights(outputWeightspath + str(i) + '.h5') | |