-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpneumonia_new_loader.py
218 lines (168 loc) · 7.1 KB
/
pneumonia_new_loader.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
#!/usr/bin/env python
# coding: utf-8
# # Pneumonia Balanced Databunches
import collections
import pickle
from fastai.vision import *
import os
import pandas as pd
def default_transforms():
tfms = get_transforms(do_flip=True, flip_vert=False,
max_zoom=1.3, max_lighting=0.3)
return tfms
def get_labels(file_path, known_classes=('normal', 'bacteria', 'virus'), default='normal'):
"""get labels from filepath"""
base = file_path.stem
for k in known_classes:
if k in base:
return k
return default
def filter_files(file_path, selected=('bacteria', 'virus')):
"""filter files based on filepath"""
base = file_path.stem
for s in selected:
if s in base:
return True
return False
def stringify(x):
return [str(y) for y in x]
def get_rel_fn(x, base):
return [y.relative_to(base) for y in x]
def list_to_ll(path, subset):
"""Converts list of features with label to fastai imagelist"""
df = pd.DataFrame(subset, columns = ['path', 'label'])
data = ImageList.from_df(df, path=path).split_none().label_from_df()
#print(type(data), type(data.train))
return data.train
def get_labellist_contents(path, filter_func=None, label_func=None):
ll = ImageList.from_folder(path)
if filter_func is not None:ll = ll.filter_by_func(filter_func)
ll = ll.split_none()
if label_func is None:
ll = ll.label_from_folder()
else:
ll = ll.label_from_func(label_func)
return ll.train
def get_dir_contents(path, subdir='train', **kwargs):
ll = get_labellist_contents(path/subdir, **kwargs)
all_items = list(zip(get_rel_fn(ll.items, path), stringify(ll.y)))
grouped_items = {}
keys = set([y for x, y in all_items])
for k in keys:
entries = [(x, y) for x, y in all_items if y == k]
random.shuffle(entries)
grouped_items[k] = entries
#print([(k, len(grouped_items[k])) for k in keys])
return grouped_items
def get_sampled_data(path, n_samples=100, balance_valid=True, **kwargs):
"""generates new data set after sampling and scaling"""
contents_tr = get_dir_contents(path, subdir='train', **kwargs)
new_train = []
for k, v in contents_tr.items():
n = len(v)
if n >= n_samples:
new_train += v[:n_samples]
else:
times = n_samples//n
mod = n_samples%n
new_train += v * times
if mod > 0:
new_train += v[:mod]
contents_tst = get_dir_contents(path, subdir='test', **kwargs)
new_test, new_valid = [], []
if balance_valid:
min_len = np.min([len(v) for v in contents_tst.values()])
max_valid = min(min_len//2, n_samples)
else:
max_valid = n_samples
for k, v in contents_tst.items():
n = min(len(v) // 2, max_valid)
new_test += v[:n]
v = v[n:]
n = min(len(v), max_valid)
new_valid += v[:n]
random.shuffle(new_train)
random.shuffle(new_test)
random.shuffle(new_valid)
return new_train, new_test, new_valid
def get_xray_databunch(path, scale=1, size=None, tfms=None, cache=None, bs=64,
include_test=False, double_valid=False, **kwargs):
if tfms is None:
tfms = default_transforms()
p_name = Path(f'{cache}.pkl')
if cache is not None and p_name.exists():
with open(p_name, 'rb') as f:
new_train, new_test, new_valid = pickle.load(f)
else:
new_train, new_test, new_valid = get_sampled_data(path, **kwargs)
if cache is not None:
with open(p_name, 'wb') as f:
pickle.dump([new_train, new_test, new_valid], f)
if scale > 1: # Duplicate entries, if requested
new_train = new_train * scale
random.shuffle(new_train)
ll_tr = list_to_ll(path, new_train)
if include_test:
ll_val = list_to_ll(path, new_valid)
ils = ItemLists(path=path, train=ll_tr, valid=ll_val)
db = ils.transform(tfms, size=size).databunch(num_workers=7, bs=bs).normalize(imagenet_stats)
ll_tst = list_to_ll(path, new_test)
ils = ItemLists(path=path, train=ll_tr, valid=ll_tst)
db_tst = ils.transform(tfms, size=size).databunch(num_workers=7, bs=bs).normalize(imagenet_stats)
return db, db_tst
else:
if double_valid:
ll_val = list_to_ll(path, new_valid+new_test)
else:
ll_val = list_to_ll(path, new_valid)
ils = ItemLists(path=path, train=ll_tr, valid=ll_val)
db = ils.transform(tfms, size=size).databunch(num_workers=7, bs=bs).normalize(imagenet_stats)
return db
def get_db(path, kind, n_samples=100, **kwargs):
assert kind in ('np', 'nvb', 'vb')
cname = f'{kind}_{n_samples}'
if kind == 'np':
db = get_xray_databunch(path, label_func=None, n_samples=n_samples, cache=cname, **kwargs)
elif kind == 'nvb':
db = get_xray_databunch(path, label_func=get_labels, n_samples=n_samples, cache=cname, **kwargs)
elif kind == 'vb':
db = get_xray_databunch(path, label_func=get_labels, filter_func=filter_files,
n_samples=n_samples, cache=cname, **kwargs)
return db
# def get_xray_databunch(path, scale=1, size=None, tfms=None, cache=None, bs=None, **kwargs):
# if tfms is None:
# tfms = default_transforms()
# p_name = Path(f'{cache}.pkl')
# if cache is not None and p_name.exists():
# with open(p_name, 'rb') as f:
# new_train, new_test, new_valid = pickle.load(f)
# else:
# new_train, new_test, new_valid = get_sampled_data(path, **kwargs)
# if cache is not None:
# with open(p_name, 'wb') as f:
# pickle.dump([new_train, new_test, new_valid], f)
# if scale > 1: # Duplicate entries, if requested
# new_train = new_train * scale
# random.shuffle(new_train)
# ll_tr = list_to_ll(path, new_train)
# ll_val = list_to_ll(path, new_valid)
# ll_tst = list_to_ll(path, new_test)
# ils = ItemLists(path=path, train=ll_tr, valid=ll_val); ils
# if bs is None:
# db = ils.transform(tfms, size=size).databunch(num_workers=7)
# else:
# db = ils.transform(tfms, size=size).databunch(num_workers=7, bs=bs)
# return db
# def get_db(path, kind, n_samples=100, scale=1, size=448, tfms=None, bs=None):
# assert kind in ('np', 'nvb', 'vb')
# cname = f'{kind}_{n_samples}'
# if kind == 'np':
# db = get_xray_databunch(path, label_func=None,
# scale=scale, size=size, n_samples=n_samples, tfms=tfms, cache=cname, bs=bs)
# elif kind == 'nvb':
# db = get_xray_databunch(path, label_func=get_labels,
# scale=scale, size=size, n_samples=n_samples, tfms=tfms, cache=cname, bs=bs)
# elif kind == 'vb':
# db = get_xray_databunch(path, label_func=get_labels, filter_func=filter_files,
# scale=scale, size=size, n_samples=n_samples, tfms=tfms, cache=cname, bs=bs)
# return db