-
Notifications
You must be signed in to change notification settings - Fork 0
/
task_generator.py
220 lines (180 loc) · 8.76 KB
/
task_generator.py
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
# code is based on https://github.com/katerakelly/pytorch-maml
import torchvision
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torch
from torch.utils.data import DataLoader,Dataset
import random
import os
from PIL import Image
import numpy as np
from torch.utils.data.sampler import Sampler
import transforms as T
class Rotate(object):
def __init__(self, angle):
self.angle = angle
def __call__(self, x, mode="reflect"):
x = x.rotate(self.angle)
return x
def mini_imagenet_folders():
train_folder = './datas/miniImagenet/train'
test_folder = './datas/miniImagenet/test'
val_folder = './datas/miniImagenet/val'
metatrain_folders = [os.path.join(train_folder, label) \
for label in os.listdir(train_folder) \
if os.path.isdir(os.path.join(train_folder, label)) \
]
metatest_folders = [os.path.join(test_folder, label) \
for label in os.listdir(test_folder) \
if os.path.isdir(os.path.join(test_folder, label)) \
]
metaval_folders = [os.path.join(val_folder, label) \
for label in os.listdir(val_folder) \
if os.path.isdir(os.path.join(val_folder, label)) \
]
random.seed(1)
random.shuffle(metatrain_folders)
random.shuffle(metatest_folders)
random.shuffle(metaval_folders)
return metatrain_folders,metaval_folders,metatest_folders
class MiniImagenetTask(object):
def __init__(self, character_folders, num_classes, train_num,test_num):
self.character_folders = character_folders
self.num_classes = num_classes
self.train_num = train_num
self.test_num = test_num
class_folders = random.sample(self.character_folders,self.num_classes)
labels = np.array(range(len(class_folders)))
labels = dict(zip(class_folders, labels))
samples = dict()
self.train_roots = []
self.test_roots = []
for c in class_folders:
temp = [os.path.join(c, x) for x in os.listdir(c)]
samples[c] = random.sample(temp, len(temp))
random.shuffle(samples[c])
self.train_roots += samples[c][:train_num]
self.test_roots += samples[c][train_num:train_num+test_num]
self.train_labels = [labels[self.get_class(x)] for x in self.train_roots]
self.test_labels = [labels[self.get_class(x)] for x in self.test_roots]
def get_class(self, sample):
return os.path.join(*sample.split('/')[:-1])
class FewShotDataset(Dataset):
def __init__(self, task, split='train', transform_84=None, transform_64=None, transform_48=None,target_transform=None):
self.transform_84 = transform_84 # Torch operations on the input image
self.transform_64 = transform_64
self.transform_48 = transform_48
self.target_transform = target_transform
self.task = task
self.split = split
self.image_roots = self.task.train_roots if self.split == 'train' else self.task.test_roots
self.labels = self.task.train_labels if self.split == 'train' else self.task.test_labels
def __len__(self):
return len(self.image_roots)
def __getitem__(self, idx):
raise NotImplementedError("This is an abstract class. Subclass this class for your particular dataset.")
class MiniImagenet(FewShotDataset):
def __init__(self, *args, **kwargs):
super(MiniImagenet, self).__init__(*args, **kwargs)
def __getitem__(self, idx):
image_root = self.image_roots[idx]
image_84 = Image.open(image_root).convert('RGB')
image_64 = image_84.resize((64,64))
image_48 = image_84.resize((48,48))
if self.transform_84 is not None:
image_84 = self.transform_84(image_84)
image_64 = self.transform_64(image_64)
image_48 = self.transform_48(image_48)
label = self.labels[idx]
if self.target_transform is not None:
label = self.target_transform(label)
return image_84, image_64, image_48, label
class ClassBalancedSampler(Sampler):
''' Samples 'num_inst' examples each from 'num_cl' pools
of examples of size 'num_per_class' '''
def __init__(self, num_cl, num_inst,shuffle=True):
self.num_cl = num_cl
self.num_inst = num_inst
self.shuffle = shuffle
def __iter__(self):
# return a single list of indices, assuming that items will be grouped by class
if self.shuffle:
batches = [[i+j*self.num_inst for i in torch.randperm(self.num_inst)] for j in range(self.num_cl)]
else:
batches = [[i+j*self.num_inst for i in range(self.num_inst)] for j in range(self.num_cl)]
batches = [[batches[j][i] for j in range(self.num_cl)] for i in range(self.num_inst)]
if self.shuffle:
random.shuffle(batches)
for sublist in batches:
random.shuffle(sublist)
batches = [item for sublist in batches for item in sublist]
return iter(batches)
def __len__(self):
return 1
class ClassBalancedSamplerOld(Sampler):
''' Samples 'num_inst' examples each from 'num_cl' pools
of examples of size 'num_per_class' '''
def __init__(self, num_per_class, num_cl, num_inst,shuffle=True):
self.num_per_class = num_per_class
self.num_cl = num_cl
self.num_inst = num_inst
self.shuffle = shuffle
def __iter__(self):
# return a single list of indices, assuming that items will be grouped by class
if self.shuffle:
batch = [[i+j*self.num_inst for i in torch.randperm(self.num_inst)[:self.num_per_class]] for j in range(self.num_cl)]
else:
batch = [[i+j*self.num_inst for i in range(self.num_inst)[:self.num_per_class]] for j in range(self.num_cl)]
batch = [item for sublist in batch for item in sublist]
if self.shuffle:
random.shuffle(batch)
return iter(batch)
def __len__(self):
return 1
def get_mini_imagenet_data_loader(task, num_per_class=1, split='train',shuffle = False,train_query_argue=False, train_support_argue=False):
normalize = transforms.Normalize(mean=[0.92206, 0.92206, 0.92206], std=[0.08426, 0.08426, 0.08426])
Arguementation_84 = T.Compose([
T.RandomCrop(84, padding=8),
T.RandomHorizontalFlip(),
T.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4),
T.ToTensor(),
normalize,
T.RandomErasing(0.5)
])
Arguementation_64 = T.Compose([
T.RandomCrop(64, padding=6),
T.RandomHorizontalFlip(),
T.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4),
T.ToTensor(),
normalize,
T.RandomErasing(0.5)
])
Arguementation_48 = T.Compose([
T.RandomCrop(48, padding=4),
T.RandomHorizontalFlip(),
T.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4),
T.ToTensor(),
normalize,
T.RandomErasing(0.5)
])
support_Arguementation = T.Compose([
T.RandomHorizontalFlip(),
T.ToTensor(),
normalize,
])
if split == 'train' :
if train_support_argue == False:
dataset = MiniImagenet(task,split=split,transform_84=transforms.Compose([transforms.ToTensor(),normalize]), transform_64=transforms.Compose([transforms.ToTensor(),normalize]), transform_48=transforms.Compose([transforms.ToTensor(),normalize]))
sampler = ClassBalancedSamplerOld(num_per_class,task.num_classes, task.train_num,shuffle=shuffle)
else:
dataset = MiniImagenet(task,split=split,transform_84=support_Arguementation, transform_64=support_Arguementation, transform_48=support_Arguementation)
sampler = ClassBalancedSamplerOld(num_per_class,task.num_classes, task.train_num,shuffle=shuffle)
else:
if train_query_argue == False:
dataset = MiniImagenet(task,split=split,transform_84=transforms.Compose([transforms.ToTensor(),normalize]), transform_64=transforms.Compose([transforms.ToTensor(),normalize]), transform_48=transforms.Compose([transforms.ToTensor(),normalize]))
sampler = ClassBalancedSampler(task.num_classes, task.test_num,shuffle=shuffle)
else:
dataset = MiniImagenet(task,split=split,transform_84=Arguementation_84, transform_64=Arguementation_64, transform_48=Arguementation_48)
sampler = ClassBalancedSampler(task.num_classes, task.test_num,shuffle=shuffle)
loader = DataLoader(dataset, batch_size=num_per_class*task.num_classes, sampler=sampler)
return loader