LSTMEval.py 7.24 KB
Newer Older
1 2 3 4 5 6 7 8
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# @author: Pavel Korshunov <pavel.korshunov@idiap.ch>
# @date: Wed 19 Oct 23:43:22 2016

from bob.pad.base.algorithm import Algorithm
import numpy

9
# import tensorflow as tf
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
10
import os
11 12

import logging
13

14 15 16
logger = logging.getLogger("bob.pad.voice")


17
class LSTMEval(Algorithm):
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
18
    """This class is for evaluating data stored in tensorflow tfrecord format using a pre-trained LSTM model."""
19 20

    def __init__(self,
21 22
                 input_shape=[200, 81],  # [temporal_length, feature_size]
                 lstm_network_size=60,  # the output size of LSTM cell
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
23
                 normalization_file=None,  # file with normalization parameters from train set
24 25 26 27 28 29 30 31
                 **kwargs):
        """Generates a test value that is read and written"""

        # call base class constructor registering that this tool performs everything.
        Algorithm.__init__(
            self,
            performs_projection=True,
            requires_projector_training=False,
32
            **kwargs
33
        )
34

35 36 37
        self.input_shape = input_shape
        self.num_time_steps = input_shape[0]
        self.lstm_network_size = lstm_network_size
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
38 39 40 41 42 43 44 45
        self.data_std = None
        if normalization_file and os.path.exists(normalization_file):
            npzfile = numpy.load(normalization_file)
            self.data_mean = npzfile['data_mean']
            self.data_std = npzfile['data_std']
        else:
            self.data_mean = 0
            self.data_std = 1
46

47
        self.data_reader = None
48
        self.session = None
49
        self.dnn_model = None
50
        self.data_placeholder = None
51

52 53 54 55
    def simple_lstm_network(self, train_data_shuffler, batch_size=10, lstm_cell_size=64,
                            num_time_steps=28, num_classes=10, seed=10, reuse=False):
        import tensorflow as tf
        from bob.learn.tensorflow.layers import lstm
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
56
        slim = tf.contrib.slim
57 58 59 60 61 62 63 64 65 66

        if isinstance(train_data_shuffler, tf.Tensor):
            inputs = train_data_shuffler
        else:
            inputs = train_data_shuffler("data", from_queue=False)

        initializer = tf.contrib.layers.xavier_initializer(seed=seed)

        # Creating an LSTM network
        graph = lstm(inputs, lstm_cell_size, num_time_steps=num_time_steps, batch_size=batch_size,
67
                     output_activation_size=num_classes, scope='lstm',
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
68
                     weights_initializer=initializer, activation=tf.nn.relu, reuse=reuse)
69 70

        # fully connect the LSTM output to the classes
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
71 72
        graph = slim.fully_connected(graph, num_classes, activation_fn=None, scope='fc1',
                                     weights_initializer=initializer, reuse=reuse)
73 74 75

        return graph

Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
76 77 78 79 80
    def normalize_data(self, features):
        mean = numpy.mean(features, axis=0)
        std = numpy.std(features, axis=0)
        return numpy.divide(features - mean, std)

81 82
    def _check_feature(self, feature):
        """Checks that the features are appropriate."""
83
        if not isinstance(feature, numpy.ndarray) or feature.ndim != 2 or feature.dtype != numpy.float32:
84 85
            raise ValueError("The given feature is not appropriate", feature)
        return True
86

87 88 89 90
    def restore_trained_model(self, projector_file):
        import tensorflow as tf
        if self.session is None:
            self.session = tf.Session()
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
91
        data_pl = tf.placeholder(tf.float32, shape=(None,) + tuple(self.input_shape))
92
        graph = self.simple_lstm_network(data_pl, batch_size=1,
93
                                         lstm_cell_size=self.lstm_network_size, num_time_steps=self.num_time_steps,
94
                                         num_classes=2, reuse=False)
95 96

        self.session.run(tf.global_variables_initializer())
97
        saver = tf.train.Saver()
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
98
        #        saver = tf.train.import_meta_graph(projector_file + ".meta", clear_devices=True)
99
        saver.restore(self.session, projector_file)
100
        return tf.nn.softmax(graph, name="softmax"), data_pl
101

102 103
    def load_projector(self, projector_file):
        logger.info("Loading pretrained model from {0}".format(projector_file))
104 105

        self.dnn_model, self.data_placeholder = self.restore_trained_model(projector_file)
106

107
    def project_feature(self, feature):
108

109
        logger.info(" .... Projecting %d features vector" % feature.shape[0])
110 111
        from bob.learn.tensorflow.datashuffler import DiskAudio
        if not self.data_reader:
112
            self.data_reader = DiskAudio([0], [0], [1] + self.input_shape)
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
113

Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
114 115 116 117 118 119 120 121 122
        # normalize the feature using pre-loaded normalization parameters
        if self.data_std and feature is not None:
            feature = numpy.divide(feature - self.data_mean, self.data_std)

        # split the feature in the sliding window frames
        frames, _ = self.data_reader.split_features_in_windows(features=feature, label=1,
                                                               win_size=self.num_time_steps,
                                                               sliding_step=5)
        logger.info(" .... And frames of shape {0} are extracted to pass into DNN model".format(frames.shape))
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
123 124 125
        if frames is None:
            return None

126
        projections = numpy.zeros((len(frames), 2), dtype=numpy.float32)
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
127 128
        for i in range(frames.shape[0]):
            frame = frames[i]
129 130 131 132 133
            frame = numpy.reshape(frame, ([1] + list(frames[0].shape)))
            logger.info(" .... projecting frame of shape {0} onto DNN model".format(frame.shape))

            if self.session is not None:
                forward_output = self.session.run(self.dnn_model, feed_dict={self.data_placeholder: frame})
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
134
                projections[i] = forward_output[0]
135 136 137
            else:
                raise ValueError("Tensorflow session was not initialized, so cannot project on DNN model!")
        logger.info("Projected scores {0}".format(projections))
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
138

139
        return numpy.asarray(projections, dtype=numpy.float32)
140

141 142
    def project(self, feature):
        """project(feature) -> projected
143

144 145
        This function will project the given feature.
        It is assured that the :py:meth:`load_projector` was called once before the ``project`` function is executed.
146

147
        **Parameters:**
148

149 150
        feature : object
          The feature to be projected.
151

152
        **Returns:**
153

154 155 156
        projected : object
          The projected features.
          Must be writable with the :py:meth:`write_feature` function and readable with the :py:meth:`read_feature` function.
157

158 159 160 161 162 163 164
        """
        if len(feature) > 0:
            feature = numpy.cast['float32'](feature)
            self._check_feature(feature)
            return self.project_feature(feature)
        else:
            return numpy.zeros(1, dtype=numpy.float64)
165

166 167
    def score_for_multiple_projections(self, toscore):
        """scorescore_for_multiple_projections(toscore) -> score
168

169
        **Returns:**
170

171 172 173 174
        score : float
          A score value for the object ``toscore``.
        """
        scores = numpy.asarray(toscore, dtype=numpy.float32)
175
        real_scores = scores[:, 1]
176 177
        logger.debug("Mean score %f", numpy.mean(real_scores))
        return [numpy.mean(real_scores)]
178

179 180 181 182 183
    def score(self, toscore):
        """Returns the evarage value of the probe"""
        logger.debug("score() score %f", toscore)
        # return only real score
        return [toscore[0]]
184 185


186
algorithm = LSTMEval()