-
Notifications
You must be signed in to change notification settings - Fork 1
/
data_LIDC_IDRI.py
404 lines (347 loc) · 17.9 KB
/
data_LIDC_IDRI.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
# %%
import os
import random
import torch
import torch.utils.data
from torchvision.datasets.folder import pil_loader
import torchvision.transforms as transforms
import torch.nn.functional as F
import numpy as np
from PIL import Image
import skimage.measure as skm
import skimage.io as skio
import skimage.util as sku
import pandas as pd
import sklearn.preprocessing as skp
import matplotlib.pyplot as plt
from glob import glob
from scipy.stats import entropy
# os.environ["MKL_NUM_THREADS"] = "6"
# os.environ["NUMEXPR_NUM_THREADS"] = "6"
# os.environ["OMP_NUM_THREADS"] = "6"
# torch.set_num_threads(6)
# %%
class RandomRotation:
"""Rotate by one of the given angles."""
def __init__(self, angles):
self.angles = angles
def __call__(self, x):
angle = random.choice(self.angles)
return transforms.functional.rotate(x, angle)
class LIDC_IDRI_EXPL_pseudo(torch.utils.data.Dataset):
def __init__(self, df, base_path, split, transform_split=None, num_labels=0, gt_sample_ids=None, stats=None, verbose=False, agg=True, transform=None, soft_labels=False):
assert split in {"train", "val", "test"}
self.base_path = base_path
self.split = "val" if split == "test" else split
self.img_shape = (224, 224) # (32, 32) #(128, 128)
self.verbose = verbose
self.soft_labels = soft_labels
if transform_split is None:
transform_split = split
self.num_labels = num_labels
use_entropy = False
header = [
'img_id',
'gt_subtlety', 'gt_internalStructure', 'gt_calcification', 'gt_sphericity', 'gt_margin', 'gt_lobulation', 'gt_spiculation', 'gt_texture', 'gt_malignancy',
'pd_subtlety', 'pd_internalStructure', 'pd_calcification', 'pd_sphericity', 'pd_margin', 'pd_lobulation', 'pd_spiculation', 'pd_texture', 'pd_malignancy',
'conf_subtlety', 'conf_internalStructure', 'conf_calcification', 'conf_sphericity', 'conf_margin', 'conf_lobulation', 'conf_spiculation', 'conf_texture', 'conf_malignancy',
]
self.header = header
# df = df[header]
df = df[list(filter(lambda c: '_' in c, df.columns.to_list()))] # filter out non-feature columns
if use_entropy:
df['entropy'] = df.iloc[:, df.columns.get_loc('prob_subtlety_1') : df.columns.get_loc('prob_subtlety_1') + len(list(filter(lambda c: 'prob_' in c, df.columns.values)))].apply(lambda row: entropy(row), axis=1)
self.threshold_label = df['entropy'][df['entropy'].to_numpy().argsort()[::-1][self.num_labels]]
self.gt_sample_ids = df['img_id'][df.entropy > self.threshold_label].to_list() if gt_sample_ids is None else gt_sample_ids
else:
self.threshold_label = df['conf_malignancy'][df['conf_malignancy'].argsort()[self.num_labels]]
self.gt_sample_ids = df['img_id'][df.conf_malignancy < self.threshold_label].to_list() if gt_sample_ids is None else gt_sample_ids
if self.num_labels == 0:
df = df[df.conf_malignancy > 0.9] # filter out low confidence
if agg:
# append a nid column
df['nid'] = df.apply(lambda row: '_'.join(row.img_id.split('_')[:-2] + row.img_id.split('_')[-1:]), axis=1)
df_median = df.groupby('nid').median()
for ftr in header[10:]:
df[ftr] = df['nid'].map(df_median[ftr])
# df = df.loc[df['malignancy'] != 3] # nodules of median radiologists' score 3 were removed
# df_median = df_median.loc[df_median['malignancy'] != 3] # nodules of median radiologists' score 3 were removed
# scenes = json.load(fd)["scenes"]
# scans = pl.query(pl.Scan).filter(
# pl.Scan.slice_thickness < 3
# ) # "CT scans with slice thickness larger than or equal to 3 mm were also excluded"
if agg:
self.img_ids, self.img_class_ids, self.img_ftr_ids, self.scenes, self.fnames = \
self.prepare_scenes(df, df_median)
else:
self.img_ids, self.img_class_ids, self.img_ftr_ids, self.scenes, self.fnames = \
self.prepare_scenes(df)
if transform is not None:
self.transform = transform
else:
# if split == "train":
# transform_list = [
# transforms.Resize((32, 32)),
# transforms.RandomHorizontalFlip(),
# transforms.RandomVerticalFlip(),
# # RandomRotation(angles=[0, 90, 180, 270]),
# transforms.GaussianBlur(kernel_size=1),
# ]
# else:
# transform_list = [
# transforms.Resize((32, 32)),
# ]
if transform_split == "train":
transform_list = [
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.RandomVerticalFlip(),
RandomRotation(angles=[0, 90, 180, 270]),
# transforms.RandomPerspective(distortion_scale=0.1, p=0.5),
transforms.GaussianBlur(kernel_size=1),
]
else:
transform_list = [
transforms.Resize(256, interpolation=3),
transforms.CenterCrop(224),
]
'''
inverse_modes_mapping = {
0: InterpolationMode.NEAREST,
2: InterpolationMode.BILINEAR,
3: InterpolationMode.BICUBIC,
4: InterpolationMode.BOX,
5: InterpolationMode.HAMMING,
1: InterpolationMode.LANCZOS,
}
'''
transform_list.append(transforms.ToTensor())
if stats is not None:
transform_list.append(transforms.Normalize(*stats))
self.transform = transforms.Compose(transform_list)
self.n_classes = len(np.unique(self.img_class_ids, axis=0))
def prepare_scenes(self, df, df_median=None):
# pids = [] # patient id
img_ids = [] # nod id
scenes = [] # nods
img_class_ids = []
img_ftr_ids = []
fnames = []
df_header = df.columns.values
for ann in df.itertuples(index=False):
# print(ann)
if df_median is not None:
img_class_id = 1 if ann.gt_malignancy > 0 else 0
img_class_id_pseudo = 1 if ann.pd_malignancy > 0 else 0
else:
img_class_id = np.round(ann.gt_malignancy)
img_class_id_pseudo = np.round(ann.pd_malignancy)
imgs_per_ann = glob(f"{os.path.join(self.base_path, 'Image', self.split, str(img_class_id), ann.img_id)}*.png")
fnames += imgs_per_ann
img_ids += [ann.img_id] * len(imgs_per_ann)
if self.soft_labels:
img_class_id_pseudo = [ann.prob_malignancy_0, ann.prob_malignancy_1]
img_ftr_id = {}
for ftr in self.header[10:18]:
ftr = ftr.replace('pd_', '')
img_ftr_id[ftr] = ann[df.columns.get_loc(f'prob_{ftr}_1') : df.columns.get_loc(f'prob_{ftr}_1') + len(list(filter(lambda c: f'prob_{ftr}_' in c, df_header)))]
else:
# add feature labels
img_ftr_id = {df_header[i].replace('pd_', ''):np.round(ann[i]) for i in range(df.columns.get_loc('pd_subtlety'), df.columns.get_loc('pd_subtlety')+8)}
img_class_id_pseudo = img_class_id if ann.img_id in self.gt_sample_ids else img_class_id_pseudo # use gt label for seed samples
img_class_ids += [img_class_id_pseudo] * len(imgs_per_ann)
img_ftr_ids += [img_ftr_id] * len(imgs_per_ann)
return img_ids, img_class_ids, img_ftr_ids, scenes, fnames
def __getitem__(self, idx):
image_id = self.img_ids[idx]
# image = self.get_image(image_id)
image = pil_loader(self.fnames[idx])
# TODO: sofar only dummy
img_expl = torch.tensor(skio.imread(self.fnames[idx].replace('Image', 'Mask')))
if self.transform is not None:
image = self.transform(image) # in range [0., 1.]
# image = (image - 0.5) * 2.0 # Rescale to [-1, 1].
# img_expl = self.transform_img_expl(img_expl)
if image.size(0) == 1:
image = image.repeat(3, 1, 1)
# objects = self.scenes[idx]
# table_expl = self.gt_table_expls[idx]
img_class_id = self.img_class_ids[idx]
img_ftr_id = self.img_ftr_ids[idx]
# remove objects presence indicator from gt table
# objects = objects[:, 1:]
return image, img_class_id, img_ftr_id, image_id, img_expl, idx
def __len__(self):
return len(self.fnames)
class LIDC_IDRI_EXPL(torch.utils.data.Dataset):
def __init__(self, base_path, split, transform_split=None, stats=None, verbose=False, agg=True, transform=None):
assert split in {"train", "val", "test"}
self.base_path = base_path
self.split = "val" if split == "test" else split
self.img_shape = (224, 224) # (32, 32) #(128, 128)
self.verbose = verbose
if transform_split is None:
transform_split = split
header = ['id', 'scan_id', 'subtlety', 'internalStructure', 'calcification', 'sphericity', 'margin', 'lobulation', 'spiculation', 'texture', 'malignancy']
self.header = header
df = pd.read_csv(f'{self.base_path}/meta_{self.split}.csv', index_col=0, converters={'coords': lambda x: list(map(float, x[1:-1].split(',')))})
# df[header] = df[header].astype(int)
if agg:
# append a nid column
df['nid'] = df.apply(lambda row: '_'.join(row.name.split('_')[:-2] + row.name.split('_')[-1:]), axis=1)
df_median = df.groupby('nid').median()
for ftr in header[2:]:
df[ftr] = df['nid'].map(df_median[ftr])
# df = df.loc[df['malignancy'] != 3] # nodules of median radiologists' score 3 were removed
df_median = df_median.loc[df_median['malignancy'] != 3] # nodules of median radiologists' score 3 were removed
# scenes = json.load(fd)["scenes"]
# scans = pl.query(pl.Scan).filter(
# pl.Scan.slice_thickness < 3
# ) # "CT scans with slice thickness larger than or equal to 3 mm were also excluded"
if agg:
self.img_ids, self.img_class_ids, self.img_ftr_ids, self.scenes, self.fnames = \
self.prepare_scenes(df, df_median)
else:
self.img_ids, self.img_class_ids, self.img_ftr_ids, self.scenes, self.fnames = \
self.prepare_scenes(df)
if transform is not None:
self.transform = transform
else:
# if split == "train":
# transform_list = [
# transforms.Resize((32, 32)),
# transforms.RandomHorizontalFlip(),
# transforms.RandomVerticalFlip(),
# # RandomRotation(angles=[0, 90, 180, 270]),
# transforms.GaussianBlur(kernel_size=1),
# ]
# else:
# transform_list = [
# transforms.Resize((32, 32)),
# ]
if transform_split == "train":
transform_list = [
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.RandomVerticalFlip(),
RandomRotation(angles=[0, 90, 180, 270]),
# transforms.RandomPerspective(distortion_scale=0.1, p=0.5),
transforms.GaussianBlur(kernel_size=1),
]
else:
transform_list = [
transforms.Resize(256, interpolation=3),
transforms.CenterCrop(224),
]
'''
inverse_modes_mapping = {
0: InterpolationMode.NEAREST,
2: InterpolationMode.BILINEAR,
3: InterpolationMode.BICUBIC,
4: InterpolationMode.BOX,
5: InterpolationMode.HAMMING,
1: InterpolationMode.LANCZOS,
}
'''
transform_list.append(transforms.ToTensor())
if stats is not None:
transform_list.append(transforms.Normalize(*stats))
self.transform = transforms.Compose(transform_list)
self.n_classes = len(np.unique(self.img_class_ids, axis=0))
def prepare_scenes(self, df, df_median=None):
# pids = [] # patient id
img_ids = [] # nod id
scenes = [] # nods
img_class_ids = []
img_ftr_ids = []
fnames = []
for ann in df.itertuples():
# print(ann)
if df_median is not None:
img_class_id = 0 if ann.malignancy < 3 else 1 # 0(unlikely):1-2, 1(suspicious):3-5
else:
img_class_id = np.round(ann.malignancy) - 1
imgs_per_ann = glob(f"{os.path.join(self.base_path, 'Image', self.split, str(img_class_id), ann.Index)}*.png")
fnames += imgs_per_ann
img_ids += [ann.Index] * len(imgs_per_ann)
img_class_ids += [img_class_id] * len(imgs_per_ann)
# add feature labels
img_ftr_id = {self.header[i-1]:np.round(ann[i]) - 1 for i in range(3, len(self.header))}
# img_ftr_id = {
# "subtlety": 0 if ann.subtlety < 3 else 1, # 0(unlikely):1-2, 1(suspicious):3-5
# "internalStructure": 1 if ann.internalStructure == 1 else 0,
# "calcification": 1 if ann.calcification == 4 else 0,
# "sphericity": 0 if ann.sphericity > 4 else 1,
# "margin": 0 if ann.margin > 4 else 1,
# "lobulation": 0 if ann.lobulation < 3 else 1,
# "spiculation": 0 if ann.spiculation < 3 else 1,
# "texture": 0 if ann.texture > 4 else 1,
# }
img_ftr_ids += [img_ftr_id] * len(imgs_per_ann)
return img_ids, img_class_ids, img_ftr_ids, scenes, fnames
def __getitem__(self, idx):
image_id = self.img_ids[idx]
# image = self.get_image(image_id)
image = pil_loader(self.fnames[idx])
# TODO: sofar only dummy
img_expl = torch.tensor(skio.imread(self.fnames[idx].replace('Image', 'Mask')))
if self.transform is not None:
image = self.transform(image) # in range [0., 1.]
# image = (image - 0.5) * 2.0 # Rescale to [-1, 1].
# img_expl = self.transform_img_expl(img_expl)
if image.size(0) == 1:
image = image.repeat(3, 1, 1)
# objects = self.scenes[idx]
# table_expl = self.gt_table_expls[idx]
img_class_id = self.img_class_ids[idx]
img_ftr_id = self.img_ftr_ids[idx]
# remove objects presence indicator from gt table
# objects = objects[:, 1:]
return image, img_class_id, img_ftr_id, image_id, img_expl, idx
def __len__(self):
return len(self.fnames)
class LIDC_IDRI_FTR(torch.utils.data.Dataset):
def __init__(self, base_path, split, agg=False):
assert split in {"train", "val", "test"}
self.base_path = base_path
self.split = "val" if split == "test" else split
header = ['id', 'scan_id', 'subtlety', 'internalStructure', 'calcification', 'sphericity', 'margin', 'lobulation', 'spiculation', 'texture', 'malignancy']
dfs = {}
for folder in os.listdir(base_path):
dfs[folder] = pd.read_csv(f'{base_path}/{folder}/meta_{folder}.csv', index_col=0, converters={'coords': lambda x: list(map(float, x[1:-1].split(',')))})
dfs[folder][header] = dfs[folder][header].astype(int)
if agg:
# append a nid column
dfs[folder]['nid'] = dfs[folder].apply(lambda row: '_'.join(row.name.split('_')[:-2] + row.name.split('_')[-1:]), axis=1)
dfs[folder] = dfs[folder].groupby('nid').median()
dfs[folder] = dfs[folder].loc[dfs[folder]['malignancy'] != 3] # nodules of median radiologists' score 3 were removed
# df = pd.read_csv(f'{self.base_path}/{self.split}/meta_{self.split}.csv', index_col=0, converters={'coords': lambda x: list(map(float, x[1:-1].split(',')))})
# df[header] = df[header].astype(int)
# df = dfs[self.split]
if agg:
for df in dfs.values():
# df['subtlety'] = np.where(df['subtlety'] < 3, 0, 1)
# df['internalStructure'] = np.where(df['internalStructure'] == 1, 1, 0)
# df['calcification'] = np.where(df['calcification'] == 4, 1, 0)
# df['sphericity'] = np.where(df['sphericity'] > 4, 0, 1)
# df['margin'] = np.where(df['margin'] > 4, 0, 1)
# df['lobulation'] = np.where(df['lobulation'] < 3, 0, 1)
# df['spiculation'] = np.where(df['spiculation'] < 3, 0, 1)
# df['texture'] = np.where(df['texture'] > 4, 0, 1)
labels = np.where(dfs[self.split]['malignancy'] < 3, 0, 1) # 0(unlikely):1-2, 1(suspicious):3-5
# labels = F.one_hot(torch.as_tensor(labels - 1, dtype=torch.int64), num_classes=5).float()
else:
labels = np.round(dfs[self.split]['malignancy']) - 1
scaler = skp.StandardScaler()
dfs['train'][header[2:-1]] = scaler.fit_transform(dfs['train'][header[2:-1]])
inputs = dfs[self.split][header[2:-1]].to_numpy()
if self.split != 'train':
inputs = scaler.transform(inputs)
self.inputs = torch.FloatTensor(inputs)
self.labels = torch.FloatTensor(labels)
self.n_classes = len(np.unique(labels, axis=0))
self.ftr_len = self.inputs.size(-1)
def __getitem__(self, idx):
return self.inputs[idx], self.labels[idx]
def __len__(self):
return len(self.labels)