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

Switch to unified view

a b/trainers/GMVAE.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 Phase, update_log_dicts, indicate_early_stopping, AEMODEL
8
from trainers.DLMODEL import *
9
10
11
class GMVAE(AEMODEL):
12
    class Config(AEMODEL.Config):
13
        def __init__(self):
14
            super().__init__('GMVAE')
15
            self.dim_c = 6
16
            self.dim_z = 1
17
            self.dim_w = 1
18
            self.c_lambda = 1
19
            self.restore_lr = 1e-3
20
            self.restore_steps = 150
21
            self.tv_lambda = 1.8
22
23
    def __init__(self, sess, config, network=None):
24
        super().__init__(sess, config, network)
25
        self.x = tf.placeholder(tf.float32, [None, self.config.outputHeight, self.config.outputWidth, self.config.numChannels], name='x')
26
        self.tv_lambda = tf.placeholder(tf.float32, shape=())
27
28
        # Additional Parameters
29
        self.dim_c = self.config.dim_c
30
        self.dim_z = self.config.dim_z
31
        self.dim_w = self.config.dim_w
32
        self.c_lambda = self.config.c_lambda
33
        self.restore_lr = self.config.restore_lr
34
        self.restore_steps = self.config.restore_steps
35
        self.tv_lambda_value = self.config.tv_lambda
36
37
        self.outputs = self.network(self.x, dropout_rate=self.dropout_rate, dropout=self.dropout, config=self.config)
38
39
        self.w_mu = self.outputs['w_mu']
40
        self.w_log_sigma = self.outputs['w_log_sigma']
41
        self.z_sampled = self.outputs['z_sampled']
42
        self.z_mu = self.outputs['z_mu']
43
        self.z_log_sigma = self.outputs['z_log_sigma']
44
        self.z_wc_mu = self.outputs['z_wc_mus']
45
        self.z_wc_log_sigma_inv = self.outputs['z_wc_log_sigma_invs']
46
        self.xz_mu = self.outputs['xz_mu']
47
        self.pc = self.outputs['pc']
48
        self.reconstruction = self.xz_mu
49
50
        # Print Stats
51
        self.get_number_of_trainable_params()
52
        # Instantiate Saver
53
        self.saver = tf.train.Saver()
54
55
    def train(self, dataset):
56
        # Determine trainable variables
57
        self.variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
58
59
        # Build losses
60
        # 1. the reconstruction loss
61
        self.losses['L1'] = tf.losses.absolute_difference(self.x, self.xz_mu, reduction=Reduction.NONE)
62
        self.losses['L1_sum'] = tf.reduce_sum(self.losses['L1'], axis=[1, 2, 3])
63
        self.losses['reconstructionLoss'] = self.losses['mean_p_loss'] = mean_p_loss = tf.reduce_mean(self.losses['L1_sum'])
64
        self.losses['L2'] = tf.losses.mean_squared_error(self.x, self.xz_mu, reduction=Reduction.NONE)
65
        self.losses['L2_sum'] = tf.reduce_sum(self.losses['L2'])
66
67
        # 2. E_c_w[KL(q(z|x)|| p(z|w, c))]
68
        # calculate KL for each cluster
69
        # KL  = 1/2(  logvar2 - logvar1 + (var1 + (m1-m2)^2)/var2  - 1 ) here dim_c clusters, then we have batchsize * dim_z * dim_c
70
        # then [batchsize * dim_z* dim_c] * [batchsize * dim_c * 1]  = batchsize * dim_z * 1, squeeze it to batchsize * dim_z
71
        self.z_mu = tf.tile(tf.expand_dims(self.z_mu, -1), [1, 1, self.dim_c])
72
        z_logvar = tf.tile(tf.expand_dims(self.z_log_sigma, -1), [1, 1, self.dim_c])
73
        d_mu_2 = tf.squared_difference(self.z_mu, self.z_wc_mu)
74
        d_var = (tf.exp(z_logvar) + d_mu_2) * (tf.exp(self.z_wc_log_sigma_inv) + 1e-6)
75
        d_logvar = -1 * (self.z_wc_log_sigma_inv + z_logvar)
76
        kl = (d_var + d_logvar - 1) * 0.5
77
        con_prior_loss = tf.reduce_sum(tf.squeeze(tf.matmul(kl, tf.expand_dims(self.pc, -1)), -1), 1)
78
        self.losses['conditional_prior_loss'] = mean_con_loss = tf.reduce_mean(con_prior_loss)
79
80
        # 3. KL(q(w|x)|| p(w) ~ N(0, I))
81
        # KL = 1/2 sum( mu^2 + var - logvar -1 )
82
        w_loss = 0.5 * tf.reduce_sum(tf.square(self.w_mu) + tf.exp(self.w_log_sigma) - self.w_log_sigma - 1, 1)
83
        self.losses['w_prior_loss'] = mean_w_loss = tf.reduce_mean(w_loss)
84
85
        # 4. KL(q(c|z)||p(c)) =  - sum_k q(k) log p(k)/q(k) , k = dim_c
86
        # let p(k) = 1/K#
87
88
        closs1 = tf.reduce_sum(tf.multiply(self.pc, tf.log(self.pc * self.dim_c + 1e-8)), [1])
89
        c_lambda = tf.cast(tf.fill(tf.shape(closs1), self.c_lambda), dtype=tf.float32)
90
        c_loss = tf.maximum(closs1, c_lambda)
91
        self.losses['c_prior_loss'] = mean_c_loss = tf.reduce_mean(c_loss)
92
93
        self.losses['loss'] = mean_p_loss + mean_con_loss + mean_w_loss + mean_c_loss
94
        self.losses['restore'] = self.tv_lambda * tf.image.total_variation(tf.subtract(self.x, self.reconstruction))
95
        self.losses['grads'] = tf.gradients(self.losses['loss'] + self.losses['restore'], self.x)[0]
96
97
        # Set the optimizer
98
        optim = self.create_optimizer(self.losses['loss'], var_list=self.variables, learningrate=self.config.learningrate,
99
                                      beta1=self.config.beta1, type=self.config.optimizer)
100
101
        # initialize all variables
102
        tf.global_variables_initializer().run(session=self.sess)
103
104
        best_cost = inf
105
        last_improvement = 0
106
        last_epoch = self.load_checkpoint()
107
108
        # Go go go!
109
        for epoch in range(last_epoch, self.config.numEpochs):
110
            ############
111
            # TRAINING #
112
            ############
113
            self.process(dataset, epoch, Phase.TRAIN, optim, visualization_keys=['reconstruction', 'L1', 'L2'])
114
115
            # Increment last_epoch counter and save model
116
            last_epoch += 1
117
            self.save(self.checkpointDir, last_epoch)
118
119
            ##############
120
            # VALIDATION #
121
            ##############
122
            val_scalars = self.process(dataset, epoch, Phase.VAL, visualization_keys=['reconstruction', 'L1', 'L2'])
123
124
            best_cost, last_improvement, stop = indicate_early_stopping(val_scalars['loss'], best_cost, last_improvement)
125
            if stop:
126
                print('Early stopping was triggered due to no improvement over the last 5 epochs')
127
                break
128
129
        if self.tv_lambda_value == -1 and self.restore_steps > 0:
130
            ##############
131
            # Determine lambda #
132
            ##############
133
            print('Determining best lambda')
134
            self.determine_best_lambda(dataset)
135
136
    def process(self, dataset, epoch, phase: Phase, optim=None, visualization_keys=None):
137
        scalars = defaultdict(list)
138
        visuals = []
139
        num_batches = dataset.num_batches(self.config.batchsize, set=phase.value)
140
        for idx in range(0, num_batches):
141
            batch, _, _ = dataset.next_batch(self.config.batchsize, set=phase.value)
142
143
            fetches = {
144
                'reconstruction': self.reconstruction,
145
                **self.losses
146
            }
147
            if phase == Phase.TRAIN:
148
                fetches['optimizer'] = optim
149
150
            feed_dict = {
151
                self.x: batch,
152
                self.tv_lambda: self.tv_lambda_value,
153
                self.dropout: phase == Phase.TRAIN,
154
                self.dropout_rate: self.config.dropout_rate
155
            }
156
157
            run = self.sess.run(fetches, feed_dict=feed_dict)
158
159
            # Print to console
160
            print(f'Epoch ({phase.value}): [{epoch:2d}] [{idx:4d}/{num_batches:4d}] loss: {run["loss"]:.8f}')
161
            update_log_dicts(*trainer_utils.get_summary_dict(batch, run, visualization_keys), scalars, visuals)
162
163
        self.log_to_tensorboard(epoch, scalars, visuals, phase)
164
        return scalars
165
166
    def reconstruct(self, x, dropout=False):
167
        if x.ndim < 4:
168
            x = np.expand_dims(x, 0)
169
170
        if self.restore_steps == 0:
171
            feed_dict = {
172
                self.x: x,
173
                self.tv_lambda: self.tv_lambda_value,
174
                self.dropout: dropout,
175
                self.dropout_rate: self.config.dropout_rate
176
            }
177
            results = self.sess.run({'reconstruction': self.reconstruction}, feed_dict=feed_dict)
178
        else:
179
            restored = x.copy()
180
            for step in range(self.restore_steps):
181
                feed_dict = {
182
                    self.x: restored,
183
                    self.tv_lambda: self.tv_lambda_value,
184
                    self.dropout: dropout,  # apply only during MC sampling.
185
                    self.dropout_rate: self.config.dropout_rate
186
                }
187
                run = self.sess.run({'grads': self.losses['grads']}, feed_dict=feed_dict)
188
                gradients = run['grads']
189
                restored -= self.restore_lr * gradients
190
191
            results = {
192
                'reconstruction': restored
193
            }
194
        results['l1err'] = np.sum(np.abs(x - results['reconstruction']))
195
        results['l2err'] = np.sum(np.sqrt((x - results['reconstruction']) ** 2))
196
197
        return results
198
199
    def determine_best_lambda(self, dataset):
200
        lambdas = np.arange(20) / 10.0
201
        mean_errors = []
202
        fetches = self.losses
203
204
        for tv_lambda in lambdas:
205
            errors = []
206
            for idx in range(int(dataset.num_batches(self.config.batchsize, set=Phase.VAL.value) * 0.2)):
207
                batch, _, _ = dataset.next_batch(self.config.batchsize, set=Phase.VAL.value)
208
                restored = batch.copy()
209
                for step in range(self.restore_steps):
210
                    feed_dict = {
211
                        self.x: restored,
212
                        self.tv_lambda: tv_lambda,
213
                        self.dropout: False,
214
                        self.dropout_rate: self.config.dropout_rate
215
                    }
216
                    run = self.sess.run(fetches, feed_dict=feed_dict)
217
                    restored -= self.restore_lr * run['grads']
218
                errors.append(np.sum(np.abs(batch - restored)))
219
            mean_error = np.mean(errors)
220
            mean_errors.append(mean_error)
221
            print(f'mean_error for lambda {tv_lambda}: {mean_error}')
222
        self.tv_lambda_value = lambdas[mean_errors.index(min(mean_errors))]
223
        print(f'Best lambda: {self.tv_lambda_value}')