import sys import os import numpy as np import torch from torch import nn from tqdm import tqdm from torch.utils.data import DataLoader import torch.optim as optim from itertools import chain, combinations import utilities_raw as utilities # Assuming utilities_raw is in the same directory as this script from torchvision.models import resnet18 from easyfsl.methods import PrototypicalNetworks def to_softmax(inarr): return np.exp(inarr)/np.sum(np.exp(inarr), axis=1)[:, None] def powerset(iterable): s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) def main(strategy,epoch_no,env): list_cl_env = { 1: [0,1, 2, 5], 2: [0,2, 5], 3: [0,1, 2, 5], 4: [0,1, 2, 5], 5: [0,1, 2], 6: [0,1, 2, 5], 7: [0,2], 8: [0,1, 2, 5], 9: [0,1, 2, 5], 10: [0,1, 2, 5], 11: [0,1, 2, 5], 12: [0,1, 2, 5] } # folder = f"./workspace/Jammer_detection/Src/federated_synthetic_data/federated_scr/{strategy}/model/" folder = f"./workspace/Jammer_detection/Src/Linkhalle_federated/federated_learning/{strategy}/model/" # folder = "./workspace/Jammer_detection/Src/Env_federated/outputs/2024-03-27/12-36-41/model_global_env/" #result_folder = f"{folder}/env_{env}/r_{epoch_no}/" result_folder = f"{folder}/env_all/r_{epoch_no}/" # startweight = f"{folder}model_weights0epoch{epoch_no}.h5" startweight = f"{folder}round--{epoch_no}_weights.h5" # startweight = f"{folder}model_weights0epoch100.h5" torch.autograd.set_detect_anomaly(True) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print(device) batchSize = 40 dp_base = "./workspace/Jammer_detection/Datasets/Diff_env_daten/base_data/data" split_file = "./workspace/Jammer_detection/Datasets/Diff_env_daten/base_data/all_test_env.txt" new_classes = 3 + np.array(list(list(powerset("013"))[7])).astype(int) old_classes = np.array(list(set(np.arange(6)) - set(new_classes))) # new_classes = np.array([nc for nc in new_classes if nc != 6]) print("New classes: ", new_classes) additional_classes = [3 + np.array(list(x)).astype(int) for x in list(powerset("".join((new_classes - 3).astype("str"))))] print(f"old classes are -----------------------------{old_classes}") # support_list = { # 0: ["03926.npy", "04028.npy", "03926.npy","04258.npy"], # 1: ["02007.npy", "02127.npy","22207.npy", "24553.npy"], # 2: ["00592.npy", "00403.npy","21058.npy", "23407.npy"], ##class 6 8 # 5: ["03705.npy", "03668.npy","22106.npy", "24462.npy"] # } #6 #3 # support_list = { # 0: ["03926.npy", "04028.npy","04258.npy", "03926.npy",], # 1: ["02007.npy", "02127.npy", "22207.npy", "17355.npy",], #class 3,6 # 2: ["00592.npy", "00403.npy", "21058.npy", "16209.npy",], # 5: ["03705.npy", "03668.npy", "22106.npy", "17264.npy",] # } support_list = { 0: ["03926.npy", "04028.npy","04258.npy", "03926.npy","03890.npy","04108.npy","04107.npy","00409.npy","04070.npy"], 1: ["02007.npy", "17355.npy", "19000.npy", "20559.npy","22207.npy","24553.npy","26213.npy","27850.npy","29529.npy","38688.npy"], #class 3,6 2: ["00592.npy", "04697.npy", "16209.npy", "17848.npy","19509.npy","21062.npy","22699.npy","23407.npy","25060.npy","26707.npy","30063.npy"], 5: ["03705.npy", "15796.npy", "17264.npy", "18910.npy","22106.npy","24462.npy","27759.npy","37956.npy"] } if not os.path.exists(result_folder): os.makedirs(result_folder) print(startweight) with open(split_file, "r") as f: test_info = f.readlines() test_info = np.array([x.split("\n")[0].split("\t") for x in test_info]) classes = test_info[:, 1].astype(int) mask_class = np.isin(classes, [0, 1, 2, 5]) ##0, 1, 2, 5 # mask_class = np.isin(classes, list_cl_env[env]) ##0, 1, 2, 5 test_info = test_info[mask_class] # ##env code # environments = test_info[:, -1].astype(int) # mask = np.isin(environments, [0,env]) #0,1, 6, 8 # test_info = test_info[mask] test_list_raw = test_info[:, 0] test_classes = test_info[:, 1].astype(int) test_list = [] for tlr in test_list_raw: tlr = tlr.split("/")[1] test_list.append([dp_base +"/"+ tlr]) model =resnet18(pretrained=False) model.fc = nn.Identity() few_shot_classifier = PrototypicalNetworks(model).to(device) few_shot_classifier.load_state_dict(torch.load(startweight, map_location=device)) few_shot_classifier.eval() save_file = f"{result_folder}/summary.txt" save_file_all_vals = f"{result_folder}/preds_" save_file_all_vals_ind = f"{result_folder}/inds_" results = [] # for ai, add_class in enumerate(additional_classes[2:]): # ai +=2 print(additional_classes) additional_classes = [additional_classes[0]] for ai, add_class in enumerate(additional_classes): print("Dealing with classes: ", ai, add_class) cur_classes = np.concatenate([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,split_file,dp_base) support_images = torch.tensor(support_images).to(device) support_labels = torch.tensor(support_labels).to(device) print(f"my tesing support set is -----------------------{support_images.shape}") few_shot_classifier.process_support_set(support_images, support_labels) # print(np.sum(np.isnan(few_shot_classifier.prototypes.cpu().detach().numpy()))) datagen = utilities.gen_data_batch_test(test_list, test_classes, batchSize) 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) # print(inputs.shape) out = few_shot_classifier(inputs).float() #out = model(inputs).float() ##addded pred_x = out.detach().cpu().numpy() # print(pred_x) 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) lab[lab == 5] = 3 np.save(save_file_all_vals + "_".join(cur_classes.astype(str)) + ".npy", pred) np.save(save_file_all_vals_ind + "_".join(cur_classes.astype(str)) + ".npy", inds) # print(pred[:5]) pred = to_softmax(pred) pred_red_arg = [] pred_red = [] lab_red = [] cpred_arg = np.zeros(len(cur_classes)) cpred = np.zeros(len(cur_classes)) clab = [] cind = inds[0] # print(pred[:5]) 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) lab_bool = lab > 0 ###### change this number as per classes # print(pred[:5]) pred_bool = np.argmax(pred, axis=1) > 0 ###### change this number as per classes pred_arg_bool = np.sum(pred_arg[:, 1:], axis=1) > 0 ###### change this number as per classes 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): 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") if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: python script.py ") sys.exit(1) strategy = sys.argv[1] epoch_no = sys.argv[2] print(epoch_no) try: epoch_no = int(epoch_no) except ValueError: print("Error: run_no must be an integer.") sys.exit(1) # env_no = range(1,13) # epoch_no = range(1,21) # for i in env_no: # print(f"Im testing for run env-----------{i}") # for j in epoch_no: # main(strategy,j,i) i = 1 epoch_no=10 # for epoch_no in range (1,11): main(strategy,epoch_no,i)