-
Notifications
You must be signed in to change notification settings - Fork 0
/
FSLTask.py
228 lines (185 loc) · 7.97 KB
/
FSLTask.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
219
220
221
222
223
224
225
226
227
228
import os
import pickle
import numpy as np
import torch
import math
# from tqdm import tqdm
# ========================================================
# Usefull paths
_datasetFeaturesFiles = {
"cub_RN18": "./checkpoints/cub/RN18/cub.plk",
}
_cacheDir = "./"
_maxRuns = 10000
_min_examples = -1
# ========================================================
# Module internal functions and variables
_randStates = None
_rsCfg = None
def _load_pickle(file):
with open(file, 'rb') as f:
data = pickle.load(f)
labels = [np.full(shape=len(data[key]), fill_value=key)
for key in data]
data = [features for key in data for features in data[key]]
dataset = dict()
dataset['data'] = torch.FloatTensor(np.stack(data, axis=0))
dataset['labels'] = torch.LongTensor(np.concatenate(labels))
return dataset
# =========================================================
# Callable variables and functions from outside the module
data = None
labels = None
dsName = None
def convert_prob_to_samples(prob, q_shot):
prob = prob * q_shot
for i in range(len(prob)):
if sum(np.round(prob[i])) > q_shot:
while sum(np.round(prob[i])) != q_shot:
idx = 0
for j in range(len(prob[i])):
frac, whole = math.modf(prob[i, j])
if j == 0:
frac_clos = abs(frac - 0.5)
else:
if abs(frac - 0.5) < frac_clos:
idx = j
frac_clos = abs(frac - 0.5)
prob[i, idx] = np.floor(prob[i, idx])
prob[i] = np.round(prob[i])
elif sum(np.round(prob[i])) < q_shot:
while sum(np.round(prob[i])) != q_shot:
idx = 0
for j in range(len(prob[i])):
frac, whole = math.modf(prob[i, j])
if j == 0:
frac_clos = abs(frac - 0.5)
else:
if abs(frac - 0.5) < frac_clos:
idx = j
frac_clos = abs(frac - 0.5)
prob[i, idx] = np.ceil(prob[i, idx])
prob[i] = np.round(prob[i])
else:
prob[i] = np.round(prob[i])
return prob.astype(int)
def get_dirichlet_query_dist(alpha, n_tasks, n_ways, q_shots):
alpha = np.full(n_ways, alpha)
prob_dist = np.random.dirichlet(alpha, n_tasks)
return convert_prob_to_samples(prob=prob_dist, q_shot=q_shots)
def loadDataSet(dsname):
if dsname not in _datasetFeaturesFiles:
raise NameError('Unknwown dataset: {}'.format(dsname))
global dsName, data, labels, _randStates, _rsCfg, _min_examples
dsName = dsname
_randStates = None
_rsCfg = None
# Loading data from files on computer
# home = expanduser("~")
dataset = _load_pickle(_datasetFeaturesFiles[dsname])
# Computing the number of items per class in the dataset
_min_examples = dataset["labels"].shape[0]
for i in range(dataset["labels"].shape[0]):
if torch.where(dataset["labels"] == dataset["labels"][i])[0].shape[0] > 0:
_min_examples = min(_min_examples, torch.where(
dataset["labels"] == dataset["labels"][i])[0].shape[0])
print("Guaranteed number of items per class: {:d}\n".format(_min_examples))
# Generating data tensors
data = torch.zeros((0, _min_examples, dataset["data"].shape[1]))
labels = dataset["labels"].clone()
while labels.shape[0] > 0:
indices = torch.where(dataset["labels"] == labels[0])[0]
data = torch.cat([data, dataset["data"][indices, :]
[:_min_examples].view(1, _min_examples, -1)], dim=0)
indices = torch.where(labels != labels[0])[0]
labels = labels[indices]
print("Total of {:d} classes, {:d} elements each, with dimension {:d}\n".format(
data.shape[0], data.shape[1], data.shape[2]))
def GenerateRun(iRun, cfg, regenRState=False):
global _randStates, data, _min_examples
if not regenRState:
np.random.set_state(_randStates[iRun])
classes = np.random.permutation(np.arange(data.shape[0]))[:cfg["ways"]]
indices = np.arange(_min_examples)
support = []
support_label = []
query = []
query_label = []
n_feat = data.shape[-1]
n_samples_per_cls = data.shape[1]
if cfg['balanced'] is True:
for i in range(cfg['ways']):
shuffle_indices = np.random.permutation(indices)
samples = data[classes[i], shuffle_indices, :][:cfg['shot']+cfg['queries']]
support.append(samples[:cfg['shot']])
support_label += [i] * cfg['shot']
query.append(samples[cfg['shot']:])
query_label += [i] * cfg['queries']
else:
alpha = 2
num_query_samples = get_dirichlet_query_dist(alpha, 1, cfg['ways'], cfg['ways'] * cfg['queries'])[0]
while not ((cfg['shot']+num_query_samples)<n_samples_per_cls).all():
num_query_samples = get_dirichlet_query_dist(alpha, 1, cfg['ways'], cfg['ways'] * cfg['queries'])[0]
for i in range(cfg['ways']):
shuffle_indices = np.random.permutation(indices)
samples = data[classes[i], shuffle_indices, :][:cfg['shot']+num_query_samples[i]]
support.append(samples[:cfg['shot']])
support_label += [i] * cfg['shot']
query.append(samples[cfg['shot']:])
query_label += [i] * num_query_samples[i]
support = torch.cat(support).view(cfg['ways'], cfg['shot'], -1).permute(1, 0, 2).reshape(-1, n_feat)
query = torch.cat(query)
shuffle_ind = torch.randperm(query.shape[0])
query = query[shuffle_ind]
query_label = torch.tensor(query_label)[shuffle_ind].tolist()
dataset = torch.cat([support, query], dim=0)
label = support_label + query_label
label = torch.tensor(label)
label[:cfg['shot']*cfg['ways']] = label[:cfg['shot']*cfg['ways']].view(cfg['ways'], cfg['shot']).permute(1,0).reshape(-1)
return dataset, label
def ClassesInRun(iRun, n_ways):
global _randStates, data
np.random.set_state(_randStates[iRun])
classes = np.random.permutation(np.arange(data.shape[0]))[:n_ways]
return classes
def setRandomStates(cfg):
global _randStates, _rsCfg
if _rsCfg == cfg:
return
rsFile = os.path.join(_cacheDir, "RandStates_{}_s{}_q{}_w{}_r{}".format(
dsName, cfg['shot'], cfg['queries'], cfg['ways'], cfg['runs']))
if not os.path.exists(rsFile):
print("{} does not exist, regenerating it...".format(rsFile))
#np.random.seed(0)
_randStates = []
for iRun in range(cfg['runs']):
np.random.seed(iRun)
_randStates.append(np.random.get_state())
#GenerateRun(iRun, cfg, regenRState=True, generate=False)
torch.save(_randStates, rsFile)
else:
print("reloading random states from file....")
_randStates = torch.load(rsFile)
_rsCfg = cfg
def GenerateRunSet(cfg=None):
global dataset, label, _maxRuns
if cfg is None:
cfg = {"shot": 1, "ways": 5, "queries": 15, "runs":_maxRuns}
start = 0
end = cfg['runs']
setRandomStates(cfg)
print("generating task from {} to {}".format(start, end))
dataset = torch.zeros((end-start, cfg['ways'] * (cfg['shot']+cfg['queries']), data.shape[2]))
label = torch.zeros((end-start, cfg['ways'] * (cfg['shot']+cfg['queries']))).type(torch.int64)
for iRun in range(end-start):
dataset[iRun], label[iRun] = GenerateRun(iRun, cfg)
return dataset, label
# define a main code to test this module
if __name__ == "__main__":
print("Testing Task loader for Few Shot Learning")
loadDataSet('miniimagenet')
cfg = {"shot": 1, "ways": 5, "queries": 15, "runs": 10}
setRandomStates(cfg)
run10, label = GenerateRun(10, cfg)
print("First call:", run10[:2, :2, :2])
print(ds.size())