train_test.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. from __future__ import absolute_import
  2. from __future__ import print_function
  3. import numpy as np
  4. import random
  5. from keras.datasets import mnist
  6. from keras.models import Model
  7. from keras.layers import Input, Flatten, Dense, Dropout, Lambda
  8. from keras.optimizer_v2.rmsprop import RMSprop
  9. from keras import backend as K
  10. num_classes = 10
  11. epochs = 20
  12. def euclidean_distance(vects):
  13. x, y = vects
  14. sum_square = K.sum(K.square(x - y), axis=1, keepdims=True)
  15. return K.sqrt(K.maximum(sum_square, K.epsilon()))
  16. def eucl_dist_output_shape(shapes):
  17. shape1, shape2 = shapes
  18. return (shape1[0], 1)
  19. def contrastive_loss(y_true, y_pred):
  20. '''Contrastive loss from Hadsell-et-al.'06
  21. http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf
  22. '''
  23. margin = 1
  24. square_pred = K.square(y_pred)
  25. margin_square = K.square(K.maximum(margin - y_pred, 0))
  26. return K.mean(y_true * square_pred + (1 - y_true) * margin_square)
  27. def create_pairs(x, digit_indices):
  28. '''Positive and negative pair creation.
  29. Alternates between positive and negative pairs.
  30. '''
  31. pairs = []
  32. labels = []
  33. n = min([len(digit_indices[d]) for d in range(num_classes)]) - 1
  34. for d in range(num_classes):
  35. for i in range(n):
  36. z1, z2 = digit_indices[d][i], digit_indices[d][i + 1]
  37. pairs += [[x[z1], x[z2]]]
  38. inc = random.randrange(1, num_classes)
  39. dn = (d + inc) % num_classes
  40. z1, z2 = digit_indices[d][i], digit_indices[dn][i]
  41. pairs += [[x[z1], x[z2]]]
  42. labels += [1, 0]
  43. return np.array(pairs), np.array(labels)
  44. def create_base_network(input_shape):
  45. '''Base network to be shared (eq. to feature extraction).
  46. '''
  47. _input = Input(shape=input_shape)
  48. x = Flatten()(_input)
  49. x = Dense(128, activation='relu')(x)
  50. x = Dropout(0.1)(x)
  51. x = Dense(128, activation='relu')(x)
  52. x = Dropout(0.1)(x)
  53. x = Dense(128, activation='relu')(x)
  54. return Model(input, x)
  55. def compute_accuracy(y_true, y_pred):
  56. '''Compute classification accuracy with a fixed threshold on distances.
  57. '''
  58. pred = y_pred.ravel() < 0.5
  59. return np.mean(pred == y_true)
  60. def accuracy(y_true, y_pred):
  61. '''Compute classification accuracy with a fixed threshold on distances.
  62. '''
  63. return K.mean(K.equal(y_true, K.cast(y_pred < 0.5, y_true.dtype)))
  64. # the data, split between train and test sets
  65. (x_train, y_train), (x_test, y_test) = mnist.load_data()
  66. x_train = x_train.astype('float32')
  67. x_test = x_test.astype('float32')
  68. x_train /= 255
  69. x_test /= 255
  70. input_shape = x_train.shape[1:]
  71. # create training+test positive and negative pairs
  72. digit_indices = [np.where(y_train == i)[0] for i in range(num_classes)]
  73. tr_pairs, tr_y = create_pairs(x_train, digit_indices)
  74. digit_indices = [np.where(y_test == i)[0] for i in range(num_classes)]
  75. te_pairs, te_y = create_pairs(x_test, digit_indices)
  76. # network definition
  77. base_network = create_base_network(input_shape)
  78. input_a = Input(shape=input_shape)
  79. input_b = Input(shape=input_shape)
  80. # because we re-use the same instance `base_network`,
  81. # the weights of the network
  82. # will be shared across the two branches
  83. processed_a = base_network(input_a)
  84. processed_b = base_network(input_b)
  85. distance = Lambda(euclidean_distance,
  86. output_shape=eucl_dist_output_shape)([processed_a, processed_b])
  87. model = Model([input_a, input_b], distance)
  88. # train
  89. rms = RMSprop()
  90. model.compile(loss=contrastive_loss, optimizer=rms, metrics=[accuracy])
  91. model.fit([tr_pairs[:, 0], tr_pairs[:, 1]], tr_y,
  92. batch_size=128,
  93. epochs=epochs,
  94. validation_data=([te_pairs[:, 0], te_pairs[:, 1]], te_y))
  95. # compute final accuracy on training and test sets
  96. y_pred = model.predict([tr_pairs[:, 0], tr_pairs[:, 1]])
  97. tr_acc = compute_accuracy(tr_y, y_pred)
  98. y_pred = model.predict([te_pairs[:, 0], te_pairs[:, 1]])
  99. te_acc = compute_accuracy(te_y, y_pred)
  100. print('* Accuracy on training set: %0.2f%%' % (100 * tr_acc))
  101. print('* Accuracy on test set: %0.2f%%' % (100 * te_acc))