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

Switch to unified view

a b/trainers/VAE.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, update_log_dicts, Phase, indicate_early_stopping
8
from trainers.DLMODEL import *
9
10
matplotlib.pyplot.ion()
11
12
13
class VAE(AEMODEL):
14
    class Config(AEMODEL.Config):
15
        def __init__(self):
16
            super().__init__('VAE')
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.outputs = self.network(self.x, dropout_rate=self.dropout_rate, dropout=self.dropout, config=self.config)
22
        self.reconstruction = self.outputs['x_hat']
23
        self.z_mu = self.outputs['z_mu']
24
        self.z_sigma = self.outputs['z_sigma']
25
26
        # Print Stats
27
        self.get_number_of_trainable_params()
28
        # Instantiate Saver
29
        self.saver = tf.train.Saver()
30
31
    def train(self, dataset):
32
        # Determine trainable variables
33
        self.variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
34
35
        # Build losses
36
        self.losses['L1'] = tf.losses.absolute_difference(self.x, self.reconstruction, reduction=Reduction.NONE)
37
        rec = tf.reduce_sum(self.losses['L1'], axis=[1, 2, 3])
38
        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)
39
40
        self.losses['reconstructionLoss'] = tf.reduce_mean(rec)
41
        self.losses['kl'] = tf.reduce_mean(kl)
42
        self.losses['loss'] = tf.reduce_mean(rec + kl)
43
44
        # Set the optimizer
45
        optim = self.create_optimizer(self.losses['loss'], var_list=self.variables, learningrate=self.config.learningrate,
46
                                      beta1=self.config.beta1, type=self.config.optimizer)
47
48
        # initialize all variables
49
        tf.global_variables_initializer().run(session=self.sess)
50
51
        best_cost = inf
52
        last_improvement = 0
53
        last_epoch = self.load_checkpoint()
54
55
        # Go go go!
56
        for epoch in range(last_epoch, self.config.numEpochs):
57
            ############
58
            # TRAINING #
59
            ############
60
            self.process(dataset, epoch, Phase.TRAIN, optim)
61
62
            # Increment last_epoch counter and save model
63
            last_epoch += 1
64
            self.save(self.checkpointDir, last_epoch)
65
66
            ##############
67
            # VALIDATION #
68
            ##############
69
            val_scalars = self.process(dataset, epoch, Phase.VAL)
70
71
            best_cost, last_improvement, stop = indicate_early_stopping(val_scalars['loss'], best_cost, last_improvement)
72
            if stop:
73
                print('Early stopping was triggered due to no improvement over the last 5 epochs')
74
                break
75
76
    def process(self, dataset, epoch, phase: Phase, optim=None):
77
        scalars = defaultdict(list)
78
        visuals = []
79
        num_batches = dataset.num_batches(self.config.batchsize, set=phase.value)
80
        for idx in range(0, num_batches):
81
            batch, _, _ = dataset.next_batch(self.config.batchsize, set=phase.value)
82
83
            fetches = {
84
                'reconstruction': self.reconstruction,
85
                **self.losses
86
            }
87
            if phase == Phase.TRAIN:
88
                fetches['optimizer'] = optim
89
90
            feed_dict = {
91
                self.x: batch,
92
                self.dropout: phase == Phase.TRAIN,
93
                self.dropout_rate: self.config.dropout_rate
94
            }
95
96
            run = self.sess.run(fetches, feed_dict=feed_dict)
97
98
            # Print to console
99
            print(f'Epoch ({phase.value}): [{epoch:2d}] [{idx:4d}/{num_batches:4d}] loss: {run["loss"]:.8f}')
100
            update_log_dicts(*trainer_utils.get_summary_dict(batch, run), scalars, visuals)
101
102
        self.log_to_tensorboard(epoch, scalars, visuals, phase)
103
        return scalars
104
105
    def reconstruct(self, x, dropout=False):
106
        if x.ndim < 4:
107
            x = np.expand_dims(x, 0)
108
109
        fetches = {
110
            'reconstruction': self.reconstruction
111
        }
112
113
        feed_dict = {
114
            self.x: x,
115
            self.dropout: dropout,  # apply only during MC sampling.
116
            self.dropout_rate: self.config.dropout_rate
117
        }
118
        results = self.sess.run(fetches, feed_dict=feed_dict)
119
120
        results['l1err'] = np.sum(np.abs(x - results['reconstruction']))
121
        results['l2err'] = np.sum(np.sqrt((x - results['reconstruction']) ** 2))
122
123
        return results