Neural Machine Learning Translation
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.
Updates¶
If you were working on the notebook before this update...¶
- The current notebook is version "4a".
- You can find your original work saved in the notebook with the previous version name ("v4")
- To view the file directory, go to the menu "File->Open", and this will open a new tab that shows the file directory.
List of updates¶
- Clarified names of variables to be consistent with the lectures and consistent within the assignment
- pre-attention bi-directional LSTM: the first LSTM that processes the input data.
- 'a': the hidden state of the pre-attention LSTM.
- post-attention LSTM: the LSTM that outputs the translation.
- 's': the hidden state of the post-attention LSTM.
- energies "e". The output of the dense function that takes "a" and "s" as inputs.
- All references to "output activation" are updated to "hidden state".
- "post-activation" sequence model is updated to "post-attention sequence model".
- 3.1: "Getting the activations from the Network" renamed to "Getting the attention weights from the network."
- Appropriate mentions of "activation" replaced "attention weights."
- Sequence of alphas corrected to be a sequence of "a" hidden states.
- pre-attention bi-directional LSTM: the first LSTM that processes the input data.
- one_step_attention:
- Provides sample code for each Keras layer, to show how to call the functions.
- Reminds students to provide the list of hidden states in a specific order, in order to pause the autograder.
- model
- Provides sample code for each Keras layer, to show how to call the functions.
- Added a troubleshooting note about handling errors.
- Fixed typo: outputs should be of length 10 and not 11.
define optimizer and compile model
- Provides sample code for each Keras layer, to show how to call the functions.
Spelling, grammar and wording corrections.
Let's load all the packages you will need for this assignment.
from keras.layers import Bidirectional, Concatenate, Permute, Dot, Input, LSTM, Multiply
from keras.layers import RepeatVector, Dense, Activation, Lambda
from keras.optimizers import Adam
from keras.utils import to_categorical
from keras.models import load_model, Model
import keras.backend as K
import numpy as np
from faker import Faker
import random
from tqdm import tqdm
from babel.dates import format_date
from nmt_utils import *
import matplotlib.pyplot as plt
%matplotlib inline
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.
1.1 - Dataset¶
We will train the model on a dataset of 10,000 human readable dates and their equivalent, standardized, machine readable dates. Let's run the following cells to load the dataset and print some examples.
m = 10000
dataset, human_vocab, machine_vocab, inv_machine_vocab = load_dataset(m)
dataset[:10]
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
.
- Note: These indices are not necessarily consistent with
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.
Tx = 30
Ty = 10
X, Y, Xoh, Yoh = preprocess_data(dataset, human_vocab, machine_vocab, Tx, Ty)
print("X.shape:", X.shape)
print("Y.shape:", Y.shape)
print("Xoh.shape:", Xoh.shape)
print("Yoh.shape:", Yoh.shape)
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 $T_x$ using a special character (< pad >).
X.shape = (m, Tx)
where m is the number of training examples in a batch.
- Each character in X is replaced by an index (integer) mapped to the character using
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)
.
- Each character is replaced by the index (integer) it is mapped to in
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))
- Each index in
Yoh
: one-hot version ofY
- Each index in
Y
is converted to the one-hot representation. Yoh.shape = (m, Tx, len(machine_vocab))
.len(machine_vocab) = 11
since there are 10 numeric digits (0 to 9) and the-
symbol.
- Each index in
- 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.
index = 0
print("Source date:", dataset[index][0])
print("Target date:", dataset[index][1])
print()
print("Source after preprocessing (indices):", X[index])
print("Target after preprocessing (indices):", Y[index])
print()
print("Source after preprocessing (one-hot):", Xoh[index])
print("Target after preprocessing (one-hot):", Yoh[index])
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 $\alpha^{\langle t, t' \rangle}$.
- The attention variables $\alpha^{\langle t, t' \rangle}$ are used to compute the context variable $context^{\langle t \rangle}$ for each timestep in the output ($t=1, \ldots, T_y$).
![]() |
![]() |
</table>
**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) |
Compile the model¶
- After creating your model in Keras, you need to compile it and define the loss function, optimizer and metrics you want to use.
Sample code
optimizer = Adam(lr=..., beta_1=..., beta_2=..., decay=...)
model.compile(optimizer=..., loss=..., metrics=[...])
### START CODE HERE ### (≈2 lines)
opt = Adam()
model.compile(optimizer=opt, loss="categorical_crossentropy", metrics=["accuracy"])
### END CODE HERE ###
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 X of shape $(m = 10000, T_x = 30)$ 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 $i^{th}$ training example (X[i]
). outputs[i][j]
is the true label of the $j^{th}$ character in the $i^{th}$ training example.
- The list
s0 = np.zeros((m, n_s))
c0 = np.zeros((m, n_s))
outputs = list(Yoh.swapaxes(0,1))
Let's now fit the model and run it for one epoch.
model.fit([Xoh, s0, c0], outputs, epochs=1, batch_size=100)
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.)
model.load_weights('models/model.h5')
You can now see the results on new examples.
EXAMPLES = ['3 May 1979', '5 April 09', '21th of August 2016', 'Tue 10 Jul 2007', 'Saturday May 9 2018', 'March 3 2001', 'March 3rd 2001', '1 March 2001']
for example in EXAMPLES:
source = string_to_int(example, Tx, human_vocab)
source = np.array(list(map(lambda x: to_categorical(x, num_classes=len(human_vocab)), source))).swapaxes(0,1)
prediction = model.predict([source, s0, c0])
prediction = np.argmax(prediction, axis = -1)
output = [inv_machine_vocab[int(i)] for i in prediction]
print("source:", example)
print("output:", ''.join(output),"\n")
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 $\alpha^{\langle t, t' \rangle}$ 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."
3.1 - Getting the attention weights from the network¶
Lets now visualize the attention values in your network. We'll propagate an example through the network, then visualize the values of $\alpha^{\langle t, t' \rangle}$.
To figure out where the attention values are located, let's start by printing a summary of the model .
model.summary()
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 $t = 0, \ldots, T_y-1$. Let's get the attention weights from this layer.
The function attention_map()
pulls out the attention values from your model and plots them.
attention_map = plot_attention_map(model, human_vocab, inv_machine_vocab, "Tuesday 09 Oct 1993", num = 7, n_s = 64);
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 $T_x$ to outputs of length $T_y$, where $T_x$ and $T_y$ can be different.
- You can visualize attention weights $\alpha^{\langle t,t' \rangle}$ 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.
Comments
Post a Comment