-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreateTrainingSplits.py
221 lines (164 loc) · 6.93 KB
/
createTrainingSplits.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
# A script to create train/test splits from the total amos dataset
import pandas as pd
import numpy as np
import os
import pickle as pkl
import shutil
local = False
if local:
root_folder = "/Users/katecevora/Documents/PhD/data/AMOS_3D"
else:
root_folder = "/rds/general/user/kc2322/home/data/AMOS_3D"
input_folder = os.path.join(root_folder, "nnUNet_raw/Dataset200_AMOS")
output_folder = os.path.join(root_folder, "nnUNet_raw")
input_images_folder = os.path.join(input_folder, "imagesTr")
input_labels_folder = os.path.join(input_folder, "labelsTr")
splits_folder = os.path.join(root_folder, "splits")
meta_data_path = os.path.join(root_folder, "labeled_data_meta_0000_0599.csv")
def saveDatasetInfo():
# open metadata
df = pd.read_csv(meta_data_path)
# List the images in the training dataset
images = os.listdir(input_images_folder)
amos_id = df["amos_id"].values
sex_mf = df["Patient's Sex"].values
patients = []
genders = []
patients_tr = []
# Change the patient ID to be a 4-character string with zero padding where necessary
for id in amos_id:
id = str(id)
if len(id) == 1:
id = "000" + id
elif len(id) == 2:
id = "00" + id
elif len(id) == 3:
id = "0" + id
patients.append(id)
patients = np.array(patients)
for image in images:
if image.endswith(".nii.gz"):
# Find the gender of the subject from the metadata
id = image[5:9]
if id in patients:
x = np.where(patients == id)[0][0]
patients_tr.append(id)
if sex_mf[x] == "M":
genders.append(0)
elif sex_mf[x] == "F":
genders.append(1)
genders = np.array(genders)
patients_tr = np.array(patients_tr)
# Save lists
info = {"patients": patients_tr,
"genders": genders}
f = open(os.path.join(input_folder, "info.pkl"), "wb")
pkl.dump(info, f)
f.close()
def generate_folds():
f = open(os.path.join(input_folder, "info.pkl"), "rb")
info = pkl.load(f)
f.close()
patients = np.array(info["patients"])
genders = np.array(info["genders"]) # male = 0, female = 1
# split into male and female IDs
ids_m = patients[genders == 0]
ids_f = patients[genders == 1]
# randomly shuffle indices
np.random.shuffle(ids_m)
np.random.shuffle(ids_f)
block_size = np.floor(ids_f.shape[0] / 9)
dataset_size = int(block_size * 8)
print("Dataset size: {}".format(dataset_size))
print("Test set size per fold: {}".format(block_size * 2))
# create 9 training blocks overall (these will form 5 folds)
blocks_f = []
blocks_m = []
for i in range(9):
blocks_f.append(ids_f[int(i * block_size):int((i + 1) * block_size)])
blocks_m.append(ids_m[int(i * block_size):int((i + 1) * block_size)])
# create 5 training folds for three datasets
ts = np.concatenate((blocks_f[0], blocks_m[0]), axis=0)
tr1_f = np.concatenate(blocks_f[1:5], axis=0)
tr1_m = np.concatenate(blocks_m[1:5], axis=0)
tr1 = np.concatenate((tr1_f, tr1_m), axis=0)
tr2 = np.concatenate(blocks_f[1:9], axis=0)
tr3 = np.concatenate(blocks_m[1:9], axis=0)
set_1_ids = {"train": tr1, "test": ts}
set_2_ids = {"train": tr2, "test": ts}
set_3_ids = {"train": tr3, "test": ts}
#f = open(os.path.join(splits_folder, "fold_0.pkl"), "wb")
#pkl.dump([set_1_ids, set_2_ids, set_3_ids], f)
#f.close()
print(tr1.shape, tr2.shape, tr3.shape, ts.shape)
for f in range(1, 4):
ts = np.concatenate((blocks_f[f], blocks_m[f]), axis=0)
tr1_f = np.concatenate((blocks_f[0:f] + blocks_f[f+1:5]), axis=0)
tr1_m = np.concatenate((blocks_m[0:f] + blocks_m[f+1:5]), axis=0)
tr1 = np.concatenate((tr1_f, tr1_m), axis=0)
tr2 = np.concatenate((blocks_f[0:f] + blocks_f[f+1:9]), axis=0)
tr3 = np.concatenate((blocks_m[0:f] + blocks_m[f+1:9]), axis=0)
set_1_ids = {"train": tr1, "test": ts}
set_2_ids = {"train": tr2, "test": ts}
set_3_ids = {"train": tr3, "test": ts}
#f = open(os.path.join(splits_folder, "fold_{}.pkl".format(f)), "wb")
#pkl.dump([set_1_ids, set_2_ids, set_3_ids], f)
#f.close()
print(tr1.shape, tr2.shape, tr3.shape, ts.shape)
ts = np.concatenate((blocks_f[4], blocks_m[4]), axis=0)
tr1_f = np.concatenate(blocks_f[:4], axis=0)
tr1_m = np.concatenate(blocks_m[:4], axis=0)
tr1 = np.concatenate((tr1_f, tr1_m), axis=0)
tr2 = np.concatenate((blocks_f[0:4] + blocks_f[5:9]), axis=0)
tr3 = np.concatenate((blocks_m[0:4] + blocks_m[5:9]), axis=0)
set_1_ids = {"train": tr1, "test": ts}
set_2_ids = {"train": tr2, "test": ts}
set_3_ids = {"train": tr3, "test": ts}
#f = open(os.path.join(splits_folder, "fold_4.pkl"), "wb")
#pkl.dump([set_1_ids, set_2_ids, set_3_ids], f)
#f.close()
def copy_images(dataset_name, ids_tr, ids_ts):
os.mkdir(os.path.join(output_folder, dataset_name))
output_imagesTr = os.path.join(output_folder, dataset_name, "imagesTr")
output_labelsTr = os.path.join(output_folder, dataset_name, "labelsTr")
output_imagesTs = os.path.join(output_folder, dataset_name, "imagesTs")
output_labelsTs = os.path.join(output_folder, dataset_name, "labelsTs")
os.mkdir(output_imagesTr)
os.mkdir(output_labelsTr)
os.mkdir(output_imagesTs)
os.mkdir(output_labelsTs)
# copy over the files from Training Set
for case in list(ids_tr):
print("Case {}".format(case))
img_name = "amos_" + case + "_0000.nii.gz"
lab_name = "amos_" + case + ".nii.gz"
# Copy across images
shutil.copyfile(os.path.join(input_images_folder, img_name), os.path.join(output_imagesTr, img_name))
# Copy across labels
shutil.copyfile(os.path.join(input_labels_folder, lab_name), os.path.join(output_labelsTr, lab_name))
# copy over the files from Test Set
for case in list(ids_ts):
img_name = "amos_" + case + "_0000.nii.gz"
lab_name = "amos_" + case + ".nii.gz"
# Copy across images
shutil.copyfile(os.path.join(input_images_folder, img_name), os.path.join(output_imagesTs, img_name))
# Copy across labels
shutil.copyfile(os.path.join(input_labels_folder, lab_name), os.path.join(output_labelsTs, lab_name))
def sort():
# Sort the case IDs according to the sets
folds = [0, 1, 2, 3, 4]
for fold in folds:
f = open(os.path.join(splits_folder, "fold_{}.pkl".format(fold)), "rb")
ids = pkl.load(f)
f.close()
for j in range(3):
ids_tr = ids[j]["train"]
ids_ts = ids[j]["test"]
name = "Dataset{}0{}".format(5+fold, j) + "_Fold{}".format(fold)
print("Working on Set {}....".format(name))
copy_images(name, ids_tr, ids_ts)
def main():
#saveDatasetInfo()
generate_folds()
if __name__ == "__main__":
main()