test_cnn.py 7.94 KB
Newer Older
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
132
133
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
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# @author: Tiago de Freitas Pereira <tiago.pereira@idiap.ch>
# @date: Thu 13 Oct 2016 13:35 CEST

import numpy
from bob.learn.tensorflow.datashuffler import Memory, SiameseMemory, TripletMemory, Disk, SiameseDisk, TripletDisk
from bob.learn.tensorflow.network import Chopra, MLP
from bob.learn.tensorflow.loss import BaseLoss, ContrastiveLoss, TripletLoss
from bob.learn.tensorflow.trainers import Trainer, SiameseTrainer, TripletTrainer
# from ..analyzers import ExperimentAnalizer, SoftmaxAnalizer
from bob.learn.tensorflow.util import load_mnist
import tensorflow as tf
import bob.io.base
import os
import shutil
from scipy.spatial.distance import cosine
import bob.measure

"""
Some unit tests for the datashuffler
"""

batch_size = 16
validation_batch_size = 400
iterations = 50
seed = 10


def dummy_experiment(data_s, architecture, session):
    """
    Create a dummy experiment and return the EER
    """

    data_shuffler = object.__new__(Memory)
    data_shuffler.__dict__ = data_s.__dict__.copy()

    # Extracting features for enrollment
    enroll_data, enroll_labels = data_shuffler.get_batch()
    enroll_features = architecture(enroll_data, session=session)
    del enroll_data

    # Extracting features for probing
    probe_data, probe_labels = data_shuffler.get_batch()
    probe_features = architecture(probe_data, session=session)
    del probe_data

    # Creating models
    models = []
    for i in range(len(data_shuffler.possible_labels)):
        indexes_model = numpy.where(enroll_labels == data_shuffler.possible_labels[i])[0]
        models.append(numpy.mean(enroll_features[indexes_model, :], axis=0))

    # Probing
    positive_scores = numpy.zeros(shape=0)
    negative_scores = numpy.zeros(shape=0)
    for i in range(len(data_shuffler.possible_labels)):
        # Positive scoring
        indexes = probe_labels == data_shuffler.possible_labels[i]
        positive_data = probe_features[indexes, :]
        p = [cosine(models[i], positive_data[j]) for j in range(positive_data.shape[0])]
        positive_scores = numpy.hstack((positive_scores, p))

        # negative scoring
        indexes = probe_labels != data_shuffler.possible_labels[i]
        negative_data = probe_features[indexes, :]
        n = [cosine(models[i], negative_data[j]) for j in range(negative_data.shape[0])]
        negative_scores = numpy.hstack((negative_scores, n))

    threshold = bob.measure.eer_threshold((-1) * negative_scores, (-1) * positive_scores)
    far, frr = bob.measure.farfrr((-1) * negative_scores, (-1) * positive_scores, threshold)

    return (far + frr) / 2.


def test_cnn_trainer():
    train_data, train_labels, validation_data, validation_labels = load_mnist()
    train_data = numpy.reshape(train_data, (train_data.shape[0], 28, 28, 1))
    validation_data = numpy.reshape(validation_data, (validation_data.shape[0], 28, 28, 1))

    # Creating datashufflers
    train_data_shuffler = Memory(train_data, train_labels,
                                 input_shape=[28, 28, 1],
                                 batch_size=batch_size)

    with tf.Session() as session:
        directory = "./temp/cnn"

        # Preparing the architecture
        architecture = Chopra(seed=seed, fc1_output=10)

        # Loss for the softmax
        loss = BaseLoss(tf.nn.sparse_softmax_cross_entropy_with_logits, tf.reduce_mean)

        # One graph trainer
        trainer = Trainer(architecture=architecture,
                          loss=loss,
                          iterations=iterations,
                          analizer=None,
                          prefetch=False,
                          temp_dir=directory)
        trainer.train(train_data_shuffler)

        # Testing
        validation_shape = [400, 28, 28, 1]
        chopra = Chopra(seed=seed, fc1_output=10)
        chopra.load(bob.io.base.HDF5File(os.path.join(directory, "model.hdf5")),
                    shape=validation_shape, session=session)
        validation_data_shuffler = Memory(validation_data, validation_labels,
                                          input_shape=[28, 28, 1],
                                          batch_size=validation_batch_size)

        [data, labels] = validation_data_shuffler.get_batch()
        predictions = chopra(data, session=session)
        accuracy = 100. * numpy.sum(numpy.argmax(predictions, 1) == labels) / predictions.shape[0]

        # At least 80% of accuracy
        assert accuracy > 80.
        shutil.rmtree(directory)


