Path: blob/master/examples/vision/metric_learning.py
8035 views
"""1Title: Metric learning for image similarity search2Author: [Mat Kelcey](https://twitter.com/mat_kelcey)3Date created: 2020/06/054Last modified: 2020/06/095Description: Example of using similarity metric learning on CIFAR-10 images.6Accelerator: GPU7"""89"""10## Overview1112Metric learning aims to train models that can embed inputs into a high-dimensional space13such that "similar" inputs, as defined by the training scheme, are located close to each14other. These models once trained can produce embeddings for downstream systems where such15similarity is useful; examples include as a ranking signal for search or as a form of16pretrained embedding model for another supervised problem.1718For a more detailed overview of metric learning see:1920* [What is metric learning?](http://contrib.scikit-learn.org/metric-learn/introduction.html)21* ["Using crossentropy for metric learning" tutorial](https://www.youtube.com/watch?v=Jb4Ewl5RzkI)22"""2324"""25## Setup2627Set Keras backend to tensorflow.28"""29import os3031os.environ["KERAS_BACKEND"] = "tensorflow"3233import random34import matplotlib.pyplot as plt35import numpy as np36import tensorflow as tf37from collections import defaultdict38from PIL import Image39from sklearn.metrics import ConfusionMatrixDisplay40import keras41from keras import layers4243"""44## Dataset4546For this example we will be using the47[CIFAR-10](https://www.cs.toronto.edu/~kriz/cifar.html) dataset.48"""4950from keras.datasets import cifar105152(x_train, y_train), (x_test, y_test) = cifar10.load_data()5354x_train = x_train.astype("float32") / 255.055y_train = np.squeeze(y_train)56x_test = x_test.astype("float32") / 255.057y_test = np.squeeze(y_test)5859"""60To get a sense of the dataset we can visualise a grid of 25 random examples.616263"""6465height_width = 32666768def show_collage(examples):69box_size = height_width + 270num_rows, num_cols = examples.shape[:2]7172collage = Image.new(73mode="RGB",74size=(num_cols * box_size, num_rows * box_size),75color=(250, 250, 250),76)77for row_idx in range(num_rows):78for col_idx in range(num_cols):79array = (np.array(examples[row_idx, col_idx]) * 255).astype(np.uint8)80collage.paste(81Image.fromarray(array), (col_idx * box_size, row_idx * box_size)82)8384# Double size for visualisation.85collage = collage.resize((2 * num_cols * box_size, 2 * num_rows * box_size))86return collage878889# Show a collage of 5x5 random images.90sample_idxs = np.random.randint(0, 50000, size=(5, 5))91examples = x_train[sample_idxs]92show_collage(examples)9394"""95Metric learning provides training data not as explicit `(X, y)` pairs but instead uses96multiple instances that are related in the way we want to express similarity. In our97example we will use instances of the same class to represent similarity; a single98training instance will not be one image, but a pair of images of the same class. When99referring to the images in this pair we'll use the common metric learning names of the100`anchor` (a randomly chosen image) and the `positive` (another randomly chosen image of101the same class).102103To facilitate this we need to build a form of lookup that maps from classes to the104instances of that class. When generating data for training we will sample from this105lookup.106"""107108class_idx_to_train_idxs = defaultdict(list)109for y_train_idx, y in enumerate(y_train):110class_idx_to_train_idxs[y].append(y_train_idx)111112class_idx_to_test_idxs = defaultdict(list)113for y_test_idx, y in enumerate(y_test):114class_idx_to_test_idxs[y].append(y_test_idx)115116"""117For this example we are using the simplest approach to training; a batch will consist of118`(anchor, positive)` pairs spread across the classes. The goal of learning will be to119move the anchor and positive pairs closer together and further away from other instances120in the batch. In this case the batch size will be dictated by the number of classes; for121CIFAR-10 this is 10.122"""123124num_classes = 10125126127class AnchorPositivePairs(keras.utils.Sequence):128def __init__(self, num_batches):129super().__init__()130self.num_batches = num_batches131132def __len__(self):133return self.num_batches134135def __getitem__(self, _idx):136x = np.empty((2, num_classes, height_width, height_width, 3), dtype=np.float32)137for class_idx in range(num_classes):138examples_for_class = class_idx_to_train_idxs[class_idx]139anchor_idx = random.choice(examples_for_class)140positive_idx = random.choice(examples_for_class)141while positive_idx == anchor_idx:142positive_idx = random.choice(examples_for_class)143x[0, class_idx] = x_train[anchor_idx]144x[1, class_idx] = x_train[positive_idx]145return x146147148"""149We can visualise a batch in another collage. The top row shows randomly chosen anchors150from the 10 classes, the bottom row shows the corresponding 10 positives.151"""152153examples = next(iter(AnchorPositivePairs(num_batches=1)))154155show_collage(examples)156157"""158## Embedding model159160We define a custom model with a `train_step` that first embeds both anchors and positives161and then uses their pairwise dot products as logits for a softmax.162"""163164165class EmbeddingModel(keras.Model):166def train_step(self, data):167# Note: Workaround for open issue, to be removed.168if isinstance(data, tuple):169data = data[0]170anchors, positives = data[0], data[1]171172with tf.GradientTape() as tape:173# Run both anchors and positives through model.174anchor_embeddings = self(anchors, training=True)175positive_embeddings = self(positives, training=True)176177# Calculate cosine similarity between anchors and positives. As they have178# been normalised this is just the pair wise dot products.179similarities = keras.ops.einsum(180"ae,pe->ap", anchor_embeddings, positive_embeddings181)182183# Since we intend to use these as logits we scale them by a temperature.184# This value would normally be chosen as a hyper parameter.185temperature = 0.2186similarities /= temperature187188# We use these similarities as logits for a softmax. The labels for189# this call are just the sequence [0, 1, 2, ..., num_classes] since we190# want the main diagonal values, which correspond to the anchor/positive191# pairs, to be high. This loss will move embeddings for the192# anchor/positive pairs together and move all other pairs apart.193sparse_labels = keras.ops.arange(num_classes)194loss = self.compute_loss(y=sparse_labels, y_pred=similarities)195196# Calculate gradients and apply via optimizer.197gradients = tape.gradient(loss, self.trainable_variables)198self.optimizer.apply_gradients(zip(gradients, self.trainable_variables))199200# Update and return metrics (specifically the one for the loss value).201for metric in self.metrics:202# Calling `self.compile` will by default add a `keras.metrics.Mean` loss203if metric.name == "loss":204metric.update_state(loss)205else:206metric.update_state(sparse_labels, similarities)207208return {m.name: m.result() for m in self.metrics}209210211"""212Next we describe the architecture that maps from an image to an embedding. This model213simply consists of a sequence of 2d convolutions followed by global pooling with a final214linear projection to an embedding space. As is common in metric learning we normalise the215embeddings so that we can use simple dot products to measure similarity. For simplicity216this model is intentionally small.217"""218219inputs = layers.Input(shape=(height_width, height_width, 3))220x = layers.Conv2D(filters=32, kernel_size=3, strides=2, activation="relu")(inputs)221x = layers.Conv2D(filters=64, kernel_size=3, strides=2, activation="relu")(x)222x = layers.Conv2D(filters=128, kernel_size=3, strides=2, activation="relu")(x)223x = layers.GlobalAveragePooling2D()(x)224embeddings = layers.Dense(units=8, activation=None)(x)225embeddings = layers.UnitNormalization()(embeddings)226227model = EmbeddingModel(inputs, embeddings)228229"""230Finally we run the training. On a Google Colab GPU instance this takes about a minute.231"""232model.compile(233optimizer=keras.optimizers.Adam(learning_rate=1e-3),234loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),235)236237history = model.fit(AnchorPositivePairs(num_batches=1000), epochs=20)238239plt.plot(history.history["loss"])240plt.show()241242"""243## Testing244245We can review the quality of this model by applying it to the test set and considering246near neighbours in the embedding space.247248First we embed the test set and calculate all near neighbours. Recall that since the249embeddings are unit length we can calculate cosine similarity via dot products.250"""251252near_neighbours_per_example = 10253254embeddings = model.predict(x_test)255gram_matrix = np.einsum("ae,be->ab", embeddings, embeddings)256near_neighbours = np.argsort(gram_matrix.T)[:, -(near_neighbours_per_example + 1) :]257258"""259As a visual check of these embeddings we can build a collage of the near neighbours for 5260random examples. The first column of the image below is a randomly selected image, the261following 10 columns show the nearest neighbours in order of similarity.262"""263264num_collage_examples = 5265266examples = np.empty(267(268num_collage_examples,269near_neighbours_per_example + 1,270height_width,271height_width,2723,273),274dtype=np.float32,275)276for row_idx in range(num_collage_examples):277examples[row_idx, 0] = x_test[row_idx]278anchor_near_neighbours = reversed(near_neighbours[row_idx][:-1])279for col_idx, nn_idx in enumerate(anchor_near_neighbours):280examples[row_idx, col_idx + 1] = x_test[nn_idx]281282show_collage(examples)283284"""285We can also get a quantified view of the performance by considering the correctness of286near neighbours in terms of a confusion matrix.287288Let us sample 10 examples from each of the 10 classes and consider their near neighbours289as a form of prediction; that is, does the example and its near neighbours share the same290class?291292We observe that each animal class does generally well, and is confused the most with the293other animal classes. The vehicle classes follow the same pattern.294"""295296confusion_matrix = np.zeros((num_classes, num_classes))297298# For each class.299for class_idx in range(num_classes):300# Consider 10 examples.301example_idxs = class_idx_to_test_idxs[class_idx][:10]302for y_test_idx in example_idxs:303# And count the classes of its near neighbours.304for nn_idx in near_neighbours[y_test_idx][:-1]:305nn_class_idx = y_test[nn_idx]306confusion_matrix[class_idx, nn_class_idx] += 1307308# Display a confusion matrix.309labels = [310"Airplane",311"Automobile",312"Bird",313"Cat",314"Deer",315"Dog",316"Frog",317"Horse",318"Ship",319"Truck",320]321disp = ConfusionMatrixDisplay(confusion_matrix=confusion_matrix, display_labels=labels)322disp.plot(include_values=True, cmap="viridis", ax=None, xticks_rotation="vertical")323plt.show()324325326