LSTMEval.py 8.17 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
        self.data_std = None
39 40
#        import ipdb
#        ipdb.set_trace()
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
41
        features_length = input_shape[1]
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
42 43 44 45
        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']
46
            if not self.data_std.shape:  # if std was saved as scalar
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
47 48 49 50 51 52 53
                self.data_std = numpy.ones(features_length)
            # if self.data_mean.shape[0] > input_shape[0]:
            #     self.data_mean = self.data_mean[:input_shape[0]]
            # self.data_mean = numpy.reshape(self.data_mean, input_shape)
            # if self.data_std.shape[0] > input_shape[0]:
            #     self.data_std = self.data_std[:input_shape[0]]
            # self.data_std = numpy.reshape(self.data_std, input_shape)
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
54 55 56
        else:
            self.data_mean = 0
            self.data_std = 1
57

58
        self.data_reader = None
59
        self.session = None
60
        self.dnn_model = None
61
        self.data_placeholder = None
62

63 64 65 66
    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
67
        slim = tf.contrib.slim
68 69 70 71 72 73 74 75 76 77

        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,
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
78
                     output_activation_size=num_classes, scope='lstm', name='sync_cell',
79
                     weights_initializer=initializer, activation=tf.nn.sigmoid, reuse=reuse)
80 81

        # fully connect the LSTM output to the classes
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
82 83
        graph = slim.fully_connected(graph, num_classes, activation_fn=None, scope='fc1',
                                     weights_initializer=initializer, reuse=reuse)
84 85 86

        return graph

Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
87 88 89 90 91
    def normalize_data(self, features):
        mean = numpy.mean(features, axis=0)
        std = numpy.std(features, axis=0)
        return numpy.divide(features - mean, std)

92 93
    def _check_feature(self, feature):
        """Checks that the features are appropriate."""
94
        if not isinstance(feature, numpy.ndarray) or feature.ndim != 2 or feature.dtype != numpy.float32:
95 96
            raise ValueError("The given feature is not appropriate", feature)
        return True
97

98 99
    def restore_trained_model(self, projector_file):
        import tensorflow as tf
100 101
        from bob.learn.tensorflow.network import LightCNN9

102 103
        if self.session is None:
            self.session = tf.Session()
104 105 106
        data_pl = tf.placeholder(tf.float32, shape=(None,) + tuple(self.input_shape), name="data")
#        network = LightCNN9(n_classes=2, device="/cpu:0")
#        graph = network(data_pl)
107
        graph = self.simple_lstm_network(data_pl, batch_size=1,
108
                                         lstm_cell_size=self.lstm_network_size, num_time_steps=self.num_time_steps,
109
                                         num_classes=2, reuse=False)
110 111

        self.session.run(tf.global_variables_initializer())
112
        saver = tf.train.Saver()
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
113
        #        saver = tf.train.import_meta_graph(projector_file + ".meta", clear_devices=True)
114
        saver.restore(self.session, projector_file)
115
        return tf.nn.softmax(graph, name="softmax"), data_pl
116
#        return graph, data_pl
117

118 119
    def load_projector(self, projector_file):
        logger.info("Loading pretrained model from {0}".format(projector_file))
120 121

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

123
    def project_feature(self, feature):
124

125
        logger.info(" .... Projecting %d features vector" % feature.shape[0])
126 127
        from bob.learn.tensorflow.datashuffler import DiskAudio
        if not self.data_reader:
128
            self.data_reader = DiskAudio([0], [0], [1] + self.input_shape)
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
129

Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
130 131 132 133
        # normalize the feature using pre-loaded normalization parameters
        if self.data_std is not None and self.data_std.all() > 0:
            feature = numpy.divide(feature - self.data_mean, self.data_std)

Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
134 135 136
        # 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,
137
                                                               sliding_step=1)
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
138
#        logger.info(" .... And frames of shape {0} are extracted to pass into DNN model".format(frames.shape))
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
139 140 141
        if frames is None:
            return None

Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
142 143
        logger.info(" .... And frames of shape {0} are extracted to pass into DNN model".format(frames.shape))

144
        projections = numpy.zeros((len(frames), 2), dtype=numpy.float32)
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
145 146
        for i in range(frames.shape[0]):
            frame = frames[i]
147 148
            frame = numpy.reshape(frame, [1] + self.input_shape)
            #logger.info(" .... projecting frame of shape {0} onto DNN model".format(frame.shape))
149 150 151

            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
152
                projections[i] = forward_output[0]
153 154
            else:
                raise ValueError("Tensorflow session was not initialized, so cannot project on DNN model!")
Pavel KORSHUNOV's avatar
Pavel KORSHUNOV committed
155

156
        logger.info("Projected scores {0}".format(projections))
157
        return numpy.asarray(projections, dtype=numpy.float32)
158

159 160
    def project(self, feature):
        """project(feature) -> projected
161

162 163
        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.
164

165
        **Parameters:**
166

167 168
        feature : object
          The feature to be projected.
169

170
        **Returns:**
171

172 173 174
        projected : object
          The projected features.
          Must be writable with the :py:meth:`write_feature` function and readable with the :py:meth:`read_feature` function.
175

176 177 178 179 180 181 182
        """
        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)
183

184 185
    def score_for_multiple_projections(self, toscore):
        """scorescore_for_multiple_projections(toscore) -> score
186

187
        **Returns:**
188

189 190 191 192
        score : float
          A score value for the object ``toscore``.
        """
        scores = numpy.asarray(toscore, dtype=numpy.float32)
193
        real_scores = scores[:, 1]
194 195
        logger.debug("Mean score %f", numpy.mean(real_scores))
        return [numpy.mean(real_scores)]
196

197 198 199 200 201
    def score(self, toscore):
        """Returns the evarage value of the probe"""
        logger.debug("score() score %f", toscore)
        # return only real score
        return [toscore[0]]
202 203


204
algorithm = LSTMEval()