import numpy as np import re import os from glob import glob import pickle as pkl from itertools import chain, combinations, permutations import argparse def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) def to_softmax(inarr): ret_arr = inarr - np.max(inarr, axis=1)[:, None] return np.exp(ret_arr)/np.sum(np.exp(ret_arr), axis=1)[:, None] def to_norm(inarr): return inarr/np.sum(inarr, axis=1)[:, None] parser = argparse.ArgumentParser() parser.add_argument('--multi', help='If 1, use multiclass training else use binary', required=False, default=1) parser.add_argument('--addlayer', help='Layer(s) to add after resnet', required=False, default="None") parser.add_argument('--triplets', help='Whether to use triplet loss 0: No, 1: Yes, 2: Quadruplet loss', required=False, default="0") parser.add_argument('--repeats', help='Number of repeats per training', required=False, default="10") # Important: it is assumed, that repeated training of the same model have subsequent run numbers. # For repeats=10 for example: Trainings with hyperparameters 1 have the numbers 0,1,2,...,9; trainings with hyperparameters 2 have the numbers 10,11,12,...19 args = parser.parse_args() use_multi = int(args.multi) additional_layer = args.addlayer use_triplets = int(args.triplets) repeats = int(args.repeats) save_big_files = False # If True, the uncertainty calculation per sample will be saved, if false only the averaged uncertatinty will be saved. base_path_data = "../../Spectrum_Highway1/" base_path = "./" test_file = base_path_data + "GNSS_dataset/test.txt" # File containing the sample information for the test set if norm_type == 0: norm_data = None elif norm_type == 1: norm_data = [-135.99690198, 0.] # Overall min and max values of the train set time_size = 243 # Size of each sample. (Should be <= 243) with open(test_file, "r") as f: lab = f.readlines() lab = np.array([int(x.split("\n")[0].split("\t")[-1]) for x in lab]) # ----------- # # Create Folders train_output_folder = "results_episodic" if additional_layer != "None": train_output_folder += "_" + additional_layer if not use_multi: train_output_folder += "_binary" if use_triplets == 1: train_output_folder += "_triplet" elif use_triplets == 2: train_output_folder += "_quadruplet" data_base_folder = base_path + train_output_folder # Data folders ------------------------------------------------------------------- # sp_base = data_base_fodler + "/uncertainties/" if not os.path.exists(sp_base): os.makedirs(sp_base) # -------------------------------------------------------------------------------- # # Group all folders of the same hyperparameters together ----------------------- # re_c_folder = re.compile(data_base_folder + r'/(?P\d{1,6})_202.*_.*') folders = glob(data_base_folder + "/0*_202*") folders.sort(key=lambda x: int(re_c_folder.match(x).group(1))) folder_nums = [int(re_c_folder.match(x).group(1)) for x in folders] folders_new = [] folders_cur = [] prev_num = -1 for ffolder, fnum in zip(folders, folder_nums): if fnum//repeats != prev_num//repeats and prev_num != -1: folders_new.append(folders_cur) folders_cur = [] folders_cur.append(ffolder) prev_num = fnum folders_new.append(folders_cur) folders = folders_new group_size = 4 # In addition to the repeats each sample will be used 4 times for the uncertainty. (Normal/Flipped horizontal/Flipped vertical/Flipped both) # ------------------------------------------------------------------------------ # # Get old classes ------------------ # new_classes = np.array([3, 6, 8, 9]) old_classes = list(set(np.arange(11)) - set(new_classes)) # The old classes are always included in every training # ---------------------------------- # for cfi, cfolders in enumerate(folders): cfolder = cfolders[0] cfolder_num = int(cfolders[0].split("/")[-1].split("_")[0]) print("Dealing with count %d Number %d Folder: " % (cfi, cfolder_num), cfolder) sp_aleatoric_diag = sp_base + "%06d_aleatoric_diag.npy" % cfolder_num sp_epistemic_diag = sp_base + "%06d_epistemic_diag.npy" % cfolder_num sp_aleatoric = sp_base + "%06d_aleatoric.npy" % cfolder_num sp_epistemic = sp_base + "%06d_epistemic.npy" % cfolder_num sp_confusion = sp_base + "%06d_confusion.npy" % cfolder_num cur_folder = cfolder + "/test/" cur_pred_files = glob(cur_folder + "preds*.npy") # Sort files --------------------------------------- # cnums = [] for cpf in cur_pred_files: cpf_num = np.sum([(int(x) - 2) * 10**xi for xi, x in enumerate(cpf.split("/preds_0_1_2_")[-1].split(".npy")[0].split("_")[::-1])]) cnums.append(cpf_num) cur_pred_files = [x for x, _ in sorted(zip(cur_pred_files, cnums), key=lambda pair: pair[1])] # -------------------------------------------------- # aleatoric_diag_tests = [] epistemic_diag_tests = [] aleatoric_tests = [] epistemic_tests = [] confusion_tests = [] for cpi, cpredf in enumerate(cur_pred_files): cur_name_end = cpredf.split("/test/")[-1] print("Dealing with Preds %d " % cpi, cpredf) # get class mapping from current classes to 11 classes # m1 = [int(x) for x in cpredf.split("/preds_")[-1].split(".npy")[0].split("_")] total_cur_classes = np.unique(old_classes + m1) cur_classes_map = {x: np.where(total_cur_classes == x)[0][0] if x in total_cur_classes else -1 for x in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]} print(cur_classes_map) # ---------------------------------------------------- # cpred = np.load(cpredf) cpred = to_softmax(cpred) old_shape = cpred.shape cpred = cpred.reshape((-1, group_size, old_shape[1])).transpose((1, 0, 2)) # For Multiclass: Shape (T, N, C) T=group size, N=samples, C=classes # Include preds from other rseeds if they exist --------------------------------------------------------------------------------------------------------------------- # if len(cfolders) != 1: folder_counter = 0 for cfd in cfolders[1:]: folder_counter += 1 cpredf_c = cfd + "/test/" + cur_name_end try: cpred_c = np.load(cpredf_c) cpred_c = to_softmax(cpred_c) old_shape_c = cpred_c.shape cpred_c = cpred_c.reshape((-1, group_size, old_shape_c[1])).transpose((1, 0, 2)) # For Multiclass: Shape (T, N, C) T=group size, N=samples, C=classes cpred = np.concatenate([cpred, cpred_c], axis=0) except FileNotFoundError: print("Not tested yet: ", cpredf_c) cpred[np.isnan(cpred)] = 0.0 # ------------------------------------------------------------------------------------------------------------------------------------------------------------------- # # Extend Classes to 11 cur_test_preds = np.zeros((cpred.shape[0], cpred.shape[1], 11)) for ci, cl in enumerate([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]): if cur_classes_map[cl] != -1: cur_test_preds[:, :, ci] = cpred[:, :, cur_classes_map[cl]] cpred_arg = np.argmax(np.sum(cur_test_preds, axis=0), axis=-1) conf_mat = np.zeros((11, 11)) for iim, im in enumerate([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]): for jjm, jm in enumerate([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]): conf_mat[iim, jjm] = np.sum(cpred_arg[lab==im] == jjm) # Equation 4 from: https://openreview.net/pdf?id=Sk_P2Q9sG # For Multiclass: Shape (T, N, C) p_mean = np.mean(cur_test_preds, axis=0) p_hat_minus_p_mean = cur_test_preds - p_mean[None, :] # shape (T, N, C) epistemic = np.mean(np.matmul(p_hat_minus_p_mean[:, :, :, None], p_hat_minus_p_mean[:, :, None, :]), axis=0) # shape (N, C, C) diag_p = np.zeros((cur_test_preds.shape[0], cur_test_preds.shape[1], cur_test_preds.shape[2], cur_test_preds.shape[2])) diag_p[:, :, np.arange(cur_test_preds.shape[2]).astype(int), np.arange(cur_test_preds.shape[2]).astype(int)] = cur_test_preds aleatoric = np.mean(diag_p - np.matmul(cur_test_preds[:, :, :, None], cur_test_preds[:, :, None, :]), axis=0) # shape (N, C, C) # ep_diag = [] al_diag = [] for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: ep_diag_c = np.diag(np.mean(epistemic[lab == i], axis=0)) al_diag_c = np.diag(np.mean(aleatoric[lab == i], axis=0)) ep_diag.append(ep_diag_c) al_diag.append(al_diag_c) aleatoric_diag_tests.append(al_diag) epistemic_diag_tests.append(ep_diag) aleatoric_tests.append(aleatoric) epistemic_tests.append(epistemic) confusion_tests.append(conf_mat) np.save(sp_aleatoric_diag, np.array(aleatoric_diag_tests)) np.save(sp_epistemic_diag, np.array(epistemic_diag_tests)) if save_big_files: np.save(sp_aleatoric, np.array(aleatoric_tests)) np.save(sp_epistemic, np.array(epistemic_tests)) np.save(sp_confusion, np.array(confusion_tests)) print("Done")