text
stringlengths
0
4.99k
This example uses a Siamese Network with three identical subnetworks. We will provide three images to the model, where two of them will be similar (anchor and positive samples), and the third will be unrelated (a negative example.) Our goal is for the model to learn to estimate the similarity between images.
For the network to learn, we use a triplet loss function. You can find an introduction to triplet loss in the FaceNet paper by Schroff et al,. 2015. In this example, we define the triplet loss function as follows:
L(A, P, N) = max(‖f(A) - f(P)‖² - ‖f(A) - f(N)‖² + margin, 0)
This example uses the Totally Looks Like dataset by Rosenfeld et al., 2018.
Setup
import matplotlib.pyplot as plt
import numpy as np
import os
import random
import tensorflow as tf
from pathlib import Path
from tensorflow.keras import applications
from tensorflow.keras import layers
from tensorflow.keras import losses
from tensorflow.keras import optimizers
from tensorflow.keras import metrics
from tensorflow.keras import Model
from tensorflow.keras.applications import resnet
target_shape = (200, 200)
Load the dataset
We are going to load the Totally Looks Like dataset and unzip it inside the ~/.keras directory in the local environment.
The dataset consists of two separate files:
left.zip contains the images that we will use as the anchor.
right.zip contains the images that we will use as the positive sample (an image that looks like the anchor).
cache_dir = Path(Path.home()) / \".keras\"
anchor_images_path = cache_dir / \"left\"
positive_images_path = cache_dir / \"right\"
!gdown --id 1jvkbTr_giSP3Ru8OwGNCg6B4PvVbcO34
!gdown --id 1EzBZUb_mh_Dp_FKD0P4XiYYSd0QBH5zW
!unzip -oq left.zip -d $cache_dir
!unzip -oq right.zip -d $cache_dir
zsh:1: command not found: gdown
zsh:1: command not found: gdown
unzip: cannot find or open left.zip, left.zip.zip or left.zip.ZIP.
unzip: cannot find or open right.zip, right.zip.zip or right.zip.ZIP.
Preparing the data
We are going to use a tf.data pipeline to load the data and generate the triplets that we need to train the Siamese network.
We'll set up the pipeline using a zipped list with anchor, positive, and negative filenames as the source. The pipeline will load and preprocess the corresponding images.
def preprocess_image(filename):
\"\"\"
Load the specified file as a JPEG image, preprocess it and
resize it to the target shape.
\"\"\"
image_string = tf.io.read_file(filename)
image = tf.image.decode_jpeg(image_string, channels=3)
image = tf.image.convert_image_dtype(image, tf.float32)
image = tf.image.resize(image, target_shape)
return image
def preprocess_triplets(anchor, positive, negative):
\"\"\"
Given the filenames corresponding to the three images, load and
preprocess them.
\"\"\"
return (
preprocess_image(anchor),
preprocess_image(positive),
preprocess_image(negative),
)
Let's setup our data pipeline using a zipped list with an anchor, positive, and negative image filename as the source. The output of the pipeline contains the same triplet with every image loaded and preprocessed.
# We need to make sure both the anchor and positive images are loaded in
# sorted order so we can match them together.
anchor_images = sorted(
[str(anchor_images_path / f) for f in os.listdir(anchor_images_path)]
)
positive_images = sorted(
[str(positive_images_path / f) for f in os.listdir(positive_images_path)]
)
image_count = len(anchor_images)
anchor_dataset = tf.data.Dataset.from_tensor_slices(anchor_images)
positive_dataset = tf.data.Dataset.from_tensor_slices(positive_images)
# To generate the list of negative images, let's randomize the list of
# available images and concatenate them together.
rng = np.random.RandomState(seed=42)
rng.shuffle(anchor_images)
rng.shuffle(positive_images)
negative_images = anchor_images + positive_images
np.random.RandomState(seed=32).shuffle(negative_images)
negative_dataset = tf.data.Dataset.from_tensor_slices(negative_images)
negative_dataset = negative_dataset.shuffle(buffer_size=4096)