Advertisement
Guest User

Untitled

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