|
a |
|
b/trainers/ConstrainedAAE.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.DLMODEL import * |
|
|
9 |
|
|
|
10 |
|
|
|
11 |
class ConstrainedAAE(AEMODEL): |
|
|
12 |
class Config(AEMODEL.Config): |
|
|
13 |
def __init__(self): |
|
|
14 |
super().__init__('ConstrainedAAE') |
|
|
15 |
self.rho = 1 |
|
|
16 |
self.scale = 10.0 |
|
|
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.z = tf.placeholder(tf.float32, [None, self.config.zDim], name='z') |
|
|
22 |
|
|
|
23 |
self.outputs = self.network(self.z, self.x, dropout_rate=self.dropout_rate, dropout=self.dropout, config=self.config) |
|
|
24 |
self.reconstruction = self.x_hat = self.outputs['x_hat'] |
|
|
25 |
self.generated = self.z_ = self.outputs['z_'] |
|
|
26 |
self.d_ = self.outputs['d_'] |
|
|
27 |
self.d = self.outputs['d'] |
|
|
28 |
self.z_hat = self.outputs['z_hat'] |
|
|
29 |
self.d_hat = self.outputs['d_hat'] |
|
|
30 |
self.z_rec = self.outputs['z_rec'] |
|
|
31 |
|
|
|
32 |
self.scale = self.config.scale |
|
|
33 |
self.rho = self.config.rho |
|
|
34 |
|
|
|
35 |
# Print Stats |
|
|
36 |
self.get_number_of_trainable_params() |
|
|
37 |
# Instantiate Saver |
|
|
38 |
self.saver = tf.train.Saver() |
|
|
39 |
|
|
|
40 |
def train(self, dataset): |
|
|
41 |
# Determine trainable variables |
|
|
42 |
self.variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) |
|
|
43 |
|
|
|
44 |
# Build losses |
|
|
45 |
self.losses['gen_loss'] = gen_loss = -tf.reduce_mean(self.d_) |
|
|
46 |
self.losses['disc_loss_without_grad'] = disc_loss = tf.reduce_mean(self.d_) - tf.reduce_mean(self.d) |
|
|
47 |
self.losses['disc_loss_real'] = tf.reduce_mean(self.d) |
|
|
48 |
self.losses['disc_loss_fake'] = tf.reduce_mean(self.d_) |
|
|
49 |
|
|
|
50 |
ddx = tf.gradients(self.d_hat, self.z_hat)[0] |
|
|
51 |
ddx = tf.sqrt(tf.reduce_sum(tf.square(ddx), axis=1)) |
|
|
52 |
ddx = tf.reduce_mean(tf.square(ddx - 1.0) * self.scale) |
|
|
53 |
self.losses['disc_loss'] = disc_loss = disc_loss + ddx |
|
|
54 |
|
|
|
55 |
self.losses['L1'] = tf.losses.absolute_difference(self.x, self.reconstruction, reduction=Reduction.NONE) |
|
|
56 |
self.losses['reconstructionLoss'] = tf.reduce_mean(tf.reduce_sum(self.losses['L1'], axis=[1, 2, 3])) |
|
|
57 |
|
|
|
58 |
self.losses['L2'] = l2 = tf.reduce_mean(tf.losses.mean_squared_error(self.x, self.reconstruction, reduction=Reduction.NONE), axis=[1, 2, 3]) |
|
|
59 |
self.losses['Rec_z'] = rec_z = tf.reduce_mean(tf.losses.mean_squared_error(self.z_rec, self.z_, reduction=Reduction.NONE), axis=[1]) |
|
|
60 |
|
|
|
61 |
self.losses['loss'] = ae_loss = tf.reduce_mean(l2 + self.rho * rec_z) |
|
|
62 |
|
|
|
63 |
with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)): |
|
|
64 |
# Set the optimizer |
|
|
65 |
t_vars = tf.trainable_variables() |
|
|
66 |
dis_vars = [var for var in t_vars if 'Discriminator' in var.name] |
|
|
67 |
gen_vars = [var for var in t_vars if 'Encoder' in var.name] |
|
|
68 |
ae_vars = t_vars |
|
|
69 |
|
|
|
70 |
optim_dis = tf.train.AdamOptimizer(learning_rate=self.config.learningrate, beta1=0.5, beta2=0.9).minimize(disc_loss, var_list=dis_vars) |
|
|
71 |
optim_gen = tf.train.AdamOptimizer(learning_rate=self.config.learningrate, beta1=0.5, beta2=0.9).minimize(gen_loss, var_list=gen_vars) |
|
|
72 |
optim_ae = tf.train.AdamOptimizer(learning_rate=self.config.learningrate, beta1=0.5, beta2=0.9).minimize(ae_loss, var_list=ae_vars) |
|
|
73 |
|
|
|
74 |
# initialize all variables |
|
|
75 |
tf.global_variables_initializer().run(session=self.sess) |
|
|
76 |
|
|
|
77 |
best_cost = inf |
|
|
78 |
last_improvement = 0 |
|
|
79 |
last_epoch = self.load_checkpoint() |
|
|
80 |
|
|
|
81 |
# Go go go! |
|
|
82 |
for epoch in range(last_epoch, self.config.numEpochs): |
|
|
83 |
############ |
|
|
84 |
# TRAINING # |
|
|
85 |
############ |
|
|
86 |
phase = Phase.TRAIN |
|
|
87 |
scalars = defaultdict(list) |
|
|
88 |
visuals = [] |
|
|
89 |
d_iters = 20 |
|
|
90 |
num_batches = dataset.num_batches(self.config.batchsize, set=phase.value) |
|
|
91 |
for idx in range(0, num_batches): |
|
|
92 |
batch, _, _ = dataset.next_batch(self.config.batchsize, set=phase.value) |
|
|
93 |
|
|
|
94 |
run = {} |
|
|
95 |
for _ in range(d_iters if epoch <= 5 else 1): |
|
|
96 |
# AE optimization |
|
|
97 |
fetches = { |
|
|
98 |
'reconstruction': self.reconstruction, |
|
|
99 |
'rec_z': self.losses['Rec_z'], |
|
|
100 |
'L1': self.losses['L1'], |
|
|
101 |
'loss': self.losses['loss'], |
|
|
102 |
'reconstructionLoss': self.losses['reconstructionLoss'], |
|
|
103 |
'z_': self.z_, |
|
|
104 |
'z_rec': self.z_rec, |
|
|
105 |
'optimizer_ae': optim_ae |
|
|
106 |
} |
|
|
107 |
|
|
|
108 |
feed_dict = self.get_feed_dict(batch, phase) |
|
|
109 |
|
|
|
110 |
run = self.sess.run(fetches, feed_dict=feed_dict) |
|
|
111 |
|
|
|
112 |
for _ in range(d_iters): |
|
|
113 |
# Discriminator optimization |
|
|
114 |
fetches = { |
|
|
115 |
'disc_loss': self.losses['disc_loss'], |
|
|
116 |
'optimizer_d': optim_dis, |
|
|
117 |
} |
|
|
118 |
|
|
|
119 |
feed_dict = self.get_feed_dict(batch, phase) |
|
|
120 |
|
|
|
121 |
run = {**run, **self.sess.run(fetches, feed_dict=feed_dict)} |
|
|
122 |
|
|
|
123 |
# Generator optimization |
|
|
124 |
fetches = { |
|
|
125 |
'gen_loss': self.losses['gen_loss'], |
|
|
126 |
'optimizer_g': optim_gen, |
|
|
127 |
} |
|
|
128 |
|
|
|
129 |
feed_dict = self.get_feed_dict(batch, phase) |
|
|
130 |
|
|
|
131 |
run = {**run, **self.sess.run(fetches, feed_dict=feed_dict)} |
|
|
132 |
|
|
|
133 |
# Print to console |
|
|
134 |
print(f'Epoch ({phase.value}): [{epoch:2d}] [{idx:4d}/{num_batches:4d}] loss: {run["reconstructionLoss"]:.8f},' |
|
|
135 |
f' gen_loss: {run["gen_loss"]:.8f}, disc_loss: {run["disc_loss"]:.8f}') |
|
|
136 |
update_log_dicts(*trainer_utils.get_summary_dict(batch, run), scalars, visuals) |
|
|
137 |
|
|
|
138 |
self.log_to_tensorboard(epoch, scalars, visuals, phase) |
|
|
139 |
|
|
|
140 |
# Increment last_epoch counter and save model |
|
|
141 |
last_epoch += 1 |
|
|
142 |
self.save(self.checkpointDir, last_epoch) |
|
|
143 |
|
|
|
144 |
############## |
|
|
145 |
# VALIDATION # |
|
|
146 |
############## |
|
|
147 |
scalars = defaultdict(list) |
|
|
148 |
visuals = [] |
|
|
149 |
phase = Phase.VAL |
|
|
150 |
num_batches = dataset.num_batches(self.config.batchsize, set=phase.value) |
|
|
151 |
for idx in range(0, num_batches): |
|
|
152 |
batch, _, _ = dataset.next_batch(self.config.batchsize, set=phase.value) |
|
|
153 |
|
|
|
154 |
fetches = { |
|
|
155 |
'reconstruction': self.reconstruction, |
|
|
156 |
**self.losses |
|
|
157 |
} |
|
|
158 |
|
|
|
159 |
feed_dict = self.get_feed_dict(batch, phase) |
|
|
160 |
run = self.sess.run(fetches, feed_dict=feed_dict) |
|
|
161 |
|
|
|
162 |
# Print to console |
|
|
163 |
print(f'Epoch ({phase.value}): [{epoch:2d}] [{idx:4d}/{num_batches:4d}] loss: {run["loss"]:.8f}') |
|
|
164 |
update_log_dicts(*trainer_utils.get_summary_dict(batch, run), scalars, visuals) |
|
|
165 |
|
|
|
166 |
self.log_to_tensorboard(epoch, scalars, visuals, phase) |
|
|
167 |
|
|
|
168 |
best_cost, last_improvement, stop = indicate_early_stopping(scalars['reconstructionLoss'], best_cost, last_improvement) |
|
|
169 |
if stop: |
|
|
170 |
print('Early stopping was triggered due to no improvement over the last 5 epochs') |
|
|
171 |
break |
|
|
172 |
|
|
|
173 |
def get_feed_dict(self, batch, phase): |
|
|
174 |
return { |
|
|
175 |
self.x: batch, |
|
|
176 |
self.z: self.sample_z(), |
|
|
177 |
self.dropout: phase == Phase.TRAIN, |
|
|
178 |
self.dropout_rate: self.config.dropout_rate |
|
|
179 |
} |
|
|
180 |
|
|
|
181 |
def reconstruct(self, x, dropout=False): |
|
|
182 |
if x.ndim < 4: |
|
|
183 |
x = np.expand_dims(x, 0) |
|
|
184 |
|
|
|
185 |
fetches = { |
|
|
186 |
'reconstruction': self.reconstruction |
|
|
187 |
} |
|
|
188 |
|
|
|
189 |
feed_dict = { |
|
|
190 |
self.x: x, |
|
|
191 |
self.z: self.sample_z(), |
|
|
192 |
self.dropout: dropout, # apply only during MC sampling. |
|
|
193 |
self.dropout_rate: self.config.dropout_rate |
|
|
194 |
} |
|
|
195 |
results = self.sess.run(fetches, feed_dict=feed_dict) |
|
|
196 |
|
|
|
197 |
results['l1err'] = np.sum(np.abs(x - results['reconstruction'])) |
|
|
198 |
results['l2err'] = np.sum(np.sqrt((x - results['reconstruction']) ** 2)) |
|
|
199 |
|
|
|
200 |
return results |
|
|
201 |
|
|
|
202 |
def sample_z(self): |
|
|
203 |
return np.random.normal(size=[self.config.batchsize, self.config.zDim]) |