forked from anthonysicilia/MDL-By-MetaLearning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatasets.py
288 lines (238 loc) · 9.76 KB
/
datasets.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import nibabel as nib
import numpy as np
import torch
from torchvision.transforms import ToPILImage, ToTensor
import torchvision.transforms.functional as augmentor
def tensorize(*args):
return tuple(torch.Tensor(arg).unsqueeze(0) for arg in args)
def augment(x1, y, x2=None):
# NOTE: method expects numpy float arrays
# to_pil_image makes assumptions based on input when mode = None
# i.e. it should infer that mode = 'F'
# manually setting mode to 'F' in this function
# print(x.shape); exit()
# NOTE: accepts np.ndarray of size H x W x C
# x.shape = 64x64
# torch implicitly expands last dim as below:
# elif pic.ndim == 2:
# if 2D image, add channel dimension (HWC)
# pic = np.expand_dims(pic, 2)
# BUT!!!!!!!
# if x was a tensor this would be different:
# elif pic.ndimension() == 2:
# if 2D image, add channel dimension (CHW)
# pic = pic.unsqueeze(0)
angle = np.random.uniform(-180, 180)
scale = np.random.uniform(.8, 1.2)
shear = np.random.uniform(-30, 30)
# import matplotlib.pyplot as plt
# fig, ax = plt.subplots(1, 3)
# ax.flat[0].imshow(x)
x1 = augmentor.to_pil_image(x1, mode='F')
if x2 is not None:
x2 = augmentor.to_pil_image(x2, mode='F')
# ax.flat[1].imshow(x)
y = augmentor.to_pil_image(y, mode='F')
x1 = augmentor.affine(x1,
angle=angle, translate=(0,0), shear=shear, scale=scale)
if x2 is not None:
x2 = augmentor.affine(x2,
angle=angle, translate=(0,0), shear=shear, scale=scale)
y = augmentor.affine(y,
angle=angle, translate=(0,0), shear=shear, scale=scale)
x1 = augmentor.to_tensor(x1).float()
if x2 is not None:
x2 = augmentor.to_tensor(x2).float()
# ax.flat[2].imshow(x.squeeze(0))
# plt.show(); exit()
y = augmentor.to_tensor(y).float()
y = (y > 0).float()
# returns 1xHxW
if x2 is not None:
return x1,y,x2
else:
return x1,y
class Mixed(torch.utils.data.Dataset):
def __init__(self, t1_paths, fl_paths, label_paths,
augment=False, num_fl=None, agg=False):
# NOTE: if dataloader does not shuffle
# and batch size is kept to 5, then
# each batch equates to a single subject
t1_paths_order = [f.strip().split('/')[-1].split('_')[0]
for p in t1_paths for f in open(p) for _ in range(5)]
fl_paths_order = [f.strip().split('/')[-1].split('_')[0]
for p in fl_paths for f in open(p) for _ in range(5)]
lb_paths_order = [f.strip().split('/')[-1].split('_')[0]
for p in label_paths for f in open(p) for _ in range(5)]
assert all([a == b and b == c for a,b,c in zip(t1_paths_order,
fl_paths_order, lb_paths_order)])
# should match up so labels match, but will be randomized
# so no inherent order to track
self.order = None
t1_paths = [f.strip() for p in t1_paths
for f in open(p).readlines()]
fl_paths = [f.strip() for p in fl_paths
for f in open(p).readlines()]
label_paths = [f.strip() for p in label_paths
for f in open(p).readlines()]
t1_paths = [(p,l) for p,l in zip(t1_paths, label_paths)]
fl_paths = [(p,l) for p,l in zip(fl_paths, label_paths)]
# random subsamples of flair dataset to sim. missing data
np.random.shuffle(fl_paths)
if num_fl is not None:
fl_paths = fl_paths[:num_fl]
self.augment = augment
self.t1_data = []
self.fl_data = []
for t1 in t1_paths:
T1 = self._extract(t1[0])
Y = self._extract(t1[1])[:, :,
(24,25,26,27,28)]
for sl in range(Y.shape[2]):
self.t1_data.append({
'data' : T1[:, :, sl],
'label' : Y[:, :, sl]})
for fl in fl_paths:
FL = self._extract(fl[0])
Y = self._extract(fl[1])[:, :,
(24,25,26,27,28)]
for sl in range(Y.shape[2]):
self.fl_data.append({
'data' : FL[:, :, sl],
'label' : Y[:, :, sl]})
self.agg = agg
if self.agg:
# randomly upsample flair here (for agg)
base_len = len(self.fl_data)
while len(self.fl_data) != len(self.t1_data):
index = int(np.random.randint(0, base_len))
self.fl_data += [self.fl_data[index]]
self.data = [x for x in (self.t1_data + self.fl_data)]
self.kind = ['T1' for _ in self.t1_data] + ['FL' for _ in self.fl_data]
self.epoch_len = len(self.data)
else:
self.epoch_len = len(self.t1_data)
def __len__(self):
return self.epoch_len
def _extract(self, f):
x = nib.load(f).get_fdata()
return x.astype('float32')
def __getitem__(self, index):
if self.agg:
x = self.data[index]['data']
y = self.data[index]['label']
if self.augment:
x, y = augment(x, y)
else:
x, y = tensorize(x, y)
return {'data' : x, 'label' : y, 'kind' : self.kind[index]}
else:
t1 = self.t1_data[index]['data']
t1_label = self.t1_data[index]['label']
# randomly upsample flair here (for meta)
index = int(np.random.randint(0, len(self.fl_data)))
fl = self.fl_data[index]['data']
fl_label = self.fl_data[index]['label']
if self.augment:
t1, t1_label = augment(t1, t1_label)
fl, fl_label = augment(fl, fl_label)
else:
t1,t1_label,fl,fl_label = \
tensorize(t1,t1_label,fl,fl_label)
return {'T1' : t1, 'FL' : fl, 'T1_label' : t1_label,
'FL_label' : fl_label}
class Paired(torch.utils.data.Dataset):
def __init__(self, t1_paths, fl_paths, label_paths,
augment = False):
# NOTE: if dataloader does not shuffle
# and batch size is kept to 5, then
# each batch equates to a single subject
t1_paths_order = [f.strip().split('/')[-1].split('_')[0]
for p in t1_paths for f in open(p) for _ in range(5)]
fl_paths_order = [f.strip().split('/')[-1].split('_')[0]
for p in fl_paths for f in open(p) for _ in range(5)]
lb_paths_order = [f.strip().split('/')[-1].split('_')[0]
for p in label_paths for f in open(p) for _ in range(5)]
assert all([a == b and b == c for a,b,c in zip(t1_paths_order,
fl_paths_order, lb_paths_order)])
self.order = lb_paths_order
t1_paths = [f.strip() for p in t1_paths
for f in open(p).readlines()]
fl_paths = [f.strip() for p in fl_paths
for f in open(p).readlines()]
label_paths = [f.strip() for p in label_paths
for f in open(p).readlines()]
paths = zip(t1_paths, fl_paths, label_paths)
self.augment = augment
self.data = []
for t1_f, fl_f, label_f in paths:
T1 = self._extract(t1_f)
FL = self._extract(fl_f)
Y = self._extract(label_f)[:, :,
(24,25,26,27,28)]
for sl in range(Y.shape[2]):
self.data.append({
'T1' : T1[:, :, sl],
'FL' : FL[:, :, sl],
'label' : Y[:, :, sl]})
def __len__(self):
return len(self.data)
def _extract(self, f):
x = nib.load(f).get_fdata()
return x.astype('float32')
def __getitem__(self, index):
t1 = self.data[index]['T1']
fl = self.data[index]['FL']
y = self.data[index]['label']
if self.augment:
t1,y,fl = augment(t1,y,fl)
else:
t1,y,fl = tensorize(t1,y,fl)
return {'T1' : t1, 'FL' : fl, 'label' : y,
'subject' : self.order[index]}
class Aggregate(torch.utils.data.Dataset):
def __init__(self, data_paths, label_paths, augment = False):
# NOTE: if dataloader does not shuffle
# and batch size is kept to 5, then
# each batch equates to a single subject
data_paths_order = [f.strip().split('/')[-1].split('_')[0]
for p in data_paths for f in open(p) for _ in range(5)]
lb_paths_order = [f.strip().split('/')[-1].split('_')[0]
for p in label_paths for f in open(p) for _ in range(5)]
assert all([a == b for a,b in zip(
data_paths_order, lb_paths_order)])
self.order = lb_paths_order
data_paths = [f.strip() for p in data_paths
for f in open(p).readlines()]
label_paths = [f.strip() for p in label_paths
for f in open(p).readlines()]
paths = zip(data_paths, label_paths)
self.augment = augment
self.data = []
for data_f, label_f in paths:
X = self._extract(data_f)
Y = self._extract(label_f)[:, :,
(24,25,26,27,28)]
for sl in range(Y.shape[2]):
self.data.append({
'data' : X[:, :, sl],
'label' : Y[:, :, sl]})
def __len__(self):
return len(self.data)
def _extract(self, f):
x = nib.load(f).get_fdata()
return x.astype('float32')
def __getitem__(self, index):
x = self.data[index]['data']
y = self.data[index]['label']
if self.augment:
x,y = augment(x,y)
else:
x,y = tensorize(x,y)
return {'data' : x, 'label' : y,
'subject' : self.order[index]}
DATASETS = {
'aggregate' : Aggregate,
'paired' : Paired,
'mixed' : Mixed
}