|
a |
|
b/srscn.py |
|
|
1 |
# -*- coding: utf-8 -*- |
|
|
2 |
|
|
|
3 |
|
|
|
4 |
from __future__ import print_function, division, absolute_import, unicode_literals |
|
|
5 |
from core import util |
|
|
6 |
from core import ACNN_pos as ACNN |
|
|
7 |
from core import image_util_pos as image_util |
|
|
8 |
from core import unet_pos as unet |
|
|
9 |
import numpy as np |
|
|
10 |
import click |
|
|
11 |
import os |
|
|
12 |
import logging |
|
|
13 |
from datetime import datetime |
|
|
14 |
|
|
|
15 |
t = datetime.now().strftime('%Y-%m-%d_%H-%M-%S') |
|
|
16 |
|
|
|
17 |
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" |
|
|
18 |
os.environ['CUDA_VISIBLE_DEVICES'] = '2' |
|
|
19 |
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' |
|
|
20 |
|
|
|
21 |
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) |
|
|
22 |
|
|
|
23 |
|
|
|
24 |
@click.command(context_settings=CONTEXT_SETTINGS) |
|
|
25 |
@click.option('--saliency', default='SRSCN', help='Key word for this running time') |
|
|
26 |
@click.option('--run_times', default=1, type=click.IntRange(min=1, clamp=True), help='network training times') |
|
|
27 |
@click.option('--time', default=t, help='the current time or the time when the model to restore was trained') |
|
|
28 |
@click.option('--trainer_learning_rate', default=0.001, type=click.FloatRange(min=1e-8, clamp=True), |
|
|
29 |
help='network learning rate') |
|
|
30 |
@click.option('--train_validation_batch_size', default=5, type=click.IntRange(min=1), |
|
|
31 |
help='the number of validation cases') |
|
|
32 |
@click.option('--test_n_files', default=15, type=click.IntRange(min=1), help='the number of test cases') |
|
|
33 |
@click.option('--train_original_search_path', default='../dataset/train_original/*.nii.gz', |
|
|
34 |
help='search pattern to find all original training data and label images') |
|
|
35 |
@click.option('--train_search_path', default='../dataset/train_data_2d/*.png', |
|
|
36 |
help='search pattern to find all training data and label images') |
|
|
37 |
@click.option('--train_data_suffix', default='_img.png', help='suffix pattern for the training data images') |
|
|
38 |
@click.option('--train_label_suffix', default='_lab.png', help='suffix pattern for the training label images') |
|
|
39 |
@click.option('--train_shuffle_data', default=True, type=bool, |
|
|
40 |
help='whether the order of training files should be randomized after each epoch') |
|
|
41 |
@click.option('--train_crop_patch', default=True, type=bool, |
|
|
42 |
help='whether patches of a certain size need to be cropped for training') |
|
|
43 |
@click.option('--train_patch_size', default=(-1, -1, -1), |
|
|
44 |
type=(click.IntRange(min=-1), click.IntRange(min=-1), click.IntRange(min=-1)), |
|
|
45 |
help='size of the training patches') |
|
|
46 |
@click.option('--train_channels', default=1, type=click.IntRange(min=1), help='number of training data channels') |
|
|
47 |
@click.option('--train_n_class', default=4, type=click.IntRange(min=1), |
|
|
48 |
help='number of training label classes, including the background') |
|
|
49 |
@click.option('--train_contain_foreground', default=False, type=bool, |
|
|
50 |
help='if the training patches should contain foreground') |
|
|
51 |
@click.option('--train_label_intensity', default=(0, 88, 200, 244), multiple=True, |
|
|
52 |
type=click.IntRange(min=0), help='list of intensities of the training ground truths') |
|
|
53 |
@click.option('--net_layers', default=5, type=click.IntRange(min=2), |
|
|
54 |
help='number of convolutional blocks in the down-sampling path') |
|
|
55 |
@click.option('--net_features_root', default=32, type=click.IntRange(min=1), |
|
|
56 |
help='number of features of the first convolution layer') |
|
|
57 |
@click.option('--net_cost_name', default=u'exponential_logarithmic', |
|
|
58 |
type=click.Choice(["cross_entropy", "weighted_cross_entropy", "dice_loss", |
|
|
59 |
"generalized_dice_loss", "cross_entropy+dice_loss", |
|
|
60 |
"weighted_cross_entropy+generalized_dice_loss", |
|
|
61 |
"exponential_logarithmic"]), help='type of the cost function') |
|
|
62 |
@click.option('--net_regularizer_type', default='anatomical_constraint_cae', |
|
|
63 |
type=click.Choice(['L2_norm', 'L1_norm', 'anatomical_constraint_acnn', |
|
|
64 |
'anatomical_constraint_cae']), |
|
|
65 |
help='type of regularization') |
|
|
66 |
@click.option('--net_regularization_coefficient', default=5e-4, type=click.FloatRange(min=0), |
|
|
67 |
help='regularization coefficient') |
|
|
68 |
@click.option('--net_acnn_model_path', default='./autoencoder_trained_%s', |
|
|
69 |
help='path where to restore the ACNN auto-encoder parameters for regularization') |
|
|
70 |
@click.option('--trainer_batch_size', default=8, type=click.IntRange(min=1, clamp=True), |
|
|
71 |
help='batch size for each training iteration') |
|
|
72 |
@click.option('--trainer_optimizer_name', default='adam', type=click.Choice(['momentum', 'adam']), |
|
|
73 |
help='type of the optimizer to use (momentum or adam)') |
|
|
74 |
@click.option('--train_model_path', default='./unet_trained_%s_%s/No_%d', help='path where to store checkpoints') |
|
|
75 |
@click.option('--train_training_iters', default=638, type=click.IntRange(min=1), |
|
|
76 |
help='number of training iterations during each epoch') |
|
|
77 |
@click.option('--train_epochs', default=30, type=click.IntRange(min=1), help='number of epochs') |
|
|
78 |
@click.option('--train_dropout_rate', default=0.2, type=click.FloatRange(min=0, max=1), help='dropout probability') |
|
|
79 |
@click.option('--train_clip_gradient', default=False, type=bool, |
|
|
80 |
help='whether to apply gradient clipping with L2 norm threshold 1.0') |
|
|
81 |
@click.option('--train_display_step', default=200, type=click.IntRange(min=1), |
|
|
82 |
help='number of steps till outputting stats') |
|
|
83 |
@click.option('--train_prediction_path', default='./validation_prediction_%s_%s/No_%d', |
|
|
84 |
help='path where to save predictions on each epoch') |
|
|
85 |
@click.option('--train_restore', default=False, type=bool, help='whether previous model checkpoint need restoring') |
|
|
86 |
@click.option('--test_search_path', default='../dataset/test_data/*.nii.gz', |
|
|
87 |
help='a search pattern to find all test data and label images') |
|
|
88 |
@click.option('--test_data_suffix', default='_img.nii.gz', help='suffix pattern for the test data images') |
|
|
89 |
@click.option('--test_label_suffix', default='_lab.nii.gz', help='suffix pattern for the test label images') |
|
|
90 |
@click.option('--test_shuffle_data', default=False, type=bool, |
|
|
91 |
help='whether the order of the loaded test files path should be randomized') |
|
|
92 |
@click.option('--test_channels', default=1, type=click.IntRange(min=1), help='number of test data channels') |
|
|
93 |
@click.option('--test_n_class', default=4, type=click.IntRange(min=1), |
|
|
94 |
help='number of test label classes, including the background') |
|
|
95 |
@click.option('--test_label_intensity', default=(0, 88, 200, 244), multiple=True, |
|
|
96 |
type=click.IntRange(min=0), |
|
|
97 |
help='tuple of intensities of the test ground truths') |
|
|
98 |
@click.option('--test_prediction_path', default=u'./test_prediction_%s_%s/No_%d', |
|
|
99 |
help='path where to save test predictions') |
|
|
100 |
@click.option('--val_search_path', default='../dataset/val_data/*.nii.gz', |
|
|
101 |
help='a search pattern to find all validation data and label images') |
|
|
102 |
@click.option('--val_data_suffix', default='_img.nii.gz', help='suffix pattern for the val data images') |
|
|
103 |
@click.option('--val_label_suffix', default='_lab.nii.gz', help='suffix pattern for the val label images') |
|
|
104 |
@click.option('--val_shuffle_data', default=False, type=bool, |
|
|
105 |
help='whether the order of the loaded val files path should be randomized') |
|
|
106 |
@click.option('--val_channels', default=1, type=click.IntRange(min=1), help='number of val data channels') |
|
|
107 |
@click.option('--val_n_class', default=4, type=click.IntRange(min=1), |
|
|
108 |
help='number of val label classes, including the background') |
|
|
109 |
@click.option('--val_label_intensity', default=(0, 88, 200, 244), multiple=True, |
|
|
110 |
type=click.IntRange(min=0), |
|
|
111 |
help='tuple of intensities of the test ground truths') |
|
|
112 |
@click.option('--train_center_crop', default=True, type=bool, |
|
|
113 |
help='whether to extract roi from center during training') |
|
|
114 |
@click.option('--train_center_roi', default=(120, 120, 1), multiple=True, type=click.IntRange(min=0), |
|
|
115 |
help='roi size you want to extract during training') |
|
|
116 |
@click.option('--test_center_crop', default=True, type=bool, |
|
|
117 |
help='whether to extract roi from center while testing') |
|
|
118 |
@click.option('--test_center_roi', default=(120, 120, 1), multiple=True, type=click.IntRange(min=0), |
|
|
119 |
help='roi size you want to extract while testing') |
|
|
120 |
@click.option('--pos_parameter', default=5e-4, type=click.FloatRange(min=0), |
|
|
121 |
help='position loss weight') |
|
|
122 |
def run(run_times, time, train_search_path, train_data_suffix, train_label_suffix, train_shuffle_data, train_crop_patch, train_patch_size, train_channels, train_n_class, train_contain_foreground, train_label_intensity, train_original_search_path, |
|
|
123 |
net_layers, net_features_root, net_cost_name, net_regularizer_type, net_regularization_coefficient, net_acnn_model_path, |
|
|
124 |
trainer_batch_size, trainer_optimizer_name, trainer_learning_rate, train_validation_batch_size, train_model_path, train_training_iters, train_epochs, train_dropout_rate, train_clip_gradient, train_display_step, train_prediction_path, train_restore, |
|
|
125 |
test_search_path, test_data_suffix, test_label_suffix, test_shuffle_data, |
|
|
126 |
test_channels, test_n_class, test_label_intensity, test_n_files, test_prediction_path, |
|
|
127 |
val_search_path, val_data_suffix, val_label_suffix, val_shuffle_data, |
|
|
128 |
val_channels, val_n_class, val_label_intensity, saliency, train_center_crop, train_center_roi, test_center_crop, test_center_roi, pos_parameter |
|
|
129 |
): |
|
|
130 |
if train_restore: |
|
|
131 |
assert time != t, "The time when the model to restore was trained is not the time now! " |
|
|
132 |
|
|
|
133 |
train_acc_table = np.array([]) |
|
|
134 |
train_dice_table = np.array([]) |
|
|
135 |
train_auc_table = np.array([]) |
|
|
136 |
train_sens_table = np.array([]) |
|
|
137 |
train_spec_table = np.array([]) |
|
|
138 |
test_acc_table = np.array([]) |
|
|
139 |
test_dice_table = np.array([]) |
|
|
140 |
test_auc_table = np.array([]) |
|
|
141 |
|
|
|
142 |
for i in range(run_times): |
|
|
143 |
train_data_provider = image_util.ImageDataProvider(search_path=train_search_path, |
|
|
144 |
data_suffix=train_data_suffix, |
|
|
145 |
label_suffix=train_label_suffix, |
|
|
146 |
shuffle_data=train_shuffle_data, |
|
|
147 |
crop_patch=train_crop_patch, |
|
|
148 |
patch_size=train_patch_size, |
|
|
149 |
channels=train_channels, |
|
|
150 |
n_class=train_n_class, |
|
|
151 |
contain_foreground=train_contain_foreground, |
|
|
152 |
label_intensity=train_label_intensity, |
|
|
153 |
center_crop=train_center_crop, |
|
|
154 |
center_roi=train_center_roi, |
|
|
155 |
inference_phase=False |
|
|
156 |
) |
|
|
157 |
|
|
|
158 |
train_original_data_provider = image_util.ImageDataProvider(search_path=train_original_search_path, |
|
|
159 |
data_suffix=test_data_suffix, |
|
|
160 |
label_suffix=test_label_suffix, |
|
|
161 |
shuffle_data=False, |
|
|
162 |
crop_patch=False, |
|
|
163 |
patch_size=train_patch_size, |
|
|
164 |
channels=train_channels, |
|
|
165 |
n_class=train_n_class, |
|
|
166 |
contain_foreground=train_contain_foreground, |
|
|
167 |
label_intensity=train_label_intensity, |
|
|
168 |
center_crop=train_center_crop, |
|
|
169 |
center_roi=train_center_roi, |
|
|
170 |
inference_phase=True |
|
|
171 |
) |
|
|
172 |
|
|
|
173 |
test_data_provider = image_util.ImageDataProvider(search_path=test_search_path, |
|
|
174 |
data_suffix=test_data_suffix, |
|
|
175 |
label_suffix=test_label_suffix, |
|
|
176 |
shuffle_data=test_shuffle_data, |
|
|
177 |
crop_patch=False, |
|
|
178 |
channels=test_channels, |
|
|
179 |
n_class=test_n_class, |
|
|
180 |
label_intensity=test_label_intensity, |
|
|
181 |
center_crop=test_center_crop, |
|
|
182 |
center_roi=test_center_roi, |
|
|
183 |
inference_phase=True) |
|
|
184 |
|
|
|
185 |
val_data_provider = image_util.ImageDataProvider(search_path=val_search_path, |
|
|
186 |
data_suffix=val_data_suffix, |
|
|
187 |
label_suffix=val_label_suffix, |
|
|
188 |
shuffle_data=val_shuffle_data, |
|
|
189 |
crop_patch=False, |
|
|
190 |
channels=val_channels, |
|
|
191 |
n_class=val_n_class, |
|
|
192 |
label_intensity=val_label_intensity, |
|
|
193 |
center_crop=test_center_crop, |
|
|
194 |
center_roi=test_center_roi, |
|
|
195 |
inference_phase=True) |
|
|
196 |
|
|
|
197 |
if net_regularizer_type == 'anatomical_constraint_acnn' or net_regularizer_type == 'anatomical_constraint_cae': |
|
|
198 |
acnn = ACNN.AutoEncoder(batch_size=trainer_batch_size) |
|
|
199 |
acnn_save_path = acnn.train(train_data_provider, net_acnn_model_path % saliency) |
|
|
200 |
|
|
|
201 |
net = unet.UNet(layers=net_layers, features_root=net_features_root, channels=train_channels, |
|
|
202 |
n_class=train_n_class, batch_size=trainer_batch_size, cost_name=net_cost_name, |
|
|
203 |
pos_parameter=pos_parameter, |
|
|
204 |
cost_kwargs={'regularizer_type': net_regularizer_type, |
|
|
205 |
'regularization_coefficient': net_regularization_coefficient, |
|
|
206 |
'acnn_model_path': (net_acnn_model_path % saliency)}) |
|
|
207 |
|
|
|
208 |
trainer = unet.Trainer(net, batch_size=trainer_batch_size, optimizer_name=trainer_optimizer_name, |
|
|
209 |
opt_kwargs={'learning_rate': trainer_learning_rate}) |
|
|
210 |
|
|
|
211 |
path, train_acc, train_dice, train_auc, train_sens, train_spec = trainer.train(train_data_provider, |
|
|
212 |
val_data_provider, |
|
|
213 |
train_original_data_provider, |
|
|
214 |
train_validation_batch_size, |
|
|
215 |
model_path=train_model_path % ( |
|
|
216 |
saliency, time, i), |
|
|
217 |
training_iters=train_training_iters, |
|
|
218 |
epochs=train_epochs, |
|
|
219 |
dropout=train_dropout_rate, |
|
|
220 |
clip_gradient=train_clip_gradient, |
|
|
221 |
display_step=train_display_step, |
|
|
222 |
prediction_path=train_prediction_path % ( |
|
|
223 |
saliency, time, i), |
|
|
224 |
restore=train_restore) |
|
|
225 |
train_acc_table = np.hstack((train_acc_table, train_acc)) |
|
|
226 |
train_dice_table = np.hstack((train_dice_table, train_dice)) |
|
|
227 |
train_auc_table = np.hstack((train_auc_table, train_auc)) |
|
|
228 |
train_sens_table = np.hstack((train_sens_table, train_sens)) |
|
|
229 |
train_spec_table = np.hstack((train_spec_table, train_spec)) |
|
|
230 |
|
|
|
231 |
train_summary_path = './train_summary_%s_%s' % (saliency, time) |
|
|
232 |
if not os.path.exists(train_summary_path): |
|
|
233 |
logging.info('Allocating {:}'.format(train_summary_path)) |
|
|
234 |
os.makedirs(train_summary_path) |
|
|
235 |
np.savez(os.path.join(train_summary_path, 'No_%d.npz' % i), acc=train_acc, dice=train_dice, auc=train_auc, |
|
|
236 |
sens=train_sens, spec=train_spec) |
|
|
237 |
|
|
|
238 |
test_data_provider.reset_index() |
|
|
239 |
test_data, test_labels, test_affine, _ = test_data_provider(test_n_files) |
|
|
240 |
predictions = net.predict(path, test_data) |
|
|
241 |
|
|
|
242 |
test_acc = unet.acc_rate(predictions, test_labels) |
|
|
243 |
test_dice = unet.dice_score(predictions, test_labels) |
|
|
244 |
test_auc = unet.auc_score(predictions, test_labels) |
|
|
245 |
|
|
|
246 |
test_acc_table = np.hstack((test_acc_table, test_acc)) |
|
|
247 |
test_dice_table = np.hstack((test_dice_table, test_dice)) |
|
|
248 |
test_auc_table = np.hstack((test_auc_table, test_auc)) |
|
|
249 |
|
|
|
250 |
dice_score_path = './dice_score_%s_%s' % (saliency, time) |
|
|
251 |
if not os.path.exists(dice_score_path): |
|
|
252 |
logging.info('Allocating {:}'.format(dice_score_path)) |
|
|
253 |
os.makedirs(dice_score_path) |
|
|
254 |
np.save(os.path.join(dice_score_path, 'No_%d.npy' % i), test_dice) |
|
|
255 |
print("Mean Dice score= {:.4f}".format(np.mean(test_dice))) |
|
|
256 |
|
|
|
257 |
for j in range(len(test_data)): |
|
|
258 |
test_data[j] = np.expand_dims(test_data[j], axis=0).transpose((0, 2, 3, 1, 4)) |
|
|
259 |
test_labels[j] = np.expand_dims(test_labels[j], axis=0).transpose((0, 2, 3, 1, 4)) |
|
|
260 |
predictions[j] = np.expand_dims(predictions[j], axis=0).transpose((0, 2, 3, 1, 4)) |
|
|
261 |
|
|
|
262 |
util.save_prediction(test_data, test_labels, predictions, test_prediction_path % (saliency, time, i)) |
|
|
263 |
util.save_prediction_1(predictions, test_affine, test_prediction_path % (saliency, time, i)) |
|
|
264 |
util.save_prediction_2(predictions, test_prediction_path % (saliency, time, i)) |
|
|
265 |
|
|
|
266 |
test_summary_path = './test_summary_%s_%s' % (saliency, time) |
|
|
267 |
if not os.path.exists(test_summary_path): |
|
|
268 |
logging.info('Allocating {:}'.format(test_summary_path)) |
|
|
269 |
os.makedirs(test_summary_path) |
|
|
270 |
np.savez(os.path.join(test_summary_path, 'No_%d.npz' % i), acc=test_acc, dice=test_dice, auc=test_auc) |
|
|
271 |
|
|
|
272 |
mean_train_acc = np.mean(np.reshape(train_acc_table, [run_times, -1]), axis=0) |
|
|
273 |
mean_train_dice = np.mean(np.reshape(train_dice_table, [run_times, -1]), axis=0) |
|
|
274 |
mean_train_auc = np.mean(np.reshape(train_auc_table, [run_times, -1]), axis=0) |
|
|
275 |
mean_train_sens = np.mean(np.reshape(train_sens_table, [run_times, -1]), axis=0) |
|
|
276 |
mean_train_spec = np.mean(np.reshape(train_spec_table, [run_times, -1]), axis=0) |
|
|
277 |
mean_test_acc = np.mean(np.reshape(test_acc_table, [run_times, -1]), axis=0) |
|
|
278 |
mean_test_dice = np.mean(np.reshape(train_dice_table, [run_times, -1]), axis=0) |
|
|
279 |
mean_test_auc = np.mean(np.reshape(train_auc_table, [run_times, -1]), axis=0) |
|
|
280 |
np.savez('./mean_train_summary_%s_%s.npz' % (saliency, time), acc=mean_train_acc, auc=mean_train_auc, |
|
|
281 |
sens=mean_train_sens, spec=mean_train_spec, dice=mean_train_dice) |
|
|
282 |
np.savez('./mean_test_summary_%s_%s.npz' % (saliency, time), acc=mean_test_acc, auc=mean_test_auc, |
|
|
283 |
dice=mean_test_dice) |
|
|
284 |
|
|
|
285 |
|
|
|
286 |
if __name__ == '__main__': |
|
|
287 |
run() |