Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/Natural Language Processing with Sequence Models/Week 4 - Siamese Networks/C3_W4_lecture_notebook_siamese.ipynb
Views: 13373
Creating a Siamese model using Trax: Ungraded Lecture Notebook
L2 Normalization
Before building the model you will need to define a function that applies L2 normalization to a tensor. This is very important because in this week's assignment you will create a custom loss function which expects the tensors it receives to be normalized. Luckily this is pretty straightforward:
Notice that the denominator can be replaced by np.linalg.norm(x, axis=-1, keepdims=True)
to achieve the same results and that Trax's numpy is being used within the function.
Notice that the initial tensor was converted from a numpy array to a jax array in the process.
Siamese Model
To create a Siamese
model you will first need to create a LSTM model using the Serial
combinator layer and then use another combinator layer called Parallel
to create the Siamese model. You should be familiar with the following layers (notice each layer can be clicked to go to the docs):
Serial
A combinator layer that allows to stack layers serially using function composition.Embedding
Maps discrete tokens to vectors. It will have shape(vocabulary length X dimension of output vectors)
. The dimension of output vectors (also calledd_feature
) is the number of elements in the word embedding.LSTM
The LSTM layer. It leverages another Trax layer calledLSTMCell
. The number of units should be specified and should match the number of elements in the word embedding.Mean
Computes the mean across a desired axis. Mean uses one tensor axis to form groups of values and replaces each group with the mean value of that group.Fn
Layer with no weights that applies the function f, which should be specified using a lambda syntax.Parallel
It is a combinator layer (likeSerial
) that applies a list of layers in parallel to its inputs.
Putting everything together the Siamese model will look like this:
Next is a helper function that prints information for every layer (sublayer within Serial
):
Try changing the parameters defined before the Siamese model and see how it changes!
You will actually train this model in this week's assignment. For now you should be more familiarized with creating Siamese models using Trax. Keep it up!