def test_siamesecnn_trainer():
    train_data, train_labels, validation_data, validation_labels = load_mnist()
    train_data = numpy.reshape(train_data, (train_data.shape[0], 28, 28, 1))
    validation_data = numpy.reshape(validation_data, (validation_data.shape[0], 28, 28, 1))

    # Creating datashufflers
    train_data_shuffler = SiameseMemory(train_data, train_labels,
                                        input_shape=[28, 28, 1],
                                        batch_size=batch_size)
    validation_data_shuffler = SiameseMemory(validation_data, validation_labels,
                                             input_shape=[28, 28, 1],
                                             batch_size=validation_batch_size)

    with tf.Session() as session:
        directory = "./temp/siamesecnn"

        # Preparing the architecture
        architecture = Chopra(seed=seed, fc1_output=10)

        # Loss for the Siamese
        loss = ContrastiveLoss(contrastive_margin=4.)

        # One graph trainer
        trainer = SiameseTrainer(architecture=architecture,
                                 loss=loss,
                                 iterations=iterations,
                                 prefetch=False,
                                 analizer=None,
                                 temp_dir=directory)

        trainer.train(train_data_shuffler)

        # Testing
        validation_shape = [400, 28, 28, 1]
        chopra = Chopra(seed=seed, fc1_output=10)
        chopra.load(bob.io.base.HDF5File(os.path.join(directory, "model.hdf5")),
                    shape=validation_shape, session=session)

        eer = dummy_experiment(validation_data_shuffler, architecture, session)

        # At least 80% of accuracy
        assert eer < 0.25
        shutil.rmtree(directory)


def test_tripletcnn_trainer():
    train_data, train_labels, validation_data, validation_labels = load_mnist()
    train_data = numpy.reshape(train_data, (train_data.shape[0], 28, 28, 1))
    validation_data = numpy.reshape(validation_data, (validation_data.shape[0], 28, 28, 1))

    # Creating datashufflers
    train_data_shuffler = TripletMemory(train_data, train_labels,
                                        input_shape=[28, 28, 1],
                                        batch_size=batch_size)
    validation_data_shuffler = TripletMemory(validation_data, validation_labels,
                                             input_shape=[28, 28, 1],
                                             batch_size=validation_batch_size)

    with tf.Session() as session:
        directory = "./temp/tripletcnn"

        # Preparing the architecture
        architecture = Chopra(seed=seed, fc1_output=10)

        # Loss for the Siamese
        loss = TripletLoss(margin=4.)

        # One graph trainer
        trainer = TripletTrainer(architecture=architecture,
                                 loss=loss,
                                 iterations=iterations,
                                 prefetch=False,
                                 analizer=None,
                                 temp_dir=directory)

        trainer.train(train_data_shuffler)

        # Testing
        validation_shape = [400, 28, 28, 1]
        chopra = Chopra(seed=seed, fc1_output=10)
        chopra.load(bob.io.base.HDF5File(os.path.join(directory, "model.hdf5")),
                    shape=validation_shape, session=session)

        eer = dummy_experiment(validation_data_shuffler, architecture, session)

        # At least 80% of accuracy
        assert eer < 0.25
        shutil.rmtree(directory)