Path: blob/master/3 - Natural Language Processing with Sequence Models/Week 4/C3W4_L2_Modified Triplet Loss.ipynb
65 views
Modified Triplet Loss : Ungraded Lecture Notebook
In this notebook you'll see how to calculate the full triplet loss, step by step, including the mean negative and the closest negative. You'll also calculate the matrix of similarity scores.
Background
This is the original triplet loss function:
It can be improved by including the mean negative and the closest negative, to create a new full loss function. The inputs are the Anchor , Positive and Negative .
Let me show you what that means exactly, and how to calculate each step.
Imports
Similarity Scores
The first step is to calculate the matrix of similarity scores using cosine similarity so that you can look up , as needed for the loss formulas.
Two Vectors
First I'll show you how to calculate the similarity score, using cosine similarity, for 2 vectors.
Try changing the values in the second vector to see how it changes the cosine similarity.
Two Batches of Vectors
Now i'll show you how to calculate the similarity scores, using cosine similarity, for 2 batches of vectors. These are rows of individual vectors, just like in the example above, but stacked vertically into a matrix. They would look like the image below for a batch size (row count) of 4 and embedding size (column count) of 5.
The data is setup so that and represent duplicate inputs, but they are not duplicates with any other rows in the batch. This means and (green and green) have more similar vectors than say and (green and magenta).
I'll show you two different methods for calculating the matrix of similarities from 2 batches of vectors.

Hard Negative Mining
I'll now show you how to calculate the mean negative and the closest negative used in calculating and .
You'll do this using the matrix of similarity scores you already know how to make, like the example below for a batch size of 4. The diagonal of the matrix contains all the values, similarities from duplicate question pairs (aka Positives). This is an important attribute for the calculations to follow.

Mean Negative
is the average of the off diagonals, the values, for each row.
Closest Negative
is the largest off diagonal value, , that is smaller than the diagonal for each row.
Try using a different matrix of similarity scores.
The Loss Functions
The last step is to calculate the loss functions.
Summary
There were a lot of steps in there, so well done. You now know how to calculate a modified triplet loss, incorporating the mean negative and the closest negative. You also learned how to create a matrix of similarity scores based on cosine similarity.