Diff of /trainers/AAE.py [000000] .. [978658]

Switch to unified view

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