[关闭]
@mShuaiZhao 2018-02-19T14:38:25.000000Z 字数 19185 阅读 377

week03.Ng's Sequence Model Course-Homework

2018.02 Coursera


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.

Let's load all the packages you will need for this assignment.

  1. from keras.layers import Bidirectional, Concatenate, Permute, Dot, Input, LSTM, Multiply
  2. from keras.layers import RepeatVector, Dense, Activation, Lambda
  3. from keras.optimizers import Adam
  4. from keras.utils import to_categorical
  5. from keras.models import load_model, Model
  6. import keras.backend as K
  7. import numpy as np
  8. from faker import Faker
  9. import random
  10. from tqdm import tqdm
  11. from babel.dates import format_date
  12. from nmt_utils import *
  13. import matplotlib.pyplot as plt
  14. %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 even without using massive datasets, we will instead use 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") and 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 10000 human readable dates and their equivalent, standardized, machine readable dates. Let's run the following cells to load the dataset and print some examples.

  1. m = 10000
  2. dataset, human_vocab, machine_vocab, inv_machine_vocab = load_dataset(m)
  1. dataset[:10]
  2. result
  3. [('9 may 1998', '1998-05-09'),
  4. ('10.09.70', '1970-09-10'),
  5. ('4/28/90', '1990-04-28'),
  6. ('thursday january 26 1995', '1995-01-26'),
  7. ('monday march 7 1983', '1983-03-07'),
  8. ('sunday may 22 1988', '1988-05-22'),
  9. ('tuesday july 8 2008', '2008-07-08'),
  10. ('08 sep 1999', '1999-09-08'),
  11. ('1 jan 1981', '1981-01-01'),
  12. ('monday may 22 1995', '1995-05-22')]

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. These indices are not necessarily consistent with human_vocab.
- inv_machine_vocab: the inverse dictionary of machine_vocab, mapping from indices back to characters.

Let's preprocess the data and map the raw text data into the index values. We will also use Tx=30 (which we assume is the maximum length of the human readable date; if we get a longer input, we would have to truncate it) and Ty=10 (since "YYYY-MM-DD" is 10 characters long).

  1. Tx = 30
  2. Ty = 10
  3. X, Y, Xoh, Yoh = preprocess_data(dataset, human_vocab, machine_vocab, Tx, Ty)
  4. print("X.shape:", X.shape)
  5. print("Y.shape:", Y.shape)
  6. print("Xoh.shape:", Xoh.shape)
  7. print("Yoh.shape:", Yoh.shape)
  8. result:
  9. X.shape: (10000, 30)
  10. Y.shape: (10000, 10)
  11. Xoh.shape: (10000, 30, 37)
  12. Yoh.shape: (10000, 10, 11)

You now have:
- X: a processed version of the human readable dates in the training set, where each character is replaced by an index mapped to the character via human_vocab. Each date is further padded to values with a special character (< pad >). X.shape = (m, Tx)
- Y: a processed version of the machine readable dates in the training set, where each character is replaced by the index it is mapped to in machine_vocab. You should have Y.shape = (m, Ty).
- Xoh: one-hot version of X, the "1" entry's index is mapped to the character thanks to human_vocab. Xoh.shape = (m, Tx, len(human_vocab))
- Yoh: one-hot version of Y, the "1" entry's index is mapped to the character thanks to machine_vocab. Yoh.shape = (m, Tx, len(machine_vocab)). Here, len(machine_vocab) = 11 since there are 11 characters ('-' as well as 0-9).

