gnss_few-shot_learning / source_code /train_episodic.py
FelixOtt's picture
Upload folder using huggingface_hub
72a1ed9 verified
Raw History Blame Contribute Delete
25.5 kB
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 time
from torch.optim import SGD, Optimizer
from torch.optim.lr_scheduler import MultiStepLR
from glob import glob
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=False, default=0)
parser.add_argument('--timestamps', help='Frequency for saving Weights and Validation', required=False, default=40)
parser.add_argument('--epochs', help='Number of epochs', required=False, default=200)
parser.add_argument('--net', help='Net to use', required=False, default="resnet")
parser.add_argument('--norm', help='0: No norm, 1: Subtract minimum to get positive values', required=False, default="1")
parser.add_argument('--fewshot', help='Fewshot method to use', required=False, default="prototypical")
parser.add_argument('--seed', help='Seed for the randomness', required=False, default="0")
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="None")
parser.add_argument('--triplets', help='Whether to use triplet loss 0: No, 1: Yes, 2: Quadruplet loss', required=False, default="0")
parser.add_argument('--margin', help='Margin to use for triplets', required=False, default="2.0")
parser.add_argument('--margin2', help='Margin 2 to use for quadruplets', required=False, default="10.0")
args = parser.parse_args()
run_num = int(args.run_num)
timestamps = int(args.timestamps)
epochs = int(args.epochs)
net_name = args.net
norm_type = int(args.norm)
random_seed = int(args.seed)
fewshot_method = args.fewshot
use_multi = int(args.multi)
additional_layer = args.addlayer
use_triplets = int(args.triplets)
margin = float(args.margin)
margin2 = float(args.margin2)
if fewshot_method in ["simpleshot", "relation", "bdcspn", "laplacianshot"] and use_triplets > 0:
raise Exception("Invalid combination of few-shot method and loss function ! (Not implemented)")
if fewshot_method == "relation" and additional_layer != None:
raise Exception("Invalid combination of few-shot method and additional layer ! (Not implemented)")
if fewshot_method == "matchingnetworks" and additional_layer in ["TSiT", "gMLP"]:
raise Exception("Invalid combination of few-shot method and additional layer ! (Not implemented)")
base_path_data = "../../Spectrum_Highway1/"
base_path = "./"
train_file = base_path_data + "GNSS_dataset/train.txt"
if norm_type == 0:
norm_data = None
elif norm_type == 1:
norm_data = [-135.99690198, 0.]
time_size = 243
# ----------- #
# Create Folders
# The training weights and logs will be saved in the base_path + "results_episodic + x" depending on the traiing type (multi, triplet, quadruplet)
train_output_folder = "results_episodic"
if additional_layer != "None":
train_output_folder += "_" + additional_layer
if not use_multi:
train_output_folder += "_binary"
if use_triplets == 1:
train_output_folder += "_triplet"
elif use_triplets == 2:
train_output_folder += "_quadruplet"
print("Running: ", run_num, timestamps, epochs, time_size, net_name, fewshot_method, random_seed, additional_layer)
currentDate = time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime())
if not os.path.exists(base_path + train_output_folder):
os.mkdir(base_path + train_output_folder)
res_path = base_path + train_output_folder + ("/%06d_" % run_num) + str(currentDate) + "_" + str(random_seed) + "_" + str(int(margin*10)) + "_" + str(int(margin2*10)) + "_" + fewshot_method + "_" + str(norm_type) + "_" + net_name
os.mkdir(res_path)
os.mkdir(res_path + "/weights/")
outputWeightspath = res_path + "/weights/"
log_loss = open(res_path + "/loss.txt", "w")
log = open(res_path + "/log.txt", "w")
# ------------ #
# 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
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]
import utilities
if use_multi:
train_list_raw, valid_list_raw, train_y_raw, valid_y_raw, num_classes = utilities.get_training_data(train_info)
else:
train_list_raw, valid_list_raw, train_y_raw, valid_y_raw, num_classes = utilities.get_training_data(train_info, reduce_to_binary=True)
train_list = []
valid_list = []
train_y = []
valid_y = []
print(np.unique(train_y_raw))
"""
Extract tar files and keep them in the subfolder 00-13
"""
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])
# -------------------------- #
class tripletloss(nn.Module):
def __init__(self, margin=1.):
super().__init__()
self.margin = margin
self.eps = 10e-8
def forward(self, embeddings, labels):
# Embeddings are of shape (n_way * n_querry, n_way)
# Labels are of shape (n_way * n_querry)
pos_mask = torch.zeros_like(embeddings, dtype=bool).to(device)
inds = (torch.arange(labels.size(-1)) * embeddings.size(-1)).to(device)
inds = inds + labels
pos_mask.flatten().scatter_(dim=0, index=inds, value=True).reshape_as(embeddings)
anchor_positive_dists = embeddings[pos_mask].reshape((embeddings.size(0), 1))
anchor_negative_dists = embeddings[~pos_mask].reshape((embeddings.size(0), -1))
triplet_loss = torch.clamp(anchor_negative_dists - anchor_positive_dists + self.margin, min=0.0).reshape((embeddings.size(0), -1))
num_positive_losses = (triplet_loss > self.eps).float().sum(1)
triplet_loss = triplet_loss.sum(1) / (num_positive_losses + self.eps)
return triplet_loss.sum()
class quadrupleloss3(nn.Module):
def __init__(self, class_mask, margin1=1., margin2=2.):
super().__init__()
self.class_mask = class_mask.to(device)
self.margin1 = margin1
self.margin2 = margin2
self.eps = 10e-8
self.tensor_eye = (~(torch.eye(7).bool())).unsqueeze(1).to(device)
def forward(self, embeddings, labels):
# Embeddings are of shape (n_way * n_querry, n_way)
# Labels are of shape (n_way * n_querry)
mask_0 = (labels == 0).unsqueeze(1).repeat((1, embeddings.size(-1)))
mask_1 = (labels == 1).unsqueeze(1).repeat((1, embeddings.size(-1)))
mask_2 = (labels == 2).unsqueeze(1).repeat((1, embeddings.size(-1)))
mask_3 = (labels == 3).unsqueeze(1).repeat((1, embeddings.size(-1)))
mask_4 = (labels == 4).unsqueeze(1).repeat((1, embeddings.size(-1)))
mask_5 = (labels == 5).unsqueeze(1).repeat((1, embeddings.size(-1)))
mask_6 = (labels == 6).unsqueeze(1).repeat((1, embeddings.size(-1)))
embeddings_0 = embeddings[mask_0].reshape((-1, embeddings.size(-1)))
embeddings_1 = embeddings[mask_1].reshape((-1, embeddings.size(-1)))
embeddings_2 = embeddings[mask_2].reshape((-1, embeddings.size(-1)))
embeddings_3 = embeddings[mask_3].reshape((-1, embeddings.size(-1)))
embeddings_4 = embeddings[mask_4].reshape((-1, embeddings.size(-1)))
embeddings_5 = embeddings[mask_5].reshape((-1, embeddings.size(-1)))
embeddings_6 = embeddings[mask_6].reshape((-1, embeddings.size(-1)))
anchor_positive_dists_0 = embeddings_0[:, 0].reshape((embeddings_0.size(0), 1))
anchor_positive_dists_1 = embeddings_1[:, 1].reshape((embeddings_1.size(0), 1))
anchor_positive_dists_2 = embeddings_2[:, 2].reshape((embeddings_2.size(0), 1))
anchor_positive_dists_3 = embeddings_3[:, 3].reshape((embeddings_3.size(0), 1))
anchor_positive_dists_4 = embeddings_4[:, 4].reshape((embeddings_4.size(0), 1))
anchor_positive_dists_5 = embeddings_5[:, 5].reshape((embeddings_5.size(0), 1))
anchor_positive_dists_6 = embeddings_6[:, 6].reshape((embeddings_6.size(0), 1))
anchor_similar_dists_0 = embeddings_0[self.class_mask[0].unsqueeze(0).repeat((embeddings_0.size(0), 1))].reshape((embeddings_0.size(0), -1))
anchor_similar_dists_1 = embeddings_1[self.class_mask[1].unsqueeze(0).repeat((embeddings_1.size(0), 1))].reshape((embeddings_1.size(0), -1))
anchor_similar_dists_2 = embeddings_2[self.class_mask[2].unsqueeze(0).repeat((embeddings_2.size(0), 1))].reshape((embeddings_2.size(0), -1))
anchor_similar_dists_3 = embeddings_3[self.class_mask[3].unsqueeze(0).repeat((embeddings_3.size(0), 1))].reshape((embeddings_3.size(0), -1))
anchor_similar_dists_4 = embeddings_4[self.class_mask[4].unsqueeze(0).repeat((embeddings_4.size(0), 1))].reshape((embeddings_4.size(0), -1))
anchor_similar_dists_5 = embeddings_5[self.class_mask[5].unsqueeze(0).repeat((embeddings_5.size(0), 1))].reshape((embeddings_5.size(0), -1))
anchor_similar_dists_6 = embeddings_6[self.class_mask[6].unsqueeze(0).repeat((embeddings_6.size(0), 1))].reshape((embeddings_6.size(0), -1))
anchor_negative_dists_0 = embeddings_0[self.tensor_eye[0].repeat((embeddings_0.size(0), 1)) * ~self.class_mask[0][None, :]].reshape((embeddings_0.size(0), -1))
anchor_negative_dists_1 = embeddings_1[self.tensor_eye[1].repeat((embeddings_1.size(0), 1)) * ~self.class_mask[1][None, :]].reshape((embeddings_1.size(0), -1))
anchor_negative_dists_2 = embeddings_2[self.tensor_eye[2].repeat((embeddings_2.size(0), 1)) * ~self.class_mask[2][None, :]].reshape((embeddings_2.size(0), -1))
anchor_negative_dists_3 = embeddings_3[self.tensor_eye[3].repeat((embeddings_3.size(0), 1)) * ~self.class_mask[3][None, :]].reshape((embeddings_3.size(0), -1))
anchor_negative_dists_4 = embeddings_4[self.tensor_eye[4].repeat((embeddings_4.size(0), 1)) * ~self.class_mask[4][None, :]].reshape((embeddings_4.size(0), -1))
anchor_negative_dists_5 = embeddings_5[self.tensor_eye[5].repeat((embeddings_5.size(0), 1)) * ~self.class_mask[5][None, :]].reshape((embeddings_5.size(0), -1))
anchor_negative_dists_6 = embeddings_6[self.tensor_eye[6].repeat((embeddings_6.size(0), 1)) * ~self.class_mask[6][None, :]].reshape((embeddings_6.size(0), -1))
pos_sim_loss_0 = torch.clamp(anchor_similar_dists_0 - anchor_positive_dists_0 + self.margin1, min=0.0).reshape((embeddings_0.size(0), -1))
pos_sim_loss_1 = torch.clamp(anchor_similar_dists_1 - anchor_positive_dists_1 + self.margin1, min=0.0).reshape((embeddings_1.size(0), -1))
pos_sim_loss_2 = torch.clamp(anchor_similar_dists_2 - anchor_positive_dists_2 + self.margin1, min=0.0).reshape((embeddings_2.size(0), -1))
pos_sim_loss_3 = torch.clamp(anchor_similar_dists_3 - anchor_positive_dists_3 + self.margin1, min=0.0).reshape((embeddings_3.size(0), -1))
pos_sim_loss_4 = torch.clamp(anchor_similar_dists_4 - anchor_positive_dists_4 + self.margin1, min=0.0).reshape((embeddings_4.size(0), -1))
pos_sim_loss_5 = torch.clamp(anchor_similar_dists_5 - anchor_positive_dists_5 + self.margin1, min=0.0).reshape((embeddings_5.size(0), -1))
pos_sim_loss_6 = torch.clamp(anchor_similar_dists_6 - anchor_positive_dists_6 + self.margin1, min=0.0).reshape((embeddings_6.size(0), -1))
sim_neg_loss_0 = torch.clamp(anchor_negative_dists_0[:, None, :] - anchor_similar_dists_0[:, :, None] + self.margin2, min=0.0).reshape((embeddings_0.size(0), anchor_similar_dists_0.size(-1), -1))
sim_neg_loss_1 = torch.clamp(anchor_negative_dists_1[:, None, :] - anchor_similar_dists_1[:, :, None] + self.margin2, min=0.0).reshape((embeddings_1.size(0), anchor_similar_dists_1.size(-1), -1))
sim_neg_loss_2 = torch.clamp(anchor_negative_dists_2[:, None, :] - anchor_similar_dists_2[:, :, None] + self.margin2, min=0.0).reshape((embeddings_2.size(0), anchor_similar_dists_2.size(-1), -1))
sim_neg_loss_3 = torch.clamp(anchor_negative_dists_3[:, None, :] - anchor_similar_dists_3[:, :, None] + self.margin2, min=0.0).reshape((embeddings_3.size(0), anchor_similar_dists_3.size(-1), -1))
sim_neg_loss_4 = torch.clamp(anchor_negative_dists_4[:, None, :] - anchor_similar_dists_4[:, :, None] + self.margin2, min=0.0).reshape((embeddings_4.size(0), anchor_similar_dists_4.size(-1), -1))
sim_neg_loss_5 = torch.clamp(anchor_negative_dists_5[:, None, :] - anchor_similar_dists_5[:, :, None] + self.margin2, min=0.0).reshape((embeddings_5.size(0), anchor_similar_dists_5.size(-1), -1))
sim_neg_loss_6 = torch.clamp(anchor_negative_dists_6[:, None, :] - anchor_similar_dists_6[:, :, None] + self.margin2, min=0.0).reshape((embeddings_6.size(0), anchor_similar_dists_6.size(-1), -1))
quadruple_loss_0 = pos_sim_loss_0[:, :, None] + sim_neg_loss_0
quadruple_loss_1 = pos_sim_loss_1[:, :, None] + sim_neg_loss_1
quadruple_loss_2 = pos_sim_loss_2[:, :, None] + sim_neg_loss_2
quadruple_loss_3 = pos_sim_loss_3[:, :, None] + sim_neg_loss_3
quadruple_loss_4 = pos_sim_loss_4[:, :, None] + sim_neg_loss_4
quadruple_loss_5 = pos_sim_loss_5[:, :, None] + sim_neg_loss_5
quadruple_loss_6 = pos_sim_loss_6[:, :, None] + sim_neg_loss_6
num_positive_0 = (quadruple_loss_0 > self.eps).float().sum(1).sum(1)
num_positive_1 = (quadruple_loss_1 > self.eps).float().sum(1).sum(1)
num_positive_2 = (quadruple_loss_2 > self.eps).float().sum(1).sum(1)
num_positive_3 = (quadruple_loss_3 > self.eps).float().sum(1).sum(1)
num_positive_4 = (quadruple_loss_4 > self.eps).float().sum(1).sum(1)
num_positive_5 = (quadruple_loss_5 > self.eps).float().sum(1).sum(1)
num_positive_6 = (quadruple_loss_6 > self.eps).float().sum(1).sum(1)
quadruple_0 = quadruple_loss_0.sum(1).sum(1) / (num_positive_0 + self.eps)
quadruple_1 = quadruple_loss_1.sum(1).sum(1) / (num_positive_1 + self.eps)
quadruple_2 = quadruple_loss_2.sum(1).sum(1) / (num_positive_2 + self.eps)
quadruple_3 = quadruple_loss_3.sum(1).sum(1) / (num_positive_3 + self.eps)
quadruple_4 = quadruple_loss_4.sum(1).sum(1) / (num_positive_4 + self.eps)
quadruple_5 = quadruple_loss_5.sum(1).sum(1) / (num_positive_5 + self.eps)
quadruple_6 = quadruple_loss_6.sum(1).sum(1) / (num_positive_6 + self.eps)
return quadruple_0.sum() + quadruple_1.sum() + quadruple_2.sum() + quadruple_3.sum() + quadruple_4.sum() + quadruple_5.sum() + quadruple_6.sum()
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
if net_name == "resnet" and fewshot_method != "FEAT":
from torchvision.models import resnet18
model = resnet18(weights='IMAGENET1K_V1')
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.AdaptiveAvgPool1d(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 == "relation":
model.use_flatten = False
model.train()
model = model.to(device)
# ---------- #
# For validation -------------------------------------------------------------------- #
from easyfsl.samplers import TaskSampler
n_way = num_classes
n_shot = 2
if use_multi:
n_query = 5
else:
n_query = 20
n_validation_tasks = 250
val_set = utilities.val_set(valid_list, 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,
)
# ----------------------------------------------------------------------------------- #
# Create FewShotClassifier on top of the model -------------------------------------- #
from easyfsl.methods import FewShotClassifier
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)
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" # Pre trainewd weights for FEAT
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()
# ----------------------------------------------------------------------------------- #
# For training -------------------------------------------------------------------- #
n_shot_tr = 2
if use_multi:
n_query_tr = 2
else:
n_query_tr = 30
n_tasks_per_epoch = 250
train_set = utilities.val_set(train_list, 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,
)
# --------------------------------------------------------------------------------- #
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)
if use_triplets == 1:
criterion = tripletloss(margin=margin).to(device)
elif use_triplets == 2:
# mask for similar/negative classes for each class
classes_mask = torch.tensor([[0, 1, 0, 0, 0, 1, 1], [1, 0, 1, 1, 1, 0, 0], [0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1, 0]]).bool()
criterion = quadrupleloss3(class_mask=classes_mask, margin1=margin, margin2=margin2).to(device)
else:
if fewshot_method == "matchingnetworks":
criterion = torch.nn.NLLLoss().to(device)
elif fewshot_method == "simpleshot" or fewshot_method == "bdcspn" or fewshot_method == "laplacianshot":
criterion = torch.nn.BCELoss().to(device)
elif fewshot_method == "relation":
criterion = torch.nn.MSELoss().to(device)
else:
criterion = torch.nn.CrossEntropyLoss().to(device)
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 e in range(epochs):
print("Epoch: %d/%d" % (e, epochs))
average_loss = training_epoch(few_shot_classifier, train_loader, train_optimizer, fewshot_method)
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\n" % validation_accuracy)
log.flush()
if fewshot_method != "FEAT":
torch.save(model.state_dict(), outputWeightspath + str(e) + '.h5')
if fewshot_method == "relation" or fewshot_method == "bdcspn" or fewshot_method == "FEAT" or fewshot_method == "laplacianshot" or fewshot_method == "matchingnetworks":
torch.save(few_shot_classifier.state_dict(), outputWeightspath + str(e) + '_fs.h5')
few_shot_classifier.train()
log.close()
log_loss.close()
print("Done")