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/main/deep-learning-specialization/course-5-sequence-models/Neural_machine_translation_with_attention_v4a.ipynb
Views: 34213
Neural Machine Translation
Welcome to your first programming assignment for this week!
You will build a Neural Machine Translation (NMT) model to translate human-readable dates ("25th of June, 2009") into machine-readable dates ("2009-06-25").
You will do this using an attention model, one of the most sophisticated sequence-to-sequence models.
This notebook was produced together with NVIDIA's Deep Learning Institute.
Important Note on Submission to the AutoGrader
Before submitting your assignment to the AutoGrader, please make sure you are not doing the following:
You have not added any extra
print
statement(s) in the assignment.You have not added any extra code cell(s) in the assignment.
You have not changed any of the function parameters.
You are not using any global variables inside your graded exercises. Unless specifically instructed to do so, please refrain from it and use the local variables instead.
You are not changing the assignment code where it is not required, like creating extra variables.
If you do any of the following, you will get something like, Grader not found
(or similarly unexpected) error upon submitting your assignment. Before asking for help/debugging the errors in your assignment, check for these first. If this is the case, and you don't remember the changes you have made, you can get a fresh copy of the assignment by following these instructions.
Table of Contents
1 - Translating Human Readable Dates Into Machine Readable Dates
The model you will build here could be used to translate from one language to another, such as translating from English to Hindi.
However, language translation requires massive datasets and usually takes days of training on GPUs.
To give you a place to experiment with these models without using massive datasets, we will perform a simpler "date translation" task.
The network will input a date written in a variety of possible formats (e.g. "the 29th of August 1958", "03/30/1968", "24 JUNE 1987")
The network will translate them into standardized, machine readable dates (e.g. "1958-08-29", "1968-03-30", "1987-06-24").
We will have the network learn to output dates in the common machine-readable format YYYY-MM-DD.
You've loaded:
dataset
: a list of tuples of (human readable date, machine readable date).human_vocab
: a python dictionary mapping all characters used in the human readable dates to an integer-valued index.machine_vocab
: a python dictionary mapping all characters used in machine readable dates to an integer-valued index.Note: These indices are not necessarily consistent with
human_vocab
.
inv_machine_vocab
: the inverse dictionary ofmachine_vocab
, mapping from indices back to characters.
Let's preprocess the data and map the raw text data into the index values.
We will set Tx=30
We assume Tx is the maximum length of the human readable date.
If we get a longer input, we would have to truncate it.
We will set Ty=10
"YYYY-MM-DD" is 10 characters long.
You now have:
X
: a processed version of the human readable dates in the training set.Each character in X is replaced by an index (integer) mapped to the character using
human_vocab
.Each date is padded to ensure a length of using a special character (< pad >).
X.shape = (m, Tx)
where m is the number of training examples in a batch.
Y
: a processed version of the machine readable dates in the training set.Each character is replaced by the index (integer) it is mapped to in
machine_vocab
.Y.shape = (m, Ty)
.
Xoh
: one-hot version ofX
Each index in
X
is converted to the one-hot representation (if the index is 2, the one-hot version has the index position 2 set to 1, and the remaining positions are 0.Xoh.shape = (m, Tx, len(human_vocab))
Yoh
: one-hot version ofY
Each index in
Y
is converted to the one-hot representation.Yoh.shape = (m, Ty, len(machine_vocab))
.len(machine_vocab) = 11
since there are 10 numeric digits (0 to 9) and the-
symbol.
Let's also look at some examples of preprocessed training examples.
Feel free to play with
index
in the cell below to navigate the dataset and see how source/target dates are preprocessed.
2 - Neural Machine Translation with Attention
If you had to translate a book's paragraph from French to English, you would not read the whole paragraph, then close the book and translate.
Even during the translation process, you would read/re-read and focus on the parts of the French paragraph corresponding to the parts of the English you are writing down.
The attention mechanism tells a Neural Machine Translation model where it should pay attention to at any step.
2.1 - Attention Mechanism
In this part, you will implement the attention mechanism presented in the lecture videos.
Here is a figure to remind you how the model works.
The diagram on the left shows the attention model.
The diagram on the right shows what one "attention" step does to calculate the attention variables .
The attention variables are used to compute the context variable for each timestep in the output ().
|
|
Here are some properties of the model that you may notice:
Pre-attention and Post-attention LSTMs on both sides of the attention mechanism
There are two separate LSTMs in this model (see diagram on the left): pre-attention and post-attention LSTMs.
Pre-attention Bi-LSTM is the one at the bottom of the picture is a Bi-directional LSTM and comes before the attention mechanism.
The attention mechanism is shown in the middle of the left-hand diagram.
The pre-attention Bi-LSTM goes through time steps
Post-attention LSTM: at the top of the diagram comes after the attention mechanism.
The post-attention LSTM goes through time steps.
The post-attention LSTM passes the hidden state and cell state from one time step to the next.
An LSTM has both a hidden state and cell state
In the lecture videos, we were using only a basic RNN for the post-attention sequence model
This means that the state captured by the RNN was outputting only the hidden state .
In this assignment, we are using an LSTM instead of a basic RNN.
So the LSTM has both the hidden state and the cell state .
Each time step does not use predictions from the previous time step
Unlike previous text generation examples earlier in the course, in this model, the post-attention LSTM at time does not take the previous time step's prediction as input.
The post-attention LSTM at time 't' only takes the hidden state and cell state as input.
We have designed the model this way because unlike language generation (where adjacent characters are highly correlated) there isn't as strong a dependency between the previous character and the next character in a YYYY-MM-DD date.
Concatenation of hidden states from the forward and backward pre-attention LSTMs
: hidden state of the forward-direction, pre-attention LSTM.
: hidden state of the backward-direction, pre-attention LSTM.
: the concatenation of the activations of both the forward-direction and backward-directions of the pre-attention Bi-LSTM.
Computing "energies" as a function of and
Recall in the lesson videos "Attention Model", at time 6:45 to 8:16, the definition of "e" as a function of and .
"e" is called the "energies" variable.
is the hidden state of the post-attention LSTM
is the hidden state of the pre-attention LSTM.
and are fed into a simple neural network, which learns the function to output .
is then used when computing the attention that should pay to .
The diagram on the right of figure 1 uses a
RepeatVector
node to copy 's value times.Then it uses
Concatenation
to concatenate and .The concatenation of and is fed into a "Dense" layer, which computes .
is then passed through a softmax to compute .
Note that the diagram doesn't explicitly show variable , but is above the Dense layer and below the Softmax layer in the diagram in the right half of figure 1.
We'll explain how to use
RepeatVector
andConcatenation
in Keras below.
Implementation Details
Let's implement this neural translator. You will start by implementing two functions: one_step_attention()
and model()
.
one_step_attention
The inputs to the one_step_attention at time step are:
: all hidden states of the pre-attention Bi-LSTM.
: the previous hidden state of the post-attention LSTM
one_step_attention computes:
: the attention weights
: the context vector:
Clarifying 'context' and 'c'
In the lecture videos, the context was denoted
In the assignment, we are calling the context .
This is to avoid confusion with the post-attention LSTM's internal memory cell variable, which is also denoted .
Exercise 1 - one_step_attention
Implement one_step_attention()
.
The function
model()
will call the layers inone_step_attention()
times using a for-loop.It is important that all copies have the same weights.
It should not reinitialize the weights every time.
In other words, all steps should have shared weights.
Here's how you can implement layers with shareable weights in Keras:
Define the layer objects in a variable scope that is outside of the
one_step_attention
function. For example, defining the objects as global variables would work.Note that defining these variables inside the scope of the function
model
would technically work, sincemodel
will then call theone_step_attention
function. For the purposes of making grading and troubleshooting easier, we are defining these as global variables. Note that the automatic grader will expect these to be global variables as well.
Call these objects when propagating the input.
We have defined the layers you need as global variables.
Please run the following cells to create them.
Please note that the automatic grader expects these global variables with the given variable names. For grading purposes, please do not rename the global variables.
Please check the Keras documentation to learn more about these layers. The layers are functions. Below are examples of how to call these functions.
All tests passed!
Exercise 2 - modelf
Implement modelf()
as explained in figure 1 and the instructions:
modelf
first runs the input through a Bi-LSTM to get .Then,
modelf
callsone_step_attention()
times using afor
loop. At each iteration of this loop:It gives the computed context vector to the post-attention LSTM.
It runs the output of the post-attention LSTM through a dense layer with softmax activation.
The softmax generates a prediction .
Again, we have defined global layers that will share weights to be used in modelf()
.
Now you can use these layers times in a for
loop to generate the outputs, and their parameters will not be reinitialized. You will have to carry out the following steps:
Propagate the input
X
into a bi-directional LSTM.Remember that we want the LSTM to return a full sequence instead of just the last hidden state.
Sample code:
Iterate for :
Call
one_step_attention()
, passing in the sequence of hidden states from the pre-attention bi-directional LSTM, and the previous hidden state from the post-attention LSTM to calculate the context vector .Give to the post-attention LSTM cell.
Remember to pass in the previous hidden-state and cell-states of this LSTM
This outputs the new hidden state and the new cell state .
Sample code:
Please note that the layer is actually the "post attention LSTM cell". For the purposes of passing the automatic grader, please do not modify the naming of this global variable. This will be fixed when we deploy updates to the automatic grader.
Apply a dense, softmax layer to , get the output. Sample code:
Save the output by adding it to the list of outputs.
Create your Keras model instance.
It should have three inputs:
X
, the one-hot encoded inputs to the model, of shape (, the initial hidden state of the post-attention LSTM
, the initial cell state of the post-attention LSTM
The output is the list of outputs. Sample code
[['InputLayer', [(None, 30, 37)], 0], ['InputLayer', [(None, 64)], 0], ['Bidirectional', (None, 30, 64), 17920], ['RepeatVector', (None, 30, 64), 0, 30], ['Concatenate', (None, 30, 128), 0], ['Dense', (None, 30, 10), 1290, 'tanh'], ['Dense', (None, 30, 1), 11, 'relu'], ['Activation', (None, 30, 1), 0], ['Dot', (None, 1, 64), 0], ['InputLayer', [(None, 64)], 0], ['LSTM', [(None, 64), (None, 64), (None, 64)], 33024, [(None, 1, 64), (None, 64), (None, 64)], 'tanh'], ['Dense', (None, 11), 715, 'softmax']]
All tests passed!
Run the following cell to create your model.
Troubleshooting Note
If you are getting repeated errors after an initially incorrect implementation of "model", but believe that you have corrected the error, you may still see error messages when building your model.
A solution is to save and restart your kernel (or shutdown then restart your notebook), and re-run the cells.
Let's get a summary of the model to check if it matches the expected output.
Expected Output:
Here is the summary you should see
**Total params:** | 52,960 |
**Trainable params:** | 52,960 |
**Non-trainable params:** | 0 |
**bidirectional_1's output shape ** | (None, 30, 64) |
**repeat_vector_1's output shape ** | (None, 30, 64) |
**concatenate_1's output shape ** | (None, 30, 128) |
**attention_weights's output shape ** | (None, 30, 1) |
**dot_1's output shape ** | (None, 1, 64) |
**dense_3's output shape ** | (None, 11) |
All tests passed!
Define inputs and outputs, and fit the model
The last step is to define all your inputs and outputs to fit the model:
You have input
Xoh
of shape containing the training examples.You need to create
s0
andc0
to initialize yourpost_attention_LSTM_cell
with zeros.Given the
model()
you coded, you need the "outputs" to be a list of 10 elements of shape (m, T_y).The list
outputs[i][0], ..., outputs[i][Ty]
represents the true labels (characters) corresponding to the training example (Xoh[i]
).outputs[i][j]
is the true label of the character in the training example.
Let's now fit the model and run it for one epoch.
While training you can see the loss as well as the accuracy on each of the 10 positions of the output. The table below gives you an example of what the accuracies could be if the batch had 2 examples:
We have run this model for longer, and saved the weights. Run the next cell to load our weights. (By training a model for several minutes, you should be able to obtain a model of similar accuracy, but loading our model will save you time.)
You can now see the results on new examples.
You can also change these examples to test with your own examples. The next part will give you a better sense of what the attention mechanism is doing--i.e., what part of the input the network is paying attention to when generating a particular output character.
3 - Visualizing Attention (Optional / Ungraded)
Since the problem has a fixed output length of 10, it is also possible to carry out this task using 10 different softmax units to generate the 10 characters of the output. But one advantage of the attention model is that each part of the output (such as the month) knows it needs to depend only on a small part of the input (the characters in the input giving the month). We can visualize what each part of the output is looking at which part of the input.
Consider the task of translating "Saturday 9 May 2018" to "2018-05-09". If we visualize the computed we get this:
Notice how the output ignores the "Saturday" portion of the input. None of the output timesteps are paying much attention to that portion of the input. We also see that 9 has been translated as 09 and May has been correctly translated into 05, with the output paying attention to the parts of the input it needs to to make the translation. The year mostly requires it to pay attention to the input's "18" in order to generate "2018."
Navigate through the output of model.summary()
above. You can see that the layer named attention_weights
outputs the alphas
of shape (m, 30, 1) before dot_2
computes the context vector for every time step . Let's get the attention weights from this layer.
The function attention_map()
pulls out the attention values from your model and plots them.
Note: We are aware that you might run into an error running the cell below despite a valid implementation for Exercise 2 - modelf
above. If you get the error kindly report it on this Topic on Discourse as it'll help us improve our content.
If you haven’t joined our Discourse community you can do so by clicking on the link: http://bit.ly/dls-discourse
And don’t worry about the error, it will not affect the grading for this assignment.
On the generated plot you can observe the values of the attention weights for each character of the predicted output. Examine this plot and check that the places where the network is paying attention makes sense to you.
In the date translation application, you will observe that most of the time attention helps predict the year, and doesn't have much impact on predicting the day or month.
Congratulations!
You have come to the end of this assignment
Here's what you should remember
Machine translation models can be used to map from one sequence to another. They are useful not just for translating human languages (like French->English) but also for tasks like date format translation.
An attention mechanism allows a network to focus on the most relevant parts of the input when producing a specific part of the output.
A network using an attention mechanism can translate from inputs of length to outputs of length , where and can be different.
You can visualize attention weights to see what the network is paying attention to while generating each output.
Congratulations on finishing this assignment! You are now able to implement an attention model and use it to learn complex mappings from one sequence to another.