text stringlengths 0 4.99k |
|---|
dataset = tf.data.Dataset.zip((anchor_dataset, positive_dataset, negative_dataset)) |
dataset = dataset.shuffle(buffer_size=1024) |
dataset = dataset.map(preprocess_triplets) |
# Let's now split our dataset in train and validation. |
train_dataset = dataset.take(round(image_count * 0.8)) |
val_dataset = dataset.skip(round(image_count * 0.8)) |
train_dataset = train_dataset.batch(32, drop_remainder=False) |
train_dataset = train_dataset.prefetch(8) |
val_dataset = val_dataset.batch(32, drop_remainder=False) |
val_dataset = val_dataset.prefetch(8) |
Let's take a look at a few examples of triplets. Notice how the first two images look alike while the third one is always different. |
def visualize(anchor, positive, negative): |
\"\"\"Visualize a few triplets from the supplied batches.\"\"\" |
def show(ax, image): |
ax.imshow(image) |
ax.get_xaxis().set_visible(False) |
ax.get_yaxis().set_visible(False) |
fig = plt.figure(figsize=(9, 9)) |
axs = fig.subplots(3, 3) |
for i in range(3): |
show(axs[i, 0], anchor[i]) |
show(axs[i, 1], positive[i]) |
show(axs[i, 2], negative[i]) |
visualize(*list(train_dataset.take(1).as_numpy_iterator())[0]) |
png |
Setting up the embedding generator model |
Our Siamese Network will generate embeddings for each of the images of the triplet. To do this, we will use a ResNet50 model pretrained on ImageNet and connect a few Dense layers to it so we can learn to separate these embeddings. |
We will freeze the weights of all the layers of the model up until the layer conv5_block1_out. This is important to avoid affecting the weights that the model has already learned. We are going to leave the bottom few layers trainable, so that we can fine-tune their weights during training. |
base_cnn = resnet.ResNet50( |
weights=\"imagenet\", input_shape=target_shape + (3,), include_top=False |
) |
flatten = layers.Flatten()(base_cnn.output) |
dense1 = layers.Dense(512, activation=\"relu\")(flatten) |
dense1 = layers.BatchNormalization()(dense1) |
dense2 = layers.Dense(256, activation=\"relu\")(dense1) |
dense2 = layers.BatchNormalization()(dense2) |
output = layers.Dense(256)(dense2) |
embedding = Model(base_cnn.input, output, name=\"Embedding\") |
trainable = False |
for layer in base_cnn.layers: |
if layer.name == \"conv5_block1_out\": |
trainable = True |
layer.trainable = trainable |
Setting up the Siamese Network model |
The Siamese network will receive each of the triplet images as an input, generate the embeddings, and output the distance between the anchor and the positive embedding, as well as the distance between the anchor and the negative embedding. |
To compute the distance, we can use a custom layer DistanceLayer that returns both values as a tuple. |
class DistanceLayer(layers.Layer): |
\"\"\" |
This layer is responsible for computing the distance between the anchor |
embedding and the positive embedding, and the anchor embedding and the |
negative embedding. |
\"\"\" |
def __init__(self, **kwargs): |
super().__init__(**kwargs) |
def call(self, anchor, positive, negative): |
ap_distance = tf.reduce_sum(tf.square(anchor - positive), -1) |
an_distance = tf.reduce_sum(tf.square(anchor - negative), -1) |
return (ap_distance, an_distance) |
anchor_input = layers.Input(name=\"anchor\", shape=target_shape + (3,)) |
positive_input = layers.Input(name=\"positive\", shape=target_shape + (3,)) |
negative_input = layers.Input(name=\"negative\", shape=target_shape + (3,)) |
distances = DistanceLayer()( |
embedding(resnet.preprocess_input(anchor_input)), |
embedding(resnet.preprocess_input(positive_input)), |
embedding(resnet.preprocess_input(negative_input)), |
) |
siamese_network = Model( |
inputs=[anchor_input, positive_input, negative_input], outputs=distances |
) |
Putting everything together |
We now need to implement a model with custom training loop so we can compute the triplet loss using the three embeddings produced by the Siamese network. |
Let's create a Mean metric instance to track the loss of the training process. |
class SiameseModel(Model): |
\"\"\"The Siamese Network model with a custom training and testing loops. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.