from pathlib import Path import random from statistics import mean import numpy as np import torch from torch import nn from tqdm import tqdm from torch.utils.data import DataLoader import argparse import os import time import torch.optim as optim from glob import glob import re import utilities import matplotlib.pyplot as plt from itertools import chain, combinations, permutations import argparse def to_softmax(inarr): return np.exp(inarr)/np.sum(np.exp(inarr), axis=1)[:, None] 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)) 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('--run_num', help='Number for Identifying created folders', required=True) parser.add_argument('--addlayer', help='layer(s) to add after resnet', required=False, default="dense") parser.add_argument('--multi', help='If 0: Test on multiclass training. If 1: Test on binary training', required=False, default=0) args = parser.parse_args() training_num = int(args.run_num) additional_layer = args.addlayer use_multiclass_training = int(args.multi) # Hyper Params base_path_data = "../../Spectrum_Highway1/" base_path = "./" test_file = base_path_data + "GNSS_dataset/test_adap.txt" norm_data = [-135.99690198, 0.] batchSize = 40 time_size = 243 # ----------- # # Data folders # The test results will be saved in the already existing path base_path + "results_episodic + x" + "test" train_output_folder = base_path + "results_episodic" if additional_layer != "None": train_output_folder += "_" + additional_layer if not use_multiclass_training: train_output_folder += "_binary" folder = glob(train_output_folder + "/%06d_202*" % training_num)[0] fewshot_method = folder.split("_")[-3] new_classes = [3, 6, 8, 9] old_classes = list(set(np.arange(11)) - set(new_classes)) print("New classes: ", new_classes) class_permutations = list(permutations(new_classes)) # Test on all class permutations class_permutations = np.concatenate([np.zeros((len(class_permutations), 1)) - 1, class_permutations], axis=1).astype(int) # ---------- # # Support Data --------------- # with open(base_path_data + "GNSS_dataset/support_set.txt", "r") as f: support_info = f.readlines() # support_list = {int(si.split("\n")[0].split("\t")[-1]): [base_path_data + ("GNSS_dataset/data/%02d/" % (int(si.split(".npy")[0].split("/")[1]) // 15000)) + si.split("\t")[0].split("/")[1]] for si in support_info} support_list = {int(si.split("\n")[0].split("\t")[-1]): [base_path_data + "GNSS_dataset/data/" + si.split("\t")[0].split("/")[1]] for si in support_info} # ---------------------------- # wm = re.compile(r'.*/weights/(?P\d{1,6}).h5') wm_fs = re.compile(r'.*/weights/(?P\d{1,6})_fs.h5') if fewshot_method == "prototypical" or fewshot_method == "simpleshot": weights = glob(folder + "/weights/*") weights.sort(key=lambda x: int(wm.match(x).group(1))) elif fewshot_method == "relation" or fewshot_method == "bdcspn" or fewshot_method == "FEAT" or fewshot_method == "laplacianshot" or fewshot_method == "matchingnetworks": weights = glob(folder + "/weights/*_fs.h5") weights.sort(key=lambda x: int(wm_fs.match(x).group(1))) else: print("Invalid fewshot method: ", fewshot_method) exit() if len(weights) == 0: print("Skipped %d: Training not finished." % training_num) exit() if not os.path.exists(folder + "/post/test/"): os.makedirs(folder + "/post/test/") else: print("Skipped %d: Already Tested." % training_num) exit() # For getting best weights --- # log_train_file = glob(folder + "/log.txt")[0] with open(log_train_file, "r") as f: log_train_info = f.readlines() log_accs = np.array([float(x.split("\n")[0].split(" ")[-1]) for x in log_train_info]) weights_ind_best = np.argmax(log_accs) # ---------------------------- # startweight = weights[weights_ind_best] print(startweight) # Create Test data lists -------------- # with open(test_file, "r") as f: test_info = f.readlines() test_info = np.array([x.split("\n")[0].split("\t") for x in test_info]) test_list_raw = test_info[:, 0] test_classes = test_info[:, 1].astype(int) test_list = [] for tlr in test_list_raw: # add_folder = ("data/%02d" % (int(tlr.split("/")[-1].split(".npy")[0]) // 15000)) + "/" + tlr.split("/")[-1] add_folder = ("data/" + tlr.split("/")[-1] test_list.append(base_path_data + "GNSS_dataset/" + add_folder) # ------------------------------------- # # Create Model and load weights --------------------------------------------------------------- # class extract_tensor(nn.Module): # For extracting the tensor from an lstm output def forward(self,x): # Output shape (batch, features, hidden) tensor, _ = x return tensor class TransposeB(torch.nn.Module): def forward(self, x): x = torch.transpose(x, 1, 0) return x class TransposeT(torch.nn.Module): def forward(self, x): x = torch.transpose(x, 2, 1) return x class multihead_Attention(nn.Module): def __init__(self, embeded_dim, num_heads): super().__init__() self.attention = nn.MultiheadAttention(embeded_dim, num_heads, batch_first=True) def forward(self,x): x, _ = self.attention(x, x, x) return x # Create Model from torchvision.models import resnet18 model = resnet18() if additional_layer == "dense": model.fc = nn.Linear(512, 512) elif additional_layer == "lstm": model.avgpool = nn.AdaptiveAvgPool2d((8, 1)) model.use_flatten = False model.fc = nn.Sequential(nn.Flatten(start_dim=-2), nn.LSTM(8, 8, batch_first=True), extract_tensor(), nn.AdaptiveAvgPool1d(1), nn.Flatten()) elif additional_layer == "multiheadattention": model.avgpool = nn.AdaptiveAvgPool2d((8, 1)) model.use_flatten = False model.fc = nn.Sequential(nn.Flatten(start_dim=-2), multihead_Attention(8, 8), nn.AdaptiveAvgPool2d(1), nn.Flatten()) elif additional_layer == "conv": model.avgpool = nn.AdaptiveAvgPool2d((16, 1)) # Shape: (BS, 512, 16, 1) model.use_flatten = False model.fc = nn.Sequential(nn.Flatten(start_dim=-2), nn.Conv1d(512, 512, 4), nn.AdaptiveAvgPool1d(1), nn.Flatten()) elif additional_layer == "TSiT": from tsai.models.TSiTPlus import TSiTPlus model.avgpool = nn.AdaptiveAvgPool2d((16, 1)) # -> (BS, 512, 16, 1) model.use_flatten = False model.fc = nn.Sequential(nn.Flatten(start_dim=-2), # -> (BS, 512, 16) TransposeT(), # -> (BS, 16, 512) TSiTPlus(16, 16, seq_len=512, d_model=32, depth=3)) # -> (BS, 16) elif additional_layer == "gMLP": from tsai.models.gMLP import gMLP model.avgpool = nn.AdaptiveAvgPool2d((16, 1)) # -> (BS, 512, 16, 1) model.use_flatten = False model.fc = nn.Sequential(nn.Flatten(start_dim=-2), # -> (BS, 512, 16) TransposeT(), # -> (BS, 16, 512) gMLP(16, 16, seq_len=512, d_model=32, depth=3)) # -> (BS, 16) elif additional_layer == "autoencoder": model.fc = nn.Sequential(nn.Linear(512, 128), nn.ReLU(), nn.Linear(128, 32), nn.ReLU(), nn.Linear(32, 8), nn.Linear(8, 32), nn.ReLU(), nn.Linear(32, 128), nn.ReLU(), nn.Linear(128, 512)) else: model.use_fc = False model.load_state_dict(torch.load(startweight, map_location=device)) model.eval() from easyfsl.methods import PrototypicalNetworks few_shot_classifier = PrototypicalNetworks(model).to(device) # --------------------------------------------------------------------------------------------- # addWeightspath = folder + "/post/weights/" save_file_base = folder + "/post/test/summary_" save_file_all_vals = folder + "/post/test/preds_" save_file_all_vals_ind = folder + "/post/test/inds_" for cpi, class_perm in enumerate(class_permutations): # Test on every permutation of classes print("Dealing with classes permutation: ", cpi, class_perm) prev_classes = [] results = [] save_file = save_file_base + "_".join([str(pc) for pc in class_perm[1:]]) + ".txt" for cpj, cclass in enumerate(class_perm): # Add the new classes on by one and test if cclass == -1: prev_weights = None else: prev_classes.append(str(cclass)) prev_weights = addWeightspath + "_".join(prev_classes) + ".h5" few_shot_classifier.backbone.fc.load_state_dict(torch.load(prev_weights, map_location=device)) print("Dealing with current class: ", cclass, " from perm: ", class_perm, " with prev classes: ", prev_classes) cur_old_classes = np.array(old_classes + [int(c) for c in prev_classes]) cur_old_classes.sort() cur_new_classes = np.array([pc for pc in range(11) if (pc not in cur_old_classes)]) additional_classes = [3 + np.array(list(x)).astype(int) for x in list(powerset("".join((cur_new_classes - 3).astype("str"))))] results.append("Additionally trained on: " + " ".join([str(pc) for pc in prev_classes]) + "\n") for ai, add_class in enumerate(additional_classes): if os.path.exists(save_file_all_vals + "_prev_classes_" + "_".join([str(pc) for pc in prev_classes]) + "_add_classes_" + "_".join([str(pc) for pc in add_class]) + ".npy"): print("Skipped: ", ai, add_class, " (Already evaluated previously)") continue else: print("Dealing with additional classes: ", ai, add_class) cur_classes = np.concatenate([cur_old_classes, add_class]) cur_classes.sort() cur_support_list_files = [] cur_support_list_classes = [] for ci, cc in enumerate(cur_classes): cur_support_list_files.extend(support_list[cc]) cur_support_list_classes.extend([ci] * len(support_list[cc])) cur_support_list = [cur_support_list_files, cur_support_list_classes] # Prepare support images # support_images, support_labels = utilities.get_support_data(cur_support_list, time_size, norm=norm_data, norm_type=1) support_images = torch.tensor(support_images).to(device) support_labels = torch.tensor(support_labels).to(device) few_shot_classifier.process_support_set(support_images, support_labels) # ---------------------- # # -------------------------- # datagen = utilities.gen_data_batch_test(test_list, test_classes, time_size, batchSize, norm=norm_data, norm_type=1) pred = [] lab = [] inds = [] bcount = 0 for X_batch, Y_batch, ind_batch in datagen: if bcount % 100 == 0: print("Dealing with batch: %d" % bcount) bcount += 1 inputs = torch.tensor(X_batch).to(device) out = few_shot_classifier(inputs).float() pred_x = out.detach().cpu().numpy() pred.extend(pred_x) lab.extend(Y_batch) inds.extend(ind_batch) del inputs, out pred = np.array(pred) lab = np.array(lab) inds = np.array(inds) np.save(save_file_all_vals + "_prev_classes_" + "_".join([str(pc) for pc in prev_classes]) + "_add_classes_" + "_".join([str(pc) for pc in add_class]) + ".npy", pred) np.save(save_file_all_vals_ind + "_prev_classes_" + "_".join([str(pc) for pc in prev_classes]) + "_add_classes_" + "_".join([str(pc) for pc in add_class]) + ".npy", inds) pred = to_softmax(pred) # reduce same inds -- # # Each sample is predicted on 4 times. The 4 predictions correspond to horizontal and vertical flipping of the sample pred_red_arg = [] pred_red = [] lab_red = [] cpred_arg = np.zeros(len(cur_classes)) cpred = np.zeros(len(cur_classes)) clab = [] cind = inds[0] for icind, ccind in enumerate(inds): if ccind == cind: cpred += pred[icind] cpred_arg[np.argmax(pred[icind])] += 1 clab.append(lab[icind]) else: cind = ccind pred_red.append(cpred) pred_red_arg.append(cpred_arg) lab_red.append(np.sum(clab) / len(clab)) cpred = np.zeros(len(cur_classes)) cpred_arg = np.zeros(len(cur_classes)) cpred += pred[icind] cpred_arg[np.argmax(pred[icind])] += 1 clab = [lab[icind]] pred_red.append(cpred) pred_red_arg.append(cpred_arg) lab_red.append(np.sum(clab) / len(clab)) pred = np.array(pred_red) pred_arg = np.array(pred_red_arg) lab = np.array(lab_red) # ------------------- # # Calcualte the results for the binary case of jammer/no jammer # lab_bool = lab > 2 pred_bool = np.argmax(pred, axis=1) > 2 pred_arg_bool = np.sum(pred_arg[:, 3:], axis=1) > 0 acc = np.mean(pred_bool == lab_bool) true_positives = np.sum(pred_bool * lab_bool) true_negatives = np.sum((~pred_bool) * (~lab_bool)) false_positives = np.sum(pred_bool * (~lab_bool)) false_negatives = np.sum((~pred_bool) * lab_bool) precision = true_positives/(true_positives + false_positives) recall = true_positives/(true_positives + false_negatives) f1_score = (2 * precision * recall) / (precision + recall) f2_score = ((1 + 2**2) * precision * recall) / (2**2 * precision + recall) print('Test Acc Prob: %.5f, F1: %.5f, F2: %.5f, Prec: %.5f, Rec: %.5f' % (acc, f1_score, f2_score, precision, recall)) results.append([acc, f1_score, f2_score, precision, recall, 1]) acc = np.mean(pred_arg_bool == lab_bool) true_positives = np.sum(pred_arg_bool * lab_bool) true_negatives = np.sum((~pred_arg_bool) * (~lab_bool)) false_positives = np.sum(pred_arg_bool * (~lab_bool)) false_negatives = np.sum((~pred_arg_bool) * lab_bool) precision = true_positives/(true_positives + false_positives) recall = true_positives/(true_positives + false_negatives) f1_score = (2 * precision * recall) / (precision + recall) f2_score = ((1 + 2**2) * precision * recall) / (2**2 * precision + recall) print('Test Acc Arg: %.5f, F1: %.5f, F2: %.5f, Prec: %.5f, Rec: %.5f' % (acc, f1_score, f2_score, precision, recall)) results.append([acc, f1_score, f2_score, precision, recall, 0]) with open(save_file, 'a') as f: f.write("Train\tAccuracy\tF1\tF2\tPrecision\tRecall\tUse Prob\n") for ir, res in enumerate(results): if len(res) > 6: f.write(res) else: f.write("%d\t%.5f\t\t%.5f\t%.5f\t%.5f\t\t%.5f\t\t%d\n" % (ir, res[0], res[1], res[2], res[3], res[4], res[5])) print("Done")