Download source_code/utilities.py from FelixOtt/gnss_few-shot_learning: direct link, hf CLI and curl.
- Browser
- Download file 7.39 kB
-
https://huggingface.co/datasets/FelixOtt/gnss_few-shot_learning/resolve/main/source_code/utilities.py
- Command line
-
hf download hf://datasets/FelixOtt/gnss_few-shot_learning/source_code/utilities.py
-
curl -L -o utilities.py https://huggingface.co/datasets/FelixOtt/gnss_few-shot_learning/resolve/main/source_code/utilities.py
7.39 kB
| import numpy as np | |
| from glob import glob | |
| import json | |
| def get_training_data(dataset, rseed=0, reduce_to_binary=False): | |
| # Splits each class in the dataset into 80/20 for training/validation and returns a list of training and validation files aswell as their labels | |
| np.random.seed(rseed) | |
| np.random.shuffle(dataset) | |
| x_files = np.array([x[0] for x in dataset]) | |
| y_classes = np.array([int(x[1]) for x in dataset]) | |
| un_classes = np.unique(y_classes) | |
| classes_map = {x: i for i, x in enumerate(un_classes)} | |
| train_data_files = [] | |
| valid_data_files = [] | |
| train_classes = [] | |
| valid_classes = [] | |
| for c in un_classes: | |
| cm = classes_map[c] | |
| cinds = np.where(y_classes == c)[0] | |
| tinds = int(0.8 * len(cinds)) | |
| train_data_files.extend(x_files[cinds[:tinds]]) | |
| valid_data_files.extend(x_files[cinds[tinds:]]) | |
| train_classes.extend([cm] * tinds) | |
| valid_classes.extend([cm] * (len(cinds) - tinds)) | |
| if reduce_to_binary: | |
| train_classes = np.array(train_classes) | |
| train_classes[train_classes <= 2] = 0 | |
| train_classes[train_classes > 2] = 1 | |
| train_classes = train_classes.tolist() | |
| valid_classes = np.array(valid_classes) | |
| valid_classes[valid_classes <= 2] = 0 | |
| valid_classes[valid_classes > 2] = 1 | |
| valid_classes = valid_classes.tolist() | |
| un_classes = np.array([0, 1]) | |
| return train_data_files, valid_data_files, train_classes, valid_classes, len(un_classes) | |
| def load_test(cfile, cclass, time_size, norm_vals=None, use_norm=False, norm_type=1): | |
| cur_x_data = np.load(cfile) | |
| if use_norm: | |
| if norm_type == 1: | |
| cur_x_data -= norm_vals[0] | |
| elif norm_type == 2: | |
| cur_x_data = 10 ** (cur_x_data / 10.0) | |
| x_data = [cur_x_data, cur_x_data[::-1], cur_x_data[:, ::-1], cur_x_data[::-1, ::-1]] | |
| y_data = np.array([cclass, cclass, cclass, cclass]).astype("int") | |
| return np.asarray(x_data).astype("float32"), y_data | |
| def gen_data_batch_test(file_list, file_classes, time_size, batchSize, norm=None, norm_type=1): | |
| # Expands each sample by horizontal and vertical flipping and yields them | |
| if norm != None: | |
| norm_vals = norm | |
| unorm = True | |
| else: | |
| unorm = False | |
| cur_batch_size = 0 | |
| cur_batch_x = [] | |
| cur_batch_y = [] | |
| cur_batch_inds = [] | |
| for ifl, fl in enumerate(file_list): | |
| data_x, data_y = load_test(fl, file_classes[ifl], time_size, norm_vals=norm_vals, use_norm=unorm, norm_type=norm_type) | |
| if cur_batch_size == batchSize: | |
| yield np.repeat(np.asarray(cur_batch_x).astype("float32")[:, np.newaxis, :, :], 3, 1), np.asarray(cur_batch_y).astype("int"), np.asarray(cur_batch_inds).astype("int") | |
| # Prep next batch | |
| cur_batch_x = [] | |
| cur_batch_y = [] | |
| cur_batch_x.extend(data_x) | |
| cur_batch_y.extend(data_y) | |
| cur_batch_inds = [ifl] * len(data_x) | |
| cur_batch_size = len(data_x) | |
| # ------------- # | |
| elif cur_batch_size + len(data_x) > batchSize: | |
| cur_batch_x.extend(data_x[:batchSize - cur_batch_size]) | |
| cur_batch_y.extend(data_y[:batchSize - cur_batch_size]) | |
| cur_batch_inds.extend([ifl] * (batchSize - cur_batch_size)) | |
| yield np.repeat(np.asarray(cur_batch_x).astype("float32")[:, np.newaxis, :, :], 3, 1), np.asarray(cur_batch_y).astype("int"), np.asarray(cur_batch_inds).astype("int") | |
| # Prep next batch | |
| cur_batch_x = [] | |
| cur_batch_y = [] | |
| cur_batch_x.extend(data_x[batchSize - cur_batch_size:]) | |
| cur_batch_y.extend(data_y[batchSize - cur_batch_size:]) | |
| cur_batch_size = len(cur_batch_x) | |
| cur_batch_inds = [ifl] * cur_batch_size | |
| # ------------- # | |
| else: | |
| cur_batch_x.extend(data_x) | |
| cur_batch_y.extend(data_y) | |
| cur_batch_inds.extend([ifl] * len(data_x)) | |
| cur_batch_size += len(data_x) | |
| if cur_batch_size > 0: | |
| yield np.repeat(np.asarray(cur_batch_x).astype("float32")[:, np.newaxis, :, :], 3, 1), np.asarray(cur_batch_y).astype("int"), np.asarray(cur_batch_inds).astype("int") | |
| def get_support_data(sup_list, time_size, norm=None, norm_type=1): | |
| if norm != None: | |
| norm_vals = norm | |
| use_norm = True | |
| else: | |
| use_norm = False | |
| sup_x = [] | |
| sup_y = [] | |
| for isu, su in enumerate(sup_list[0]): | |
| cur_x_data = np.load(su) | |
| if use_norm: | |
| if norm_type == 1: | |
| cur_x_data -= norm_vals[0] | |
| elif norm_type == 2: | |
| cur_x_data = 10 ** (cur_x_data / 10.0) | |
| sup_x.append(cur_x_data) | |
| sup_y.append(sup_list[1][isu]) | |
| return np.repeat(np.asarray(sup_x).astype("float32")[:, np.newaxis, :, :], 3, 1), np.asarray(sup_y).astype("int") | |
| # For FeShot Evaluation | |
| from abc import abstractmethod | |
| from typing import List, Tuple | |
| import torch | |
| from torch import Tensor | |
| from torch.utils.data import Dataset | |
| class FewShotDataset(Dataset): | |
| """ | |
| Abstract class for all datasets used in a context of Few-Shot Learning. | |
| The tools we use in few-shot learning, especially TaskSampler, expect an | |
| implementation of FewShotDataset. | |
| Compared to PyTorch's Dataset, FewShotDataset forces a method get_labels. | |
| This exposes the list of all items labels and therefore allows to sample | |
| items depending on their label. | |
| """ | |
| def __getitem__(self, item: int) -> Tuple[Tensor, int]: | |
| raise NotImplementedError( | |
| "All PyTorch datasets, including few-shot datasets, need a __getitem__ method." | |
| ) | |
| def __len__(self) -> int: | |
| raise NotImplementedError( | |
| "All PyTorch datasets, including few-shot datasets, need a __len__ method." | |
| ) | |
| def get_labels(self) -> List[int]: | |
| raise NotImplementedError( | |
| "Implementations of FewShotDataset need a get_labels method." | |
| ) | |
| class val_set(FewShotDataset): | |
| def __init__(self, file_list, label_list, time_size, norm=None, norm_type=1): | |
| self.norm_vals = norm | |
| if norm_type == 1: | |
| self.use_norm = True | |
| else: | |
| self.use_norm = False | |
| self.norm_type = norm_type | |
| self.images = file_list | |
| self.labels = label_list | |
| self.class_names = [str(x) for x in np.unique(self.labels)] | |
| self.time_size = time_size | |
| def __getitem__(self, item: int): | |
| cfile = self.images[item][0] | |
| cur_aug = int(self.images[item][1]) | |
| cur_x_data = np.load(cfile) | |
| if cur_aug == 1: | |
| cur_x_data = cur_x_data[::-1] | |
| elif cur_aug == 2: | |
| cur_x_data = cur_x_data[:, ::-1] | |
| elif cur_aug == 3: | |
| cur_x_data = cur_x_data[::-1, ::-1] | |
| if self.use_norm: | |
| if self.norm_type == 1: | |
| cur_x_data -= self.norm_vals[0] | |
| elif self.norm_type == 2: | |
| cur_x_data = 10 ** (cur_x_data / 10.0) | |
| return torch.from_numpy(np.repeat(cur_x_data[np.newaxis, :, :], 3, 0).astype("float32")), self.labels[item] | |
| def __len__(self) -> int: | |
| return len(self.labels) | |
| def get_labels(self) -> List[int]: | |
| return self.labels | |
| def number_of_classes(self): | |
| return len(self.class_names) | |