forked from NifTK/NiftyNet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautoencoder_application.py
executable file
·280 lines (252 loc) · 13 KB
/
autoencoder_application.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
import tensorflow as tf
from niftynet.application.base_application import BaseApplication
from niftynet.engine.application_factory import ApplicationNetFactory
from niftynet.engine.application_factory import OptimiserFactory
from niftynet.engine.application_variables import CONSOLE
from niftynet.engine.application_variables import NETWORK_OUTPUT
from niftynet.engine.application_variables import TF_SUMMARIES
from niftynet.engine.sampler_linear_interpolate import LinearInterpolateSampler
from niftynet.engine.sampler_resize import ResizeSampler
from niftynet.engine.windows_aggregator_identity import WindowAsImageAggregator
from niftynet.io.image_reader import ImageReader
from niftynet.layer.loss_autoencoder import LossFunction
from niftynet.utilities.util_common import look_up_operations
SUPPORTED_INPUT = set(['image', 'feature'])
SUPPORTED_INFERENCE = \
set(['encode', 'encode-decode', 'sample', 'linear_interpolation'])
class AutoencoderApplication(BaseApplication):
REQUIRED_CONFIG_SECTION = "AUTOENCODER"
def __init__(self, net_param, action_param, is_training):
BaseApplication.__init__(self)
tf.logging.info('starting autoencoder application')
self.is_training = is_training
self.net_param = net_param
self.action_param = action_param
self.data_param = None
self.autoencoder_param = None
def initialise_dataset_loader(
self, data_param=None, task_param=None, data_partitioner=None):
self.data_param = data_param
self.autoencoder_param = task_param
if not self.is_training:
self._infer_type = look_up_operations(
self.autoencoder_param.inference_type, SUPPORTED_INFERENCE)
else:
self._infer_type = None
# read each line of csv files into an instance of Subject
if self.is_training:
file_lists = []
if self.action_param.validation_every_n > 0:
file_lists.append(data_partitioner.train_files)
file_lists.append(data_partitioner.validation_files)
else:
file_lists.append(data_partitioner.train_files)
self.readers = []
for file_list in file_lists:
reader = ImageReader(['image'])
reader.initialise(data_param, task_param, file_list)
self.readers.append(reader)
if self._infer_type in ('encode', 'encode-decode'):
self.readers = [ImageReader(['image'])]
self.readers[0].initialise(data_param,
task_param,
data_partitioner.inference_files)
elif self._infer_type == 'sample':
self.readers = []
elif self._infer_type == 'linear_interpolation':
self.readers = [ImageReader(['feature'])]
self.readers[0].initialise(data_param,
task_param,
data_partitioner.inference_files)
# if self.is_training or self._infer_type in ('encode', 'encode-decode'):
# mean_var_normaliser = MeanVarNormalisationLayer(image_name='image')
# self.reader.add_preprocessing_layers([mean_var_normaliser])
def initialise_sampler(self):
self.sampler = []
if self.is_training:
self.sampler.append([ResizeSampler(
reader=reader,
data_param=self.data_param,
batch_size=self.net_param.batch_size,
windows_per_image=1,
shuffle_buffer=True,
queue_length=self.net_param.queue_length) for reader in
self.readers])
return
if self._infer_type in ('encode', 'encode-decode'):
self.sampler.append([ResizeSampler(
reader=reader,
data_param=self.data_param,
batch_size=self.net_param.batch_size,
windows_per_image=1,
shuffle_buffer=False,
queue_length=self.net_param.queue_length) for reader in
self.readers])
return
if self._infer_type == 'linear_interpolation':
self.sampler.append([LinearInterpolateSampler(
reader=reader,
data_param=self.data_param,
batch_size=self.net_param.batch_size,
n_interpolations=self.autoencoder_param.n_interpolations,
queue_length=self.net_param.queue_length) for reader in
self.readers])
return
def initialise_network(self):
w_regularizer = None
b_regularizer = None
reg_type = self.net_param.reg_type.lower()
decay = self.net_param.decay
if reg_type == 'l2' and decay > 0:
from tensorflow.contrib.layers.python.layers import regularizers
w_regularizer = regularizers.l2_regularizer(decay)
b_regularizer = regularizers.l2_regularizer(decay)
elif reg_type == 'l1' and decay > 0:
from tensorflow.contrib.layers.python.layers import regularizers
w_regularizer = regularizers.l1_regularizer(decay)
b_regularizer = regularizers.l1_regularizer(decay)
self.net = ApplicationNetFactory.create(self.net_param.name)(
w_regularizer=w_regularizer,
b_regularizer=b_regularizer)
def connect_data_and_network(self,
outputs_collector=None,
gradients_collector=None):
def switch_sampler(for_training):
with tf.name_scope('train' if for_training else 'validation'):
sampler = self.get_sampler()[0][0 if for_training else -1]
return sampler.pop_batch_op()
if self.is_training:
if self.action_param.validation_every_n > 0:
data_dict = tf.cond(tf.logical_not(self.is_validation),
lambda: switch_sampler(True),
lambda: switch_sampler(False))
else:
data_dict = switch_sampler(for_training=True)
image = tf.cast(data_dict['image'], tf.float32)
net_output = self.net(image, is_training=self.is_training)
with tf.name_scope('Optimiser'):
optimiser_class = OptimiserFactory.create(
name=self.action_param.optimiser)
self.optimiser = optimiser_class.get_instance(
learning_rate=self.action_param.lr)
loss_func = LossFunction(loss_type=self.action_param.loss_type)
data_loss = loss_func(net_output)
loss = data_loss
if self.net_param.decay > 0.0:
reg_losses = tf.get_collection(
tf.GraphKeys.REGULARIZATION_LOSSES)
if reg_losses:
reg_loss = tf.reduce_mean(
[tf.reduce_mean(reg_loss) for reg_loss in reg_losses])
loss = loss + reg_loss
grads = self.optimiser.compute_gradients(loss)
# collecting gradients variables
gradients_collector.add_to_collection([grads])
outputs_collector.add_to_collection(
var=data_loss, name='variational_lower_bound',
average_over_devices=True, collection=CONSOLE)
outputs_collector.add_to_collection(
var=data_loss, name='variational_lower_bound',
average_over_devices=True, summary_type='scalar',
collection=TF_SUMMARIES)
outputs_collector.add_to_collection(
var=net_output[4], name='Originals',
average_over_devices=False, summary_type='image3_coronal',
collection=TF_SUMMARIES)
outputs_collector.add_to_collection(
var=net_output[2], name='Means',
average_over_devices=False, summary_type='image3_coronal',
collection=TF_SUMMARIES)
outputs_collector.add_to_collection(
var=net_output[5], name='Variances',
average_over_devices=False, summary_type='image3_coronal',
collection=TF_SUMMARIES)
else:
if self._infer_type in ('encode', 'encode-decode'):
data_dict = self.get_sampler()[0][0].pop_batch_op()
image = tf.cast(data_dict['image'], dtype=tf.float32)
net_output = self.net(image, is_training=False)
outputs_collector.add_to_collection(
var=data_dict['image_location'], name='location',
average_over_devices=True, collection=NETWORK_OUTPUT)
if self._infer_type == 'encode-decode':
outputs_collector.add_to_collection(
var=net_output[2], name='generated_image',
average_over_devices=True, collection=NETWORK_OUTPUT)
if self._infer_type == 'encode':
outputs_collector.add_to_collection(
var=net_output[7], name='embedded',
average_over_devices=True, collection=NETWORK_OUTPUT)
self.output_decoder = WindowAsImageAggregator(
image_reader=self.readers[0],
output_path=self.action_param.save_seg_dir)
return
elif self._infer_type == 'sample':
image_size = (self.net_param.batch_size,) + \
self.action_param.spatial_window_size + (1,)
dummy_image = tf.zeros(image_size)
net_output = self.net(dummy_image, is_training=False)
noise_shape = net_output[-1].get_shape().as_list()
stddev = self.autoencoder_param.noise_stddev
noise = tf.random_normal(shape=noise_shape,
mean=0.0,
stddev=stddev,
dtype=tf.float32)
partially_decoded_sample = self.net.shared_decoder(
noise, is_training=False)
decoder_output = self.net.decoder_means(
partially_decoded_sample, is_training=False)
outputs_collector.add_to_collection(
var=decoder_output, name='generated_image',
average_over_devices=True, collection=NETWORK_OUTPUT)
self.output_decoder = WindowAsImageAggregator(
image_reader=None,
output_path=self.action_param.save_seg_dir)
return
elif self._infer_type == 'linear_interpolation':
# construct the entire network
image_size = (self.net_param.batch_size,) + \
self.action_param.spatial_window_size + (1,)
dummy_image = tf.zeros(image_size)
net_output = self.net(dummy_image, is_training=False)
data_dict = self.get_sampler()[0][0].pop_batch_op()
real_code = data_dict['feature']
real_code = tf.reshape(real_code, net_output[-1].get_shape())
partially_decoded_sample = self.net.shared_decoder(
real_code, is_training=False)
decoder_output = self.net.decoder_means(
partially_decoded_sample, is_training=False)
outputs_collector.add_to_collection(
var=decoder_output, name='generated_image',
average_over_devices=True, collection=NETWORK_OUTPUT)
outputs_collector.add_to_collection(
var=data_dict['feature_location'], name='location',
average_over_devices=True, collection=NETWORK_OUTPUT)
self.output_decoder = WindowAsImageAggregator(
image_reader=self.readers[0],
output_path=self.action_param.save_seg_dir)
else:
raise NotImplementedError
def interpret_output(self, batch_output):
if self.is_training:
return True
else:
infer_type = look_up_operations(
self.autoencoder_param.inference_type,
SUPPORTED_INFERENCE)
if infer_type == 'encode':
return self.output_decoder.decode_batch(
batch_output['embedded'],
batch_output['location'][:, 0:1])
if infer_type == 'encode-decode':
return self.output_decoder.decode_batch(
batch_output['generated_image'],
batch_output['location'][:, 0:1])
if infer_type == 'sample':
return self.output_decoder.decode_batch(
batch_output['generated_image'],
None)
if infer_type == 'linear_interpolation':
return self.output_decoder.decode_batch(
batch_output['generated_image'],
batch_output['location'][:, :2])