File size: 7,390 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 | 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.
"""
@abstractmethod
def __getitem__(self, item: int) -> Tuple[Tensor, int]:
raise NotImplementedError(
"All PyTorch datasets, including few-shot datasets, need a __getitem__ method."
)
@abstractmethod
def __len__(self) -> int:
raise NotImplementedError(
"All PyTorch datasets, including few-shot datasets, need a __len__ method."
)
@abstractmethod
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)
|