Arguments: margin: Integer, defines the baseline for distance for which pairs should be classified as dissimilar. Model ( inputs =, outputs = output_layer )ĭef loss ( margin = 1 ): """Provides 'constrastive_loss' an enclosing scope with variable 'margin'. Dense ( 1, activation = "sigmoid" )( normal_layer ) siamese = keras. BatchNormalization ()( merge_layer ) output_layer = layers. Lambda ( euclidean_distance )() normal_layer = tf. tower_1 = embedding_network ( input_1 ) tower_2 = embedding_network ( input_2 ) merge_layer = layers. To allow this, we will use # same embedding network for both tower networks. Input (( 28, 28, 1 )) # As mentioned above, Siamese Network share weights between # tower networks (sister networks). Dense ( 10, activation = "tanh" )( x ) embedding_network = keras. AveragePooling2D ( pool_size = ( 2, 2 ))( x ) x = layers. Conv2D ( 16, ( 5, 5 ), activation = "tanh" )( x ) x = layers. Conv2D ( 4, ( 5, 5 ), activation = "tanh" )( x ) x = layers. BatchNormalization ()( input ) x = layers. square ( x - y ), axis = 1, keepdims = True ) return tf. Returns: Tensor containing euclidean distance (as floating point value) between vectors. Arguments: vects: List containing two tensors of same length. # Provided two tensors t1 and t2 # Euclidean distance = sqrt(sum(square(t1-t2))) def euclidean_distance ( vects ): """Find the Euclidean distance between two vectors. concat (, pairs ], axis = 1 ), cmap = "gray" ) ax. subplots ( num_row, num_col, figsize = ( 5, 5 )) for i in range ( to_show ): # If the number of rows is 1, the axes array is one-dimensional if num_row = 1 : ax = axes else : ax = axes ax. """ # Define num_row # If to_show % num_col != 0 # trim to_show, # to trim to_show limit num_row to the point where # to_show % num_col = 0 # If to_show//num_col = 0 # then it means num_col is greater then to_show # increment to_show # to increment to_show set num_row to 1 num_row = to_show // num_col if to_show // num_col != 0 else 1 # `to_show` must be an integral multiple of `num_col` # we found num_row and we have num_col # to increment or decrement to_show # to make it integral multiple of `num_col` # simply set it equal to num_row * num_col to_show = num_row * num_col # Plot the images fig, axes = plt. test: Boolean telling whether the dataset being visualized is train dataset or test dataset - (default False). predictions: Numpy Array of predictions with shape (to_show, 1) - (default is None) Must be passed when test=True. num_col: Int, number of images in one row - (default is 3) For test and train respectively, it should not exceed 3 and 7. Otherwise it will be trimmed if it is greater than num_col, and incremented if if it is less then num_col. to_show: Int, number of examples to visualize (default is 6) `to_show` must be an integral multiple of `num_col`. Arguments: pairs: Numpy Array, of pairs to visualize, having shape (Number of pairs, 2, 28, 28). astype ( "float32" ) # make train pairs pairs_train, labels_train = make_pairs ( x_train, y_train ) # make validation pairs pairs_val, labels_val = make_pairs ( x_val, y_val ) # make test pairs pairs_test, labels_test = make_pairs ( x_test, y_test )ĭef visualize ( pairs, labels, to_show = 6, num_col = 3, predictions = None, test = False ): """Creates a plot of pairs and labels, and prediction if it's test dataset. choice ( digit_indices ) x2 = x pairs += ] labels += return np. randint ( 0, num_classes - 1 ) idx2 = random. randint ( 0, num_classes - 1 ) while label2 = label1 : label2 = random. choice ( digit_indices ) x2 = x pairs += ] labels += # add a non-matching example label2 = random. """ num_classes = max ( y ) + 1 digit_indices = for i in range ( num_classes )] pairs = labels = for idx1 in range ( len ( x )): # add a matching example x1 = x label1 = y idx2 = random. Returns: Tuple containing two numpy arrays as (pairs_of_samples, labels), where pairs_of_samples' shape is (2len(x), 2,n_features_dims) and labels are a binary array of shape (2len(x)).
y: List containing labels, each label with datatype of `int`. Arguments: x: List containing images, each index in this list corresponds to one image. Def make_pairs ( x, y ): """Creates a tuple containing image pairs with corresponding label.