File size: 15,001 Bytes
72a1ed9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 | 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")
|