File size: 15,864 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 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 | 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
from easyfsl.utils import evaluate
import argparse
import os
import re
import time
from torch.optim import SGD, Optimizer
from torch.optim.lr_scheduler import MultiStepLR
from glob import glob
from itertools import chain, combinations, permutations
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 train folder', required=True)
parser.add_argument('--timestamps', help='Frequency for saving Weights and Validation', required=False, default=5)
parser.add_argument('--epochs', help='Number of epochs', required=False, default=5)
parser.add_argument('--norm', help='0: No norm, 1: Subtract minimum to get positive values', required=False, default="1")
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="dense")
args = parser.parse_args()
train_num = int(args.run_num)
timestamps = int(args.timestamps)
epochs = int(args.epochs)
norm_type = int(args.norm)
use_multi = int(args.multi)
additional_layer = args.addlayer
# Params
# The assumption is, that the dataset is stored in base_path + "GNSS_dataset"
base_path_data = "../../Spectrum_Highway1/"
base_path = "./"
train_file = base_path_data + "GNSS_dataset/train.txt"
adap_file = base_path_data + "GNSS_dataset/adap.txt"
if norm_type == 0:
norm_data = None
elif norm_type == 1:
norm_data = [-135.99690198, 0.]
time_size = 243
# ----------- #
# Create Folders
# The post training weights and logs will be saved in the already existing path base_path + "results_episodic + x" + "post"
train_output_folder = "results_episodic"
if additional_layer != "None":
train_output_folder += "_" + additional_layer
if not use_multi:
train_output_folder += "_binary"
cur_folders = glob(base_path + train_output_folder + "/%06d_202*-*" % train_num)
if len(cur_folders) == 0:
print("No Training with number %d found for: " % train_num, additional_layer, " Multi: " + str(use_multi))
exit()
base_path_train = cur_folders[0]
print("Running: ", train_num, timestamps, epochs, norm_type, use_multi, additional_layer)
if not os.path.exists(base_path_train + "/post"):
os.mkdir(base_path_train + "/post")
os.mkdir(base_path_train + "/post/weights")
else:
print("Already proccessing on another node")
#exit()
outputWeightspath = base_path_train + "/post/weights/"
log_loss = open(base_path_train + "/post/loss.txt", "w")
log = open(base_path_train + "/post/log.txt", "w")
random_seed = int(base_path_train.split("/")[-1].split("_")[-6])
# ------------ #
# Make deterministic #
np.random.seed(random_seed)
torch.manual_seed(random_seed)
random.seed(random_seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
# ------------------ #
# Create Train Test data lists
new_classes = np.array([3, 6, 8, 9])
old_classes = list(set(np.arange(11)) - set(new_classes))
print("New classes: ", new_classes, " Old classes: ", old_classes)
class_permutations = list(permutations(new_classes)) # Post train on every combination and order of new classes
print("Train File: ", train_file)
with open(train_file, "r") as f:
train_info = f.readlines()
train_info = [x.split("\n")[0].split("\t") for x in train_info]
print("Adaptation File: ", adap_file)
with open(adap_file, "r") as f:
adap_info = f.readlines()
adap_info = [x.split("\n")[0].split("\t") for x in adap_info]
data_info = train_info
data_info.extend(adap_info)
import utilities
if use_multi:
train_list_raw, valid_list_raw, train_y_raw, valid_y_raw, num_classes = utilities.get_training_data(data_info)
else:
train_list_raw, valid_list_raw, train_y_raw, valid_y_raw, num_classes = utilities.get_training_data(data_info, reduce_to_binary=True)
train_list = []
valid_list = []
train_y = []
valid_y = []
for ti, tlr in enumerate(train_list_raw):
# add_folder = ("data/%02d" % (int(tlr.split("/")[-1].split(".npy")[0]) // 15000)) + "/" + tlr.split("/")[-1]
add_folder = ("data/" + tlr.split("/")[-1]
for i in range(4):
train_list.append([base_path_data + "GNSS_dataset/" + add_folder, i])
train_y.append(train_y_raw[ti])
for vi, vlr in enumerate(valid_list_raw):
# add_folder = ("data/%02d" % (int(vlr.split("/")[-1].split(".npy")[0]) // 15000)) + "/" + vlr.split("/")[-1]
add_folder = ("data/" + vlr.split("/")[-1]
for i in range(4):
valid_list.append([base_path_data + "GNSS_dataset/" + add_folder, i])
valid_y.append(valid_y_raw[vi])
# -------------------------- #
# ------------------------------ Select Base starting weights ---------------------------------------- #
wm = re.compile(r'.*/weights/(?P<num>\d{1,6}).h5')
weights = glob(base_path_train + "/weights/*")
weights.sort(key=lambda x: int(wm.match(x).group(1)))
if len(weights) == 0:
print("Skipped %d: Training not finished." % training_num)
exit()
# For getting best weights --- #
log_train_file = glob(base_path_train + "/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)
# ---------------------------- #
base_startweight = weights[weights_ind_best]
# ---------------------------------------------------------------------------------------------------- #
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
for ci, child in enumerate(model.children()): # freezes all layers up to and including the averaging layer -> (BS, 512, 1, 1)
if ci < 9:
for param in child.parameters():
param.requires_grad = False
model.train()
model = model.to(device)
from easyfsl.methods import FewShotClassifier
from easyfsl.methods import PrototypicalNetworks
few_shot_classifier = PrototypicalNetworks(model).to(device)
from easyfsl.samplers import TaskSampler
# ---------- #
for cpi, classes in enumerate(class_permutations): # Iterate over all class permutations
print("Dealing with class permutation: ", classes)
prev_classes = []
for cpj, cclass in enumerate(classes): # Add each class in the current permutation one by one
print("Dealing with current class: ", cclass)
if len(prev_classes) == 0:
prev_weights = base_startweight
new_weights = outputWeightspath + str(cclass) + ".h5"
else:
prev_weights = outputWeightspath + "_".join(prev_classes) + ".h5"
new_weights = outputWeightspath + "_".join(prev_classes) + "_" + str(cclass) + ".h5"
prev_classes.append(str(cclass))
if os.path.exists(new_weights): # Skip if previous permutations already covered the current order
print("Skipped new class: ", cclass, " It already exists.")
continue
num_classes = len(old_classes) + len(prev_classes)
cur_classes = old_classes + [int(c) for c in prev_classes]
if len(prev_classes) == 1:
few_shot_classifier.backbone.load_state_dict(torch.load(prev_weights, map_location=device))
else:
few_shot_classifier.backbone.fc.load_state_dict(torch.load(prev_weights, map_location=device))
train_optimizer = SGD(few_shot_classifier.parameters(), lr=1e-2, momentum=0.9, weight_decay=5e-4)
train_scheduler = MultiStepLR(train_optimizer, milestones=[120, 160], gamma=0.1)
criterion = torch.nn.CrossEntropyLoss().to(device)
print("Current classes: ", cur_classes)
cur_train_list = [tl for ti, tl in enumerate(train_list) if train_y[ti] in cur_classes]
cur_train_y = [ty for ty in train_y if ty in cur_classes]
cur_valid_list = [vl for vi, vl in enumerate(valid_list) if valid_y[vi] in cur_classes]
cur_valid_y = [vy for vy in valid_y if vy in cur_classes]
def training_epoch(model: FewShotClassifier, data_loader: DataLoader, optimizer: Optimizer, method : str = "prototypical"):
all_loss = []
model.train()
with tqdm(
enumerate(data_loader), total=len(data_loader), desc="Training"
) as tqdm_train:
for episode_index, (
support_images,
support_labels,
query_images,
query_labels,
_,
) in tqdm_train:
optimizer.zero_grad()
model.process_support_set(
support_images.to(device), support_labels.to(device)
)
classification_scores = model(query_images.to(device))
# Added to deal with different losses for different fewshot methods ------------------------------------- #
if method == "simpleshot" or method == "bdcspn":
classification_scores = (torch.clamp(classification_scores, min=-0.1) + 0.1) / 1.1
if method == "simpleshot" or method == "bdcspn" or method == "relation" or method == "laplacianshot":
query_labels = torch.nn.functional.one_hot(query_labels, num_classes=num_classes).float()
# ------------------------------------------------------------------------------------------------------- #
loss = criterion(classification_scores, query_labels.to(device))
loss.backward()
optimizer.step()
all_loss.append(loss.item())
tqdm_train.set_postfix(loss=mean(all_loss))
return mean(all_loss)
# For validation -------------------------------------------------------------------- #
n_way = num_classes
n_shot = 1
if use_multi:
n_query = 1
else:
n_query = 9
n_validation_tasks = 250
val_set = utilities.val_set(cur_valid_list, cur_valid_y, time_size, norm=norm_data, norm_type=norm_type)
val_sampler = TaskSampler(
val_set, n_way=n_way, n_shot=n_shot, n_query=n_query, n_tasks=n_validation_tasks
)
val_loader = DataLoader(
val_set,
batch_sampler=val_sampler,
num_workers=1,
pin_memory=True,
collate_fn=val_sampler.episodic_collate_fn,
)
# ----------------------------------------------------------------------------------- #
# For training -------------------------------------------------------------------- #
n_shot_tr = 2
if use_multi:
n_query_tr = 3
else:
n_query_tr = 20
n_tasks_per_epoch = 250
train_set = utilities.val_set(cur_train_list, cur_train_y, time_size, norm=norm_data, norm_type=norm_type)
train_sampler = TaskSampler(
train_set, n_way=n_way, n_shot=n_shot_tr, n_query=n_query_tr, n_tasks=n_tasks_per_epoch
)
train_loader = DataLoader(
train_set,
batch_sampler=train_sampler,
num_workers=1,
pin_memory=True,
collate_fn=train_sampler.episodic_collate_fn,
)
# --------------------------------------------------------------------------------- #
for e in range(epochs):
print("Epoch: %d/%d" % (e, epochs))
average_loss = training_epoch(few_shot_classifier, train_loader, train_optimizer)
log_loss.write("%f\n" % average_loss)
log_loss.flush()
if (e + 1) % int(timestamps) == 0:
few_shot_classifier.eval()
validation_accuracy = evaluate(
few_shot_classifier, val_loader, device=device, tqdm_prefix="Validation"
)
print('Valid Acc: %.5f' % validation_accuracy)
log.write("Valid Acc: %.5f" % validation_accuracy + "\t" + "_".join(prev_classes) + "\n")
log.flush()
torch.save(few_shot_classifier.backbone.fc.state_dict(), new_weights)
few_shot_classifier.train()
log.close()
log_loss.close()
print("Done")
|