In [1]:
'''Train a Siamese MLP on pairs of digits from the MNIST dataset.
It follows Hadsell-et-al.'06 [1] by computing the Euclidean distance on the
output of the shared network and by optimizing the contrastive loss (see paper
for mode details).
[1] "Dimensionality Reduction by Learning an Invariant Mapping"
    http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf
Gets to 99.5% test accuracy after 20 epochs.
3 seconds per epoch on a Titan X GPU
'''


Out[1]:
'Train a Siamese MLP on pairs of digits from the MNIST dataset.\nIt follows Hadsell-et-al.\'06 [1] by computing the Euclidean distance on the\noutput of the shared network and by optimizing the contrastive loss (see paper\nfor mode details).\n[1] "Dimensionality Reduction by Learning an Invariant Mapping"\n    http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf\nGets to 99.5% test accuracy after 20 epochs.\n3 seconds per epoch on a Titan X GPU\n'

In [16]:
import numpy as np
import random

In [17]:
# Keras imports
from keras.datasets import mnist
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Input, Lambda
from keras.optimizers import RMSprop
from keras import backend as K

In [18]:
def euclidean_distance(vects):
    x, y = vects
    return K.sqrt(K.maximum(K.sum(K.square(x - y), axis=1, keepdims=True), K.epsilon()))

In [19]:
def eucl_dist_output_shape(shapes):
    shape1, shape2 = shapes
    return (shape1[0], 1)

In [20]:
def contrastive_loss(y_true, y_pred):
    '''Contrastive loss from Hadsell-et-al.'06
    http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf
    '''
    margin = 1
    return K.mean(y_true * K.square(y_pred) +
                  (1 - y_true) * K.square(K.maximum(margin - y_pred, 0)))

In [21]:
def create_pairs(x, digit_indices):
    '''Positive and negative pair creation.
    Alternates between positive and negative pairs.
    '''
    pairs = []
    labels = []
    n = min([len(digit_indices[d]) for d in range(10)]) - 1
    for d in range(10):
        for i in range(n):
            z1, z2 = digit_indices[d][i], digit_indices[d][i + 1]
            pairs += [[x[z1], x[z2]]]
            inc = random.randrange(1, 10)
            dn = (d + inc) % 10
            z1, z2 = digit_indices[d][i], digit_indices[dn][i]
            pairs += [[x[z1], x[z2]]]
            labels += [1, 0]
    return np.array(pairs), np.array(labels)

In [22]:
def create_base_network(input_dim):
    '''Base network to be shared (eq. to feature extraction).
    '''
    seq = Sequential()
    seq.add(Dense(128, input_shape=(input_dim,), activation='relu'))
    seq.add(Dropout(0.1))
    seq.add(Dense(128, activation='relu'))
    seq.add(Dropout(0.1))
    seq.add(Dense(128, activation='relu'))
    return seq

In [23]:
def compute_accuracy(predictions, labels):
    '''Compute classification accuracy with a fixed threshold on distances.
    '''
    return labels[predictions.ravel() < 0.5].mean()

In [29]:
# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
# normalize
x_train /= 255
x_test /= 255
# flatten images
input_dim = 784
epochs = 20

In [25]:
# create training+test positive and negative pairs
digit_indices = [np.where(y_train == i)[0] for i in range(10)]
tr_pairs, tr_y = create_pairs(x_train, digit_indices)

digit_indices = [np.where(y_test == i)[0] for i in range(10)]
te_pairs, te_y = create_pairs(x_test, digit_indices)

In [26]:
# network definition
base_network = create_base_network(input_dim)

input_a = Input(shape=(input_dim,))
input_b = Input(shape=(input_dim,))

In [27]:
# because we re-use the same instance `base_network`,
# the weights of the network
# will be shared across the two branches
processed_a = base_network(input_a)
processed_b = base_network(input_b)

distance = Lambda(euclidean_distance,
                  output_shape=eucl_dist_output_shape)([processed_a, processed_b])

model = Model([input_a, input_b], distance)

In [28]:
# train
rms = RMSprop()
model.compile(loss=contrastive_loss, optimizer=rms)
model.fit([tr_pairs[:, 0], tr_pairs[:, 1]], tr_y,
          batch_size=128,
          epochs=epochs,
          validation_data=([te_pairs[:, 0], te_pairs[:, 1]], te_y))


Train on 108400 samples, validate on 17820 samples
Epoch 1/20
108400/108400 [==============================] - 5s - loss: 0.0960 - val_loss: 0.0432
Epoch 2/20
108400/108400 [==============================] - 5s - loss: 0.0406 - val_loss: 0.0294
Epoch 3/20
108400/108400 [==============================] - 5s - loss: 0.0277 - val_loss: 0.0248
Epoch 4/20
108400/108400 [==============================] - 5s - loss: 0.0221 - val_loss: 0.0241
Epoch 5/20
108400/108400 [==============================] - 5s - loss: 0.0190 - val_loss: 0.0235
Epoch 6/20
108400/108400 [==============================] - 5s - loss: 0.0165 - val_loss: 0.0219
Epoch 7/20
108400/108400 [==============================] - 5s - loss: 0.0148 - val_loss: 0.0219
Epoch 8/20
108400/108400 [==============================] - 5s - loss: 0.0136 - val_loss: 0.0221
Epoch 9/20
108400/108400 [==============================] - 5s - loss: 0.0125 - val_loss: 0.0221
Epoch 10/20
108400/108400 [==============================] - 5s - loss: 0.0119 - val_loss: 0.0233
Epoch 11/20
108400/108400 [==============================] - 5s - loss: 0.0113 - val_loss: 0.0228
Epoch 12/20
108400/108400 [==============================] - 5s - loss: 0.0108 - val_loss: 0.0221
Epoch 13/20
108400/108400 [==============================] - 5s - loss: 0.0105 - val_loss: 0.0228
Epoch 14/20
108400/108400 [==============================] - 5s - loss: 0.0101 - val_loss: 0.0228
Epoch 15/20
108400/108400 [==============================] - 5s - loss: 0.0099 - val_loss: 0.0226
Epoch 16/20
108400/108400 [==============================] - 5s - loss: 0.0091 - val_loss: 0.0220
Epoch 17/20
108400/108400 [==============================] - 5s - loss: 0.0091 - val_loss: 0.0241
Epoch 18/20
108400/108400 [==============================] - 5s - loss: 0.0086 - val_loss: 0.0240
Epoch 19/20
108400/108400 [==============================] - 5s - loss: 0.0085 - val_loss: 0.0239
Epoch 20/20
108400/108400 [==============================] - 5s - loss: 0.0083 - val_loss: 0.0230
Out[28]:
<keras.callbacks.History at 0x1118ef940>

In [14]:
# compute final accuracy on training and test sets
pred = model.predict([tr_pairs[:, 0], tr_pairs[:, 1]])
tr_acc = compute_accuracy(pred, tr_y)
pred = model.predict([te_pairs[:, 0], te_pairs[:, 1]])
te_acc = compute_accuracy(pred, te_y)

print('* Accuracy on training set: %0.2f%%' % (100 * tr_acc))
print('* Accuracy on test set: %0.2f%%' % (100 * te_acc))


* Accuracy on training set: 99.97%
* Accuracy on test set: 99.62%

In [ ]: