Download source_code/post_train_episodic.py from FelixOtt/gnss_few-shot_learning: direct link, hf CLI and curl.
- Browser
- Download file 15.9 kB
-
https://huggingface.co/datasets/FelixOtt/gnss_few-shot_learning/resolve/main/source_code/post_train_episodic.py
- Command line
-
hf download hf://datasets/FelixOtt/gnss_few-shot_learning/source_code/post_train_episodic.py
-
curl -L -o post_train_episodic.py https://huggingface.co/datasets/FelixOtt/gnss_few-shot_learning/resolve/main/source_code/post_train_episodic.py
15.9 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 | |
| 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") | |