SiameseTrainer.py 8.98 KB
Newer Older
1 2 3 4 5 6 7 8
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# @author: Tiago de Freitas Pereira <tiago.pereira@idiap.ch>
# @date: Tue 09 Aug 2016 15:25:22 CEST

import logging
logger = logging.getLogger("bob.learn.tensorflow")
import tensorflow as tf
9
from tensorflow.core.framework import summary_pb2
10
import threading
11
from ..analyzers import ExperimentAnalizer, SoftmaxAnalizer
12
from ..network import SequenceNetwork
13
import bob.io.base
14
from .Trainer import Trainer
15
import os
16
import sys
17

18

19
class SiameseTrainer(Trainer):
20

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
    """
    Trainer for siamese networks.

    **Parameters**
      architecture: The architecture that you want to run. Should be a :py:class`bob.learn.tensorflow.network.SequenceNetwork`
      optimizer: One of the tensorflow optimizers https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html
      use_gpu: Use GPUs in the training
      loss: Loss
      temp_dir: The output directory

      base_learning_rate: Initial learning rate
      weight_decay:
      convergence_threshold:

      iterations: Maximum number of iterations
      snapshot: Will take a snapshot of the network at every `n` iterations
      prefetch: Use extra Threads to deal with the I/O
      analizer: Neural network analizer :py:mod:`bob.learn.tensorflow.analyzers`
      verbosity_level:

    """

43
    def __init__(self,
44 45
                 architecture,
                 optimizer=tf.train.AdamOptimizer(),
46 47
                 use_gpu=False,
                 loss=None,
48
                 temp_dir="cnn",
49 50 51 52

                 # Learning rate
                 base_learning_rate=0.001,
                 weight_decay=0.9,
53 54

                 ###### training options ##########
55
                 convergence_threshold=0.01,
56
                 iterations=5000,
57 58 59 60 61 62 63
                 snapshot=100,
                 prefetch=False,

                 ## Analizer
                 analizer=SoftmaxAnalizer(),

                 verbosity_level=2):
64

65 66 67 68 69 70
        super(SiameseTrainer, self).__init__(
            architecture=architecture,
            optimizer=optimizer,
            use_gpu=use_gpu,
            loss=loss,
            temp_dir=temp_dir,
71 72

            # Learning rate
73 74
            base_learning_rate=base_learning_rate,
            weight_decay=weight_decay,
75 76

            ###### training options ##########
77 78
            convergence_threshold=convergence_threshold,
            iterations=iterations,
79 80 81 82 83 84 85
            snapshot=snapshot,
            prefetch=prefetch,

            ## Analizer
            analizer=analizer,

            verbosity_level=verbosity_level
86
        )
87

88 89 90 91
        self.between_class_graph = None
        self.within_class_graph = None

    def compute_graph(self, data_shuffler, prefetch=False, name=""):
92
        """
93
        Computes the graph for the trainer.
94

95

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
        ** Parameters **

            data_shuffler: Data shuffler
            prefetch:
            name: Name of the graph
        """

        # Defining place holders
        if prefetch:
            placeholder_left_data, placeholder_right_data, placeholder_labels = data_shuffler.get_placeholders_pair_forprefetch(name="train")

            # Creating two graphs
            #placeholder_left_data, placeholder_labels = data_shuffler. \
            #    get_placeholders_forprefetch(name="train_left")
            #placeholder_right_data, _ = data_shuffler.get_placeholders(name="train_right")
            feature_left_batch, feature_right_batch, label_batch = data_shuffler.get_placeholders_pair(name="train_")

            # Defining a placeholder queue for prefetching
            queue = tf.FIFOQueue(capacity=100,
                                 dtypes=[tf.float32, tf.float32, tf.int64],
                                 shapes=[placeholder_left_data.get_shape().as_list()[1:],
                                         placeholder_right_data.get_shape().as_list()[1:],
                                         []])

            # Fetching the place holders from the queue
            self.enqueue_op = queue.enqueue_many([placeholder_left_data, placeholder_right_data, placeholder_labels])
            feature_left_batch, feature_right_batch, label_batch = queue.dequeue_many(data_shuffler.batch_size)

            # Creating the architecture for train and validation
            if not isinstance(self.architecture, SequenceNetwork):
                raise ValueError("The variable `architecture` must be an instance of "
                                 "`bob.learn.tensorflow.network.SequenceNetwork`")
        else:
            feature_left_batch, feature_right_batch, label_batch = data_shuffler.get_placeholders_pair(name="train_")
            #feature_left_batch, label_batch = data_shuffler.get_placeholders(name="train_left")
            #feature_right_batch, _ = data_shuffler.get_placeholders(name="train_right")
