gnss_few-shot_learning / source_code /test_episodic.py
FelixOtt's picture
Upload folder using huggingface_hub
72a1ed9 verified
Raw History Blame Contribute Delete
15 kB
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
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('--multi', help='If 0: Test on binaryclass training. If 1: Test on multiclass training', required=False, default=1)
parser.add_argument('--addlayer', help='layer(s) to add after resnet', required=False, default="conv")
parser.add_argument('--triplets', help='Whether to use triplet loss 0: No, 1: Yes, 2: Quadruplet loss', required=False, default="0")
args = parser.parse_args()
training_num = int(args.run_num)
use_multiclass_training = int(args.multi)
additional_layer = args.addlayer
use_triplets = int(args.triplets)
# Hyper Params
base_path_data = "../../Spectrum_Highway1/"
base_path = "./"
test_file = base_path_data + "GNSS_dataset/test.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"
if use_triplets == 1:
train_output_folder += "_triplet"
elif use_triplets == 2:
train_output_folder += "_quadruplet"
print(train_output_folder + "/%06d_202*" % training_num)
folder = glob(train_output_folder + "/%06d_202*" % training_num)[0]
fewshot_method = folder.split("_")[-3]
new_classes = np.array([3, 6, 8, 9])
old_classes = np.array(list(set(np.arange(11)) - set(new_classes)))
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"))))]
# ---------- #
# 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<num>\d{1,6}).h5')
wm_fs = re.compile(r'.*/weights/(?P<num>\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 + "/test/"):
os.makedirs(folder + "/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])
# ---------------------------- #
startweight = weights[np.argmax(log_accs)]
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)
# ------------------------------------- #
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 and load weights --------------------------------------------------------------- #
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
if fewshot_method == "prototypical" or fewshot_method == "simpleshot":
model.load_state_dict(torch.load(startweight, map_location=device))
model.eval()
if fewshot_method == "prototypical":
from easyfsl.methods import PrototypicalNetworks
few_shot_classifier = PrototypicalNetworks(model).to(device)
elif fewshot_method == "simpleshot":
from easyfsl.methods import SimpleShot
few_shot_classifier = SimpleShot(model).to(device)
elif fewshot_method == "relation":
from easyfsl.methods import RelationNetworks
few_shot_classifier = RelationNetworks(backbone=model, feature_dimension=512).to(device)
model.use_flatten = False
elif fewshot_method == "bdcspn":
from easyfsl.methods import BDCSPN
few_shot_classifier = BDCSPN(model).to(device)
elif fewshot_method == "FEAT":
from easyfsl.methods import FEAT
wp = "./feat-1-shot.pth"
few_shot_classifier = FEAT.from_resnet12_checkpoint(checkpoint_path=wp).to(device)
elif fewshot_method == "laplacianshot":
from easyfsl.methods import LaplacianShot
few_shot_classifier = LaplacianShot(model).to(device)
elif fewshot_method == "matchingnetworks":
from easyfsl.methods import MatchingNetworks
few_shot_classifier = MatchingNetworks(model, feature_dimension=512).to(device)
else:
print("Invalid fewshot method: ", fewshot_method)
exit()
if fewshot_method == "relation" or fewshot_method == "bdcspn" or fewshot_method == "FEAT" or fewshot_method == "laplacianshot" or fewshot_method == "matchingnetworks":
few_shot_classifier.load_state_dict(torch.load(startweight, map_location=device))
few_shot_classifier.eval()
# --------------------------------------------------------------------------------------------- #
save_file = folder + "/test/summary.txt"
save_file_all_vals = folder + "/test/preds_"
save_file_all_vals_ind = folder + "/test/inds_"
results = []
for ai, add_class in enumerate(additional_classes): # Calculate the results for every combination of 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, 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 + "_".join(cur_classes.astype(str)) + ".npy", pred)
np.save(save_file_all_vals_ind + "_".join(cur_classes.astype(str)) + ".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):
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")