|
a |
|
b/trainers/ceVAE.py |
|
|
1 |
from collections import defaultdict |
|
|
2 |
from math import inf |
|
|
3 |
|
|
|
4 |
from tensorflow.python.ops.losses.losses_impl import Reduction |
|
|
5 |
|
|
|
6 |
from trainers import trainer_utils |
|
|
7 |
from trainers.AEMODEL import AEMODEL, Phase, indicate_early_stopping, update_log_dicts |
|
|
8 |
from trainers.CE import retrieve_masked_batch |
|
|
9 |
from trainers.DLMODEL import * |
|
|
10 |
|
|
|
11 |
|
|
|
12 |
class ceVAE(AEMODEL): |
|
|
13 |
class Config(AEMODEL.Config): |
|
|
14 |
def __init__(self): |
|
|
15 |
super().__init__('ceVAE') |
|
|
16 |
self.use_gradient_based_restoration = True |
|
|
17 |
|
|
|
18 |
def __init__(self, sess, config, network=None): |
|
|
19 |
super().__init__(sess, config, network) |
|
|
20 |
self.x = tf.placeholder(tf.float32, [None, self.config.outputHeight, self.config.outputWidth, self.config.numChannels], name='x') |
|
|
21 |
self.x_ce = tf.placeholder(tf.float32, [None, self.config.outputHeight, self.config.outputWidth, self.config.numChannels], name='x_ce') |
|
|
22 |
self.outputs = self.network(self.x, self.x_ce, dropout_rate=self.dropout_rate, dropout=self.dropout, config=self.config) |
|
|
23 |
self.reconstruction = self.outputs['x_hat'] |
|
|
24 |
self.reconstruction_ce = self.outputs['x_hat_ce'] |
|
|
25 |
self.z_mu = self.outputs['z_mu'] |
|
|
26 |
self.z_sigma = self.outputs['z_sigma'] |
|
|
27 |
|
|
|
28 |
# Print Stats |
|
|
29 |
self.get_number_of_trainable_params() |
|
|
30 |
# Instantiate Saver |
|
|
31 |
self.saver = tf.train.Saver() |
|
|
32 |
|
|
|
33 |
def train(self, dataset): |
|
|
34 |
# Determine trainable variables |
|
|
35 |
self.variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) |
|
|
36 |
|
|
|
37 |
# Build losses |
|
|
38 |
self.losses['L1_vae'] = tf.losses.absolute_difference(self.x, self.reconstruction, reduction=Reduction.NONE) |
|
|
39 |
self.losses['L1_ce'] = tf.losses.absolute_difference(self.x_ce, self.reconstruction_ce, reduction=Reduction.NONE) |
|
|
40 |
self.losses['L1'] = 0.5 * (self.losses['L1_vae'] + self.losses['L1_ce']) |
|
|
41 |
rec_vae = tf.reduce_sum(self.losses['L1_vae'], axis=[1, 2, 3]) |
|
|
42 |
rec_ce = tf.reduce_sum(self.losses['L1_ce'], axis=[1, 2, 3]) |
|
|
43 |
kl = 0.5 * tf.reduce_sum(tf.square(self.z_mu) + tf.square(self.z_sigma) - tf.log(tf.square(self.z_sigma)) - 1, axis=1) |
|
|
44 |
|
|
|
45 |
self.losses['Rec_ce'] = tf.reduce_mean(rec_ce) |
|
|
46 |
self.losses['Rec_vae'] = tf.reduce_mean(rec_vae) |
|
|
47 |
self.losses['reconstructionLoss'] = 0.5 * tf.reduce_mean(rec_vae + rec_ce) |
|
|
48 |
self.losses['kl'] = tf.reduce_mean(kl) |
|
|
49 |
self.losses['loss'] = tf.reduce_mean(rec_vae + kl + rec_ce) |
|
|
50 |
self.losses['loss_vae'] = tf.reduce_mean(rec_vae + kl) |
|
|
51 |
self.losses['anomaly'] = self.losses['L1_vae'] * tf.abs(tf.gradients(self.losses['loss_vae'], self.x))[0] |
|
|
52 |
|
|
|
53 |
# Set the optimizer |
|
|
54 |
optim = self.create_optimizer(self.losses['loss'], var_list=self.variables, learningrate=self.config.learningrate, |
|
|
55 |
beta1=self.config.beta1, type=self.config.optimizer) |
|
|
56 |
|
|
|
57 |
# initialize all variables |
|
|
58 |
tf.global_variables_initializer().run(session=self.sess) |
|
|
59 |
|
|
|
60 |
best_cost = inf |
|
|
61 |
last_improvement = 0 |
|
|
62 |
last_epoch = self.load_checkpoint() |
|
|
63 |
|
|
|
64 |
visualization_keys = ['reconstruction', 'reconstruction_ce', 'anomaly'] |
|
|
65 |
# Go go go! |
|
|
66 |
for epoch in range(last_epoch, self.config.numEpochs): |
|
|
67 |
############ |
|
|
68 |
# TRAINING # |
|
|
69 |
############ |
|
|
70 |
self.process(dataset, epoch, Phase.TRAIN, optim, visualization_keys=visualization_keys) |
|
|
71 |
|
|
|
72 |
# Increment last_epoch counter and save model |
|
|
73 |
last_epoch += 1 |
|
|
74 |
self.save(self.checkpointDir, last_epoch) |
|
|
75 |
|
|
|
76 |
############## |
|
|
77 |
# VALIDATION # |
|
|
78 |
############## |
|
|
79 |
val_scalars = self.process(dataset, epoch, Phase.VAL, visualization_keys=visualization_keys) |
|
|
80 |
|
|
|
81 |
best_cost, last_improvement, stop = indicate_early_stopping(val_scalars['loss'], best_cost, last_improvement) |
|
|
82 |
if stop: |
|
|
83 |
print('Early stopping was triggered due to no improvement over the last 5 epochs') |
|
|
84 |
break |
|
|
85 |
|
|
|
86 |
def process(self, dataset, epoch, phase: Phase, optim=None, visualization_keys=None): |
|
|
87 |
scalars = defaultdict(list) |
|
|
88 |
visuals = [] |
|
|
89 |
num_batches = dataset.num_batches(self.config.batchsize, set=phase.value) |
|
|
90 |
for idx in range(0, num_batches): |
|
|
91 |
batch, _, brainmasks = dataset.next_batch(self.config.batchsize, return_brainmask=True, set=phase.value) |
|
|
92 |
|
|
|
93 |
masked_batch = retrieve_masked_batch(batch, brainmasks) |
|
|
94 |
|
|
|
95 |
fetches = { |
|
|
96 |
'reconstruction': self.reconstruction, |
|
|
97 |
'reconstruction_ce': self.reconstruction_ce, |
|
|
98 |
**self.losses |
|
|
99 |
} |
|
|
100 |
if phase == Phase.TRAIN: |
|
|
101 |
fetches['optimizer'] = optim |
|
|
102 |
|
|
|
103 |
feed_dict = { |
|
|
104 |
self.x: batch, |
|
|
105 |
self.x_ce: masked_batch if phase == Phase.TRAIN else batch, |
|
|
106 |
self.dropout: phase == Phase.TRAIN, |
|
|
107 |
self.dropout_rate: self.config.dropout_rate |
|
|
108 |
} |
|
|
109 |
|
|
|
110 |
run = self.sess.run(fetches, feed_dict=feed_dict) |
|
|
111 |
|
|
|
112 |
# Print to console |
|
|
113 |
print(f'Epoch ({phase.value}): [{epoch:2d}] [{idx:4d}/{num_batches:4d}] loss: {run["loss"]:.8f}') |
|
|
114 |
update_log_dicts(*trainer_utils.get_summary_dict(batch, run, visualization_keys), scalars, visuals) |
|
|
115 |
|
|
|
116 |
self.log_to_tensorboard(epoch, scalars, visuals, phase) |
|
|
117 |
return scalars |
|
|
118 |
|
|
|
119 |
def reconstruct(self, x, dropout=False): |
|
|
120 |
if x.ndim < 4: |
|
|
121 |
x = np.expand_dims(x, 0) |
|
|
122 |
|
|
|
123 |
fetches = { |
|
|
124 |
'reconstruction': self.reconstruction, |
|
|
125 |
**self.losses |
|
|
126 |
} |
|
|
127 |
|
|
|
128 |
feed_dict = { |
|
|
129 |
self.x: x, |
|
|
130 |
self.x_ce: x, |
|
|
131 |
self.dropout: dropout, |
|
|
132 |
self.dropout_rate: self.config.dropout_rate |
|
|
133 |
} |
|
|
134 |
results = self.sess.run(fetches, feed_dict=feed_dict) |
|
|
135 |
|
|
|
136 |
if self.config.use_gradient_based_restoration: |
|
|
137 |
# this is actually not the real 'reconstruction' but for convenience we treat it like it |
|
|
138 |
# would be to prevent changes in our evaluation script |
|
|
139 |
results['reconstruction'] = x - self.config.use_gradient_based_restoration * results['anomaly'] |
|
|
140 |
|
|
|
141 |
results['l1err'] = np.sum(np.abs(x - results['reconstruction'])) |
|
|
142 |
results['l2err'] = np.sum(np.sqrt((x - results['reconstruction']) ** 2)) |
|
|
143 |
|
|
|
144 |
return results |