132

133
        # Creating the siamese graph
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
        train_left_graph = self.architecture.compute_graph(feature_left_batch)
        train_right_graph = self.architecture.compute_graph(feature_right_batch)

        graph, between_class_graph, within_class_graph = self.loss(label_batch,
                                                                   train_left_graph,
                                                                   train_right_graph)

        self.between_class_graph = between_class_graph
        self.within_class_graph = within_class_graph

        return graph

    def get_feed_dict(self, data_shuffler):
        """
        Given a data shuffler prepared the dictionary to be injected in the graph

        ** Parameters **
            data_shuffler:

        """

        batch_left, batch_right, labels = data_shuffler.get_pair()
        placeholder_left_data, placeholder_right_data, placeholder_label = data_shuffler.get_placeholders_pair(name="train")

        feed_dict = {placeholder_left_data: batch_left,
                     placeholder_right_data: batch_right,
                     placeholder_label: labels}

        return feed_dict

    def fit(self, session, step):
        """
        Run one iteration (`forward` and `backward`)

        ** Parameters **
            session: Tensorflow session
            step: Iteration number

        """
        if self.prefetch:
            _, l, bt_class, wt_class, lr, summary = session.run([self.optimizer,
                                             self.training_graph, self.between_class_graph, self.within_class_graph,
                                             self.learning_rate, self.summaries_train])
        else:
            feed_dict = self.get_feed_dict(self.train_data_shuffler)
            _, l, bt_class, wt_class, lr, summary = session.run([self.optimizer,
                                             self.training_graph, self.between_class_graph, self.within_class_graph,
                                             self.learning_rate, self.summaries_train], feed_dict=feed_dict)

        logger.info("Loss training set step={0} = {1}".format(step, l))
        self.train_summary_writter.add_summary(summary, step)

    def compute_validation(self, session, data_shuffler, step):
        """
        Computes the loss in the validation set

        ** Parameters **
            session: Tensorflow session
            data_shuffler: The data shuffler to be used
            step: Iteration number

        """

        if self.validation_summary_writter is None:
            self.validation_summary_writter = tf.train.SummaryWriter(os.path.join(self.temp_dir, 'validation'), session.graph)

        self.validation_graph = self.compute_graph(data_shuffler, name="validation")
        feed_dict = self.get_feed_dict(data_shuffler)
        l = session.run(self.validation_graph, feed_dict=feed_dict)

        summaries = []
        summaries.append(summary_pb2.Summary.Value(tag="loss", simple_value=float(l)))
        self.validation_summary_writter.add_summary(summary_pb2.Summary(value=summaries), step)
        logger.info("Loss VALIDATION set step={0} = {1}".format(step, l))

    def create_general_summary(self):
        """
        Creates a simple tensorboard summary with the value of the loss and learning rate
        """

        # Train summary
        tf.scalar_summary('loss', self.training_graph, name="train")
        tf.scalar_summary('between_class_loss', self.between_class_graph, name="train")
        tf.scalar_summary('within_class_loss', self.within_class_graph, name="train")
        tf.scalar_summary('lr', self.learning_rate, name="train")
        return tf.merge_all_summaries()

    def load_and_enqueue(self, session):
        """
        Injecting data in the place holder queue

        **Parameters**
          session: Tensorflow session
        """

        while not self.thread_pool.should_stop():

            batch_left, batch_right, labels = self.train_data_shuffler.get_pair()
            placeholder_left_data, placeholder_right_data, placeholder_label = self.train_data_shuffler.get_placeholders_pair()

            feed_dict = {placeholder_left_data: batch_left,
                         placeholder_right_data: batch_right,
                         placeholder_label: labels}

            session.run(self.enqueue_op, feed_dict=feed_dict)