Lets 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.

  1. index = 0
  2. print("Source date:", dataset[index][0])
  3. print("Target date:", dataset[index][1])
  4. print()
  5. print("Source after preprocessing (indices):", X[index])
  6. print("Target after preprocessing (indices):", Y[index])
  7. print()
  8. print("Source after preprocessing (one-hot):", Xoh[index])
  9. print("Target after preprocessing (one-hot):", Yoh[index])
  10. result:
  11. Source date: 9 may 1998
  12. Target date: 1998-05-09
  13. Source after preprocessing (indices): [12 0 24 13 34 0 4 12 12 11 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36
  14. 36 36 36 36 36]
  15. Target after preprocessing (indices): [ 2 10 10 9 0 1 6 0 1 10]
  16. Source after preprocessing (one-hot): [[ 0. 0. 0. ..., 0. 0. 0.]
  17. [ 1. 0. 0. ..., 0. 0. 0.]
  18. [ 0. 0. 0. ..., 0. 0. 0.]
  19. ...,
  20. [ 0. 0. 0. ..., 0. 0. 1.]
  21. [ 0. 0. 0. ..., 0. 0. 1.]
  22. [ 0. 0. 0. ..., 0. 0. 1.]]
  23. Target after preprocessing (one-hot): [[ 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
  24. [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
  25. [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
  26. [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
  27. [ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
  28. [ 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
  29. [ 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
  30. [ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
  31. [ 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
  32. [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]

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 , which are used to compute the context variable for each timestep in the output ().

attn_model.png-271.1kB
attn_mechanism.png-168.4kB

Figure 1: Neural machine translation with attention

Here are some properties of the model that you may notice:

Lets implement this model. You will start by implementing two functions: one_step_attention() and model().

1) one_step_attention(): At step , given all the hidden states of the Bi-LSTM () and the previous hidden state of the second LSTM (), one_step_attention() will compute the attention weights () and output the context vector (see Figure 1 (right) for details):

Note that we are denoting the attention in this notebook . In the lecture videos, the context was denoted , but here we are calling it to avoid confusion with the (post-attention) LSTM's internal memory cell variable, which is sometimes also denoted .

2) model(): Implements the entire model. It first runs the input through a Bi-LSTM to get back . Then, it calls one_step_attention() times (for loop). At each iteration of this loop, it gives the computed context vector to the second LSTM, and runs the output of the LSTM through a dense layer with softmax activation to generate a prediction .

Exercise: Implement one_step_attention(). The function model() will call the layers in one_step_attention() using a for-loop, and it is important that all copies have the same weights. I.e., it should not re-initiaiize 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:
1. Define the layer objects (as global variables for examples).
2. 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 check the Keras documentation to make sure you understand what these layers are: RepeatVector(), Concatenate(), Dense(), Activation(), Dot().

  1. # Defined shared layers as global variables
  2. repeator = RepeatVector(Tx)
  3. concatenator = Concatenate(axis=-1)
  4. densor1 = Dense(10, activation = "tanh")
  5. densor2 = Dense(1, activation = "relu")
  6. activator = Activation(softmax, name='attention_weights') # We are using a custom softmax(axis = 1) loaded in this notebook
  7. dotor = Dot(axes = 1)

Now you can use these layers to implement one_step_attention(). In order to propagate a Keras tensor object X through one of these layers, use layer(X) (or layer([X,Y]) if it requires multiple inputs.), e.g. densor(X) will propagate X through the Dense(1) layer defined above.

  1. # GRADED FUNCTION: one_step_attention
  2. def one_step_attention(a, s_prev):
  3. """
  4. Performs one step of attention: Outputs a context vector computed as a dot product of the attention weights
  5. "alphas" and the hidden states "a" of the Bi-LSTM.
  6. Arguments:
  7. a -- hidden state output of the Bi-LSTM, numpy-array of shape (m, Tx, 2*n_a)
  8. s_prev -- previous hidden state of the (post-attention) LSTM, numpy-array of shape (m, n_s)
  9. Returns:
  10. context -- context vector, input of the next (post-attetion) LSTM cell
  11. """
  12. ### START CODE HERE ###
  13. # m, Tx, na_2 = a.shape
  14. # Use repeator to repeat s_prev to be of shape (m, Tx, n_s) so that you can concatenate it with all hidden states "a" (≈ 1 line)
  15. s_prev = repeator(s_prev)
  16. # Use concatenator to concatenate a and s_prev on the last axis (≈ 1 line)
  17. concat = concatenator([a, s_prev])
  18. # Use densor1 to propagate concat through a small fully-connected neural network to compute the "intermediate energies" variable e. (≈1 lines)
  19. e = densor1(concat)
  20. # Use densor2 to propagate e through a small fully-connected neural network to compute the "energies" variable energies. (≈1 lines)
  21. energies = densor2(e)
  22. # Use "activator" on "energies" to compute the attention weights "alphas" (≈ 1 line)
  23. alphas = activator(energies)
  24. # Use dotor together with "alphas" and "a" to compute the context vector to be given to the next (post-attention) LSTM-cell (≈ 1 line)
  25. context = dotor([alphas, a])
  26. ### END CODE HERE ###
  27. return context

You will be able to check the expected output of one_step_attention() after you've coded the model() function.

Exercise: Implement model() as explained in figure 2 and the text above. Again, we have defined global layers that will share weights to be used in model().

  1. n_a = 32
  2. n_s = 64
  3. post_activation_LSTM_cell = LSTM(n_s, return_state = True)
  4. output_layer = Dense(len(machine_vocab), activation=softmax)

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:

  1. Propagate the input into a Bidirectional LSTM
  2. Iterate for :

    1. Call one_step_attention() on and to get the context vector .
    2. Give to the post-attention LSTM cell. Remember pass in the previous hidden-state and cell-states of this LSTM using initial_state= [previous hidden state, previous cell state]. Get back the new hidden state and the new cell state .
    3. Apply a softmax layer to , get the output.
    4. Save the output by adding it to the list of outputs.
  3. Create your Keras model instance, it should have three inputs ("inputs", and ) and output the list of "outputs".

  1. # GRADED FUNCTION: model
  2. def model(Tx, Ty, n_a, n_s, human_vocab_size, machine_vocab_size):
  3. """
  4. Arguments:
  5. Tx -- length of the input sequence
  6. Ty -- length of the output sequence
  7. n_a -- hidden state size of the Bi-LSTM
  8. n_s -- hidden state size of the post-attention LSTM
  9. human_vocab_size -- size of the python dictionary "human_vocab"
  10. machine_vocab_size -- size of the python dictionary "machine_vocab"
  11. Returns:
  12. model -- Keras model instance
  13. """
  14. # Define the inputs of your model with a shape (Tx,)
  15. # Define s0 and c0, initial hidden state for the decoder LSTM of shape (n_s,)
  16. X = Input(shape=(Tx, human_vocab_size))
  17. s0 = Input(shape=(n_s,), name='s0')
  18. c0 = Input(shape=(n_s,), name='c0')
  19. s = s0
  20. c = c0
  21. # Initialize empty list of outputs
  22. outputs = []
  23. ### START CODE HERE ###
  24. # Step 1: Define your pre-attention Bi-LSTM. Remember to use return_sequences=True. (≈ 1 line)
  25. a = Bidirectional(LSTM(n_a, return_sequences = True))(X)
  26. # Step 2: Iterate for Ty steps
  27. for t in range(Ty):
  28. # Step 2.A: Perform one step of the attention mechanism to get back the context vector at step t (≈ 1 line)
  29. context = one_step_attention(a, s)
  30. # Step 2.B: Apply the post-attention LSTM cell to the "context" vector.
  31. # Don't forget to pass: initial_state = [hidden state, cell state] (≈ 1 line)
  32. s, _, c = post_activation_LSTM_cell(inputs = context, initial_state = [s, c])
  33. # Step 2.C: Apply Dense layer to the hidden state output of the post-attention LSTM (≈ 1 line)
  34. out = output_layer(s)
  35. # Step 2.D: Append "out" to the "outputs" list (≈ 1 line)
  36. outputs.append(out)
  37. # Step 3: Create model instance taking three inputs and returning the list of outputs. (≈ 1 line)
  38. model = Model(inputs = [X, s0, c0], outputs = outputs)
  39. ### END CODE HERE ###
  40. return model

Run the following cell to create your model.

  1. model = model(Tx, Ty, n_a, n_s, len(human_vocab), len(machine_vocab))

Let's get a summary of the model to check if it matches the expected output.

  1. model.summary()
  2. result:
  3. Layer (type) Output Shape Param # Connected to
  4. ====================================================================================================
  5. input_7 (InputLayer) (None, 30, 37) 0
  6. ____________________________________________________________________________________________________
  7. s0 (InputLayer) (None, 64) 0
  8. ____________________________________________________________________________________________________
  9. bidirectional_7 (Bidirectional) (None, 30, 64) 17920 input_7[0][0]
  10. ____________________________________________________________________________________________________
  11. repeat_vector_3 (RepeatVector) (None, 30, 64) 0 s0[0][0]
  12. lstm_11[0][0]
  13. lstm_11[1][0]
  14. lstm_11[2][0]
  15. lstm_11[3][0]
  16. lstm_11[4][0]
  17. lstm_11[5][0]
  18. lstm_11[6][0]
  19. lstm_11[7][0]
  20. lstm_11[8][0]
  21. ____________________________________________________________________________________________________
  22. concatenate_3 (Concatenate) (None, 30, 128) 0 bidirectional_7[0][0]
  23. repeat_vector_3[0][0]
  24. bidirectional_7[0][0]
  25. repeat_vector_3[1][0]
  26. bidirectional_7[0][0]
  27. repeat_vector_3[2][0]
  28. bidirectional_7[0][0]
  29. repeat_vector_3[3][0]
  30. bidirectional_7[0][0]
  31. repeat_vector_3[4][0]
  32. bidirectional_7[0][0]
  33. repeat_vector_3[5][0]
  34. bidirectional_7[0][0]
  35. repeat_vector_3[6][0]
  36. bidirectional_7[0][0]
  37. repeat_vector_3[7][0]
  38. bidirectional_7[0][0]
  39. repeat_vector_3[8][0]
  40. bidirectional_7[0][0]
  41. repeat_vector_3[9][0]
  42. ____________________________________________________________________________________________________
  43. dense_9 (Dense) (None, 30, 10) 1290 concatenate_3[0][0]
  44. concatenate_3[1][0]
  45. concatenate_3[2][0]
  46. concatenate_3[3][0]
  47. concatenate_3[4][0]
  48. concatenate_3[5][0]
  49. concatenate_3[6][0]
  50. concatenate_3[7][0]
  51. concatenate_3[8][0]
  52. concatenate_3[9][0]
  53. ____________________________________________________________________________________________________
  54. dense_10 (Dense) (None, 30, 1) 11 dense_9[0][0]
  55. dense_9[1][0]
  56. dense_9[2][0]
  57. dense_9[3][0]
  58. dense_9[4][0]
  59. dense_9[5][0]
  60. dense_9[6][0]
  61. dense_9[7][0]
  62. dense_9[8][0]
  63. dense_9[9][0]
  64. ____________________________________________________________________________________________________
  65. attention_weights (Activation) (None, 30, 1) 0 dense_10[0][0]
  66. dense_10[1][0]
  67. dense_10[2][0]
  68. dense_10[3][0]
  69. dense_10[4][0]
  70. dense_10[5][0]
  71. dense_10[6][0]
  72. dense_10[7][0]
  73. dense_10[8][0]
  74. dense_10[9][0]
  75. ____________________________________________________________________________________________________
  76. dot_3 (Dot) (None, 1, 64) 0 attention_weights[0][0]
  77. bidirectional_7[0][0]
  78. attention_weights[1][0]
  79. bidirectional_7[0][0]
  80. attention_weights[2][0]
  81. bidirectional_7[0][0]
  82. attention_weights[3][0]
  83. bidirectional_7[0][0]
  84. attention_weights[4][0]
  85. bidirectional_7[0][0]
  86. attention_weights[5][0]
  87. bidirectional_7[0][0]
  88. attention_weights[6][0]
  89. bidirectional_7[0][0]
  90. attention_weights[7][0]
  91. bidirectional_7[0][0]
  92. attention_weights[8][0]
  93. bidirectional_7[0][0]
  94. attention_weights[9][0]
  95. bidirectional_7[0][0]
  96. ____________________________________________________________________________________________________
  97. c0 (InputLayer) (None, 64) 0
  98. ____________________________________________________________________________________________________
  99. lstm_11 (LSTM) [(None, 64), (None, 6 33024 dot_3[0][0]
  100. s0[0][0]
  101. c0[0][0]
  102. dot_3[1][0]
  103. lstm_11[0][0]
  104. lstm_11[0][2]
  105. dot_3[2][0]
  106. lstm_11[1][0]
  107. lstm_11[1][2]
  108. dot_3[3][0]
  109. lstm_11[2][0]
  110. lstm_11[2][2]
  111. dot_3[4][0]
  112. lstm_11[3][0]
  113. lstm_11[3][2]
  114. dot_3[5][0]
  115. lstm_11[4][0]
  116. lstm_11[4][2]
  117. dot_3[6][0]
  118. lstm_11[5][0]
  119. lstm_11[5][2]
  120. dot_3[7][0]
  121. lstm_11[6][0]
  122. lstm_11[6][2]
  123. dot_3[8][0]
  124. lstm_11[7][0]
  125. lstm_11[7][2]
  126. dot_3[9][0]
  127. lstm_11[8][0]
  128. lstm_11[8][2]
  129. ____________________________________________________________________________________________________
  130. dense_11 (Dense) (None, 11) 715 lstm_11[0][0]
  131. lstm_11[1][0]
  132. lstm_11[2][0]
  133. lstm_11[3][0]
  134. lstm_11[4][0]
  135. lstm_11[5][0]
  136. lstm_11[6][0]
  137. lstm_11[7][0]
  138. lstm_11[8][0]
  139. lstm_11[9][0]
  140. ====================================================================================================
  141. Total params: 52,960
  142. Trainable params: 52,960
  143. Non-trainable params: 0

这个expected output真的很不靠谱啊。

As usual, after creating your model in Keras, you need to compile it and define what loss, optimizer and metrics your are want to use. Compile your model using categorical_crossentropy loss, a custom Adam optimizer (learning rate = 0.005, , , decay = 0.01) and ['accuracy'] metrics:

  1. ### START CODE HERE ### (≈2 lines)
  2. opt = Adam(lr=0.005, beta_1=0.9, beta_2=0.999, decay=0.01)
  3. model.compile(loss='categorical_crossentropy', optimizer = opt)
  4. ### END CODE HERE ###

The last step is to define all your inputs and outputs to fit the model:
- You already have X of shape containing the training examples.
- You need to create s0 and c0 to initialize your post_activation_LSTM_cell with 0s.
- Given the model() you coded, you need the "outputs" to be a list of 11 elements of shape (m, T_y). So that: outputs[i][0], ..., outputs[i][Ty] represent the true labels (characters) corresponding to the training example (X[i]). More generally, outputs[i][j] is the true label of the character in the training example.

Congratulations!

You have come to the end of this assignment

Here's what you should remember from this notebook:

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注