wesfggfd commited on
Commit
0b8419e
·
verified ·
1 Parent(s): 502e7a3

Upload 15 files

Browse files
Files changed (16) hide show
  1. .gitattributes +4 -0
  2. Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/.ipynb_checkpoints/Neural_machine_translation_with_attention_v4a-checkpoint.ipynb +1390 -0
  3. Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/Neural_machine_translation_with_attention_v4a.ipynb +0 -0
  4. Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/__pycache__/nmt_utils.cpython-37.pyc +0 -0
  5. Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/__pycache__/test_utils.cpython-37.pyc +0 -0
  6. Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/expected_output_ex1.npy +3 -0
  7. Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/generateTestCases.py +97 -0
  8. Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/attn_mechanism.png +3 -0
  9. Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/attn_model.png +3 -0
  10. Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/date_attention.png +3 -0
  11. Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/date_attention2.png +3 -0
  12. Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/poorly_trained_model.png +0 -0
  13. Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/table.png +0 -0
  14. Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/models/model.h5 +3 -0
  15. Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/nmt_utils.py +289 -0
  16. Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/test_utils.py +57 -0
.gitattributes CHANGED
@@ -72,3 +72,7 @@ Word_Representation/many_to_one_prediction_for_emoji/home/jovyan/work/W2A2/image
72
  Word_Representation/many_to_one_prediction_for_emoji/home/jovyan/work/W2A2/images/emojiss.png filter=lfs diff=lfs merge=lfs -text
73
  Word_Representation/many_to_one_prediction_for_emoji/home/jovyan/work/W2A2/images/image_1.png filter=lfs diff=lfs merge=lfs -text
74
  Word_Representation/many_to_one_prediction_for_emoji/home/jovyan/work/W2A2/images/woebot.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
72
  Word_Representation/many_to_one_prediction_for_emoji/home/jovyan/work/W2A2/images/emojiss.png filter=lfs diff=lfs merge=lfs -text
73
  Word_Representation/many_to_one_prediction_for_emoji/home/jovyan/work/W2A2/images/image_1.png filter=lfs diff=lfs merge=lfs -text
74
  Word_Representation/many_to_one_prediction_for_emoji/home/jovyan/work/W2A2/images/woebot.png filter=lfs diff=lfs merge=lfs -text
75
+ Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/attn_mechanism.png filter=lfs diff=lfs merge=lfs -text
76
+ Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/attn_model.png filter=lfs diff=lfs merge=lfs -text
77
+ Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/date_attention.png filter=lfs diff=lfs merge=lfs -text
78
+ Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/date_attention2.png filter=lfs diff=lfs merge=lfs -text
Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/.ipynb_checkpoints/Neural_machine_translation_with_attention_v4a-checkpoint.ipynb ADDED
@@ -0,0 +1,1390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "adTDe2CTh3MU"
7
+ },
8
+ "source": [
9
+ "# Neural Machine Translation\n",
10
+ "\n",
11
+ "Welcome to your first programming assignment for this week! \n",
12
+ "\n",
13
+ "* 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\"). \n",
14
+ "* You will do this using an attention model, one of the most sophisticated sequence-to-sequence models. \n",
15
+ "\n",
16
+ "This notebook was produced together with NVIDIA's Deep Learning Institute. \n",
17
+ "\n",
18
+ "## Important Note on Submission to the AutoGrader\n",
19
+ "\n",
20
+ "Before submitting your assignment to the AutoGrader, please make sure you are not doing the following:\n",
21
+ "\n",
22
+ "1. You have not added any _extra_ `print` statement(s) in the assignment.\n",
23
+ "2. You have not added any _extra_ code cell(s) in the assignment.\n",
24
+ "3. You have not changed any of the function parameters.\n",
25
+ "4. 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.\n",
26
+ "5. You are not changing the assignment code where it is not required, like creating _extra_ variables.\n",
27
+ "\n",
28
+ "If you do any of the following, you will get something like, `Grader Error: Grader feedback 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](https://www.coursera.org/learn/nlp-sequence-models/supplement/qHIve/h-ow-to-refresh-your-workspace)."
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "markdown",
33
+ "metadata": {
34
+ "id": "0LCkjDBFh3Md"
35
+ },
36
+ "source": [
37
+ "## Table of Contents\n",
38
+ "\n",
39
+ "- [Packages](#0)\n",
40
+ "- [1 - Translating Human Readable Dates Into Machine Readable Dates](#1)\n",
41
+ " - [1.1 - Dataset](#1-1)\n",
42
+ "- [2 - Neural Machine Translation with Attention](#2)\n",
43
+ " - [2.1 - Attention Mechanism](#2-1)\n",
44
+ " - [Exercise 1 - one_step_attention](#ex-1)\n",
45
+ " - [Exercise 2 - modelf](#ex-2)\n",
46
+ " - [Exercise 3 - Compile the Model](#ex-3)\n",
47
+ "- [3 - Visualizing Attention (Optional / Ungraded)](#3)\n",
48
+ " - [3.1 - Getting the Attention Weights From the Network](#3-1)"
49
+ ]
50
+ },
51
+ {
52
+ "cell_type": "markdown",
53
+ "metadata": {},
54
+ "source": [
55
+ "<a name='0'></a>\n",
56
+ "## Packages"
57
+ ]
58
+ },
59
+ {
60
+ "cell_type": "code",
61
+ "execution_count": null,
62
+ "metadata": {
63
+ "deletable": false,
64
+ "editable": false
65
+ },
66
+ "outputs": [],
67
+ "source": [
68
+ "### v3.1"
69
+ ]
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "execution_count": null,
74
+ "metadata": {
75
+ "colab": {
76
+ "base_uri": "https://localhost:8080/"
77
+ },
78
+ "executionInfo": {
79
+ "elapsed": 14508,
80
+ "status": "ok",
81
+ "timestamp": 1612468511651,
82
+ "user": {
83
+ "displayName": "Mubsi K",
84
+ "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64",
85
+ "userId": "08094225471505108399"
86
+ },
87
+ "user_tz": -300
88
+ },
89
+ "id": "RcBRMzPiiMmp",
90
+ "outputId": "17e9a429-5bb6-4401-a23a-f8f756d6113d"
91
+ },
92
+ "outputs": [],
93
+ "source": [
94
+ "from tensorflow.keras.layers import Bidirectional, Concatenate, Permute, Dot, Input, LSTM, Multiply\n",
95
+ "from tensorflow.keras.layers import RepeatVector, Dense, Activation, Lambda\n",
96
+ "from tensorflow.keras.optimizers import Adam\n",
97
+ "from tensorflow.keras.utils import to_categorical\n",
98
+ "from tensorflow.keras.models import load_model, Model\n",
99
+ "import tensorflow.keras.backend as K\n",
100
+ "import tensorflow as tf\n",
101
+ "import numpy as np\n",
102
+ "\n",
103
+ "from faker import Faker\n",
104
+ "import random\n",
105
+ "from tqdm import tqdm\n",
106
+ "from babel.dates import format_date\n",
107
+ "from nmt_utils import *\n",
108
+ "import matplotlib.pyplot as plt\n",
109
+ "%matplotlib inline"
110
+ ]
111
+ },
112
+ {
113
+ "cell_type": "markdown",
114
+ "metadata": {
115
+ "id": "J0pkH-k0h3Mf"
116
+ },
117
+ "source": [
118
+ "<a name='1'></a>\n",
119
+ "## 1 - Translating Human Readable Dates Into Machine Readable Dates\n",
120
+ "\n",
121
+ "* The model you will build here could be used to translate from one language to another, such as translating from English to Hindi. \n",
122
+ "* However, language translation requires massive datasets and usually takes days of training on GPUs. \n",
123
+ "* To give you a place to experiment with these models without using massive datasets, we will perform a simpler \"date translation\" task. \n",
124
+ "* 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\"*) \n",
125
+ "* The network will translate them into standardized, machine readable dates (*e.g. \"1958-08-29\", \"1968-03-30\", \"1987-06-24\"*). \n",
126
+ "* We will have the network learn to output dates in the common machine-readable format YYYY-MM-DD. \n",
127
+ "\n",
128
+ "<!-- \n",
129
+ "Take a look at [nmt_utils.py](./nmt_utils.py) to see all the formatting. Count and figure out how the formats work, you will need this knowledge later. !--> "
130
+ ]
131
+ },
132
+ {
133
+ "cell_type": "markdown",
134
+ "metadata": {
135
+ "id": "8BhEaJvph3Mf"
136
+ },
137
+ "source": [
138
+ "<a name='1-1'></a>\n",
139
+ "### 1.1 - Dataset\n",
140
+ "\n",
141
+ "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. "
142
+ ]
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "execution_count": null,
147
+ "metadata": {
148
+ "colab": {
149
+ "base_uri": "https://localhost:8080/"
150
+ },
151
+ "executionInfo": {
152
+ "elapsed": 16981,
153
+ "status": "ok",
154
+ "timestamp": 1612468514155,
155
+ "user": {
156
+ "displayName": "Mubsi K",
157
+ "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64",
158
+ "userId": "08094225471505108399"
159
+ },
160
+ "user_tz": -300
161
+ },
162
+ "id": "gwIf5l17h3Mg",
163
+ "outputId": "1fca5fb8-3a9b-4a78-f726-7aef8e14ee41"
164
+ },
165
+ "outputs": [],
166
+ "source": [
167
+ "m = 10000\n",
168
+ "dataset, human_vocab, machine_vocab, inv_machine_vocab = load_dataset(m)"
169
+ ]
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "execution_count": null,
174
+ "metadata": {
175
+ "colab": {
176
+ "base_uri": "https://localhost:8080/"
177
+ },
178
+ "executionInfo": {
179
+ "elapsed": 16972,
180
+ "status": "ok",
181
+ "timestamp": 1612468514156,
182
+ "user": {
183
+ "displayName": "Mubsi K",
184
+ "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64",
185
+ "userId": "08094225471505108399"
186
+ },
187
+ "user_tz": -300
188
+ },
189
+ "id": "zCTqMyPch3Mg",
190
+ "outputId": "42c9d8aa-d07b-4618-ab8a-4db4e1b971e2"
191
+ },
192
+ "outputs": [],
193
+ "source": [
194
+ "dataset[:10]"
195
+ ]
196
+ },
197
+ {
198
+ "cell_type": "markdown",
199
+ "metadata": {
200
+ "id": "ao4Ffrkxh3Mg"
201
+ },
202
+ "source": [
203
+ "You've loaded:\n",
204
+ "- `dataset`: a list of tuples of (human readable date, machine readable date).\n",
205
+ "- `human_vocab`: a python dictionary mapping all characters used in the human readable dates to an integer-valued index.\n",
206
+ "- `machine_vocab`: a python dictionary mapping all characters used in machine readable dates to an integer-valued index. \n",
207
+ " - **Note**: These indices are not necessarily consistent with `human_vocab`. \n",
208
+ "- `inv_machine_vocab`: the inverse dictionary of `machine_vocab`, mapping from indices back to characters. \n",
209
+ "\n",
210
+ "Let's preprocess the data and map the raw text data into the index values. \n",
211
+ "- We will set Tx=30 \n",
212
+ " - We assume Tx is the maximum length of the human readable date.\n",
213
+ " - If we get a longer input, we would have to truncate it.\n",
214
+ "- We will set Ty=10\n",
215
+ " - \"YYYY-MM-DD\" is 10 characters long."
216
+ ]
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "execution_count": null,
221
+ "metadata": {
222
+ "colab": {
223
+ "base_uri": "https://localhost:8080/"
224
+ },
225
+ "executionInfo": {
226
+ "elapsed": 16962,
227
+ "status": "ok",
228
+ "timestamp": 1612468514157,
229
+ "user": {
230
+ "displayName": "Mubsi K",
231
+ "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64",
232
+ "userId": "08094225471505108399"
233
+ },
234
+ "user_tz": -300
235
+ },
236
+ "id": "Qdso90EBh3Mg",
237
+ "outputId": "0a364ad8-8b25-4de3-f036-d5d8e40bdf8c"
238
+ },
239
+ "outputs": [],
240
+ "source": [
241
+ "Tx = 30\n",
242
+ "Ty = 10\n",
243
+ "X, Y, Xoh, Yoh = preprocess_data(dataset, human_vocab, machine_vocab, Tx, Ty)\n",
244
+ "\n",
245
+ "print(\"X.shape:\", X.shape)\n",
246
+ "print(\"Y.shape:\", Y.shape)\n",
247
+ "print(\"Xoh.shape:\", Xoh.shape)\n",
248
+ "print(\"Yoh.shape:\", Yoh.shape)"
249
+ ]
250
+ },
251
+ {
252
+ "cell_type": "markdown",
253
+ "metadata": {
254
+ "id": "q9C0UY25h3Mh"
255
+ },
256
+ "source": [
257
+ "You now have:\n",
258
+ "- `X`: a processed version of the human readable dates in the training set.\n",
259
+ " - Each character in X is replaced by an index (integer) mapped to the character using `human_vocab`. \n",
260
+ " - Each date is padded to ensure a length of $T_x$ using a special character (< pad >). \n",
261
+ " - `X.shape = (m, Tx)` where m is the number of training examples in a batch.\n",
262
+ "- `Y`: a processed version of the machine readable dates in the training set.\n",
263
+ " - Each character is replaced by the index (integer) it is mapped to in `machine_vocab`. \n",
264
+ " - `Y.shape = (m, Ty)`. \n",
265
+ "- `Xoh`: one-hot version of `X`\n",
266
+ " - 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.\n",
267
+ " - `Xoh.shape = (m, Tx, len(human_vocab))`\n",
268
+ "- `Yoh`: one-hot version of `Y`\n",
269
+ " - Each index in `Y` is converted to the one-hot representation. \n",
270
+ " - `Yoh.shape = (m, Ty, len(machine_vocab))`. \n",
271
+ " - `len(machine_vocab) = 11` since there are 10 numeric digits (0 to 9) and the `-` symbol."
272
+ ]
273
+ },
274
+ {
275
+ "cell_type": "markdown",
276
+ "metadata": {
277
+ "id": "N7qKvWrTh3Mh"
278
+ },
279
+ "source": [
280
+ "* Let's also look at some examples of preprocessed training examples. \n",
281
+ "* Feel free to play with `index` in the cell below to navigate the dataset and see how source/target dates are preprocessed. "
282
+ ]
283
+ },
284
+ {
285
+ "cell_type": "code",
286
+ "execution_count": null,
287
+ "metadata": {
288
+ "colab": {
289
+ "base_uri": "https://localhost:8080/"
290
+ },
291
+ "executionInfo": {
292
+ "elapsed": 16952,
293
+ "status": "ok",
294
+ "timestamp": 1612468514158,
295
+ "user": {
296
+ "displayName": "Mubsi K",
297
+ "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64",
298
+ "userId": "08094225471505108399"
299
+ },
300
+ "user_tz": -300
301
+ },
302
+ "id": "kUOayR4gh3Mh",
303
+ "outputId": "d20994de-bbea-4cc7-ffaf-38a05974c9db"
304
+ },
305
+ "outputs": [],
306
+ "source": [
307
+ "index = 0\n",
308
+ "print(\"Source date:\", dataset[index][0])\n",
309
+ "print(\"Target date:\", dataset[index][1])\n",
310
+ "print()\n",
311
+ "print(\"Source after preprocessing (indices):\", X[index])\n",
312
+ "print(\"Target after preprocessing (indices):\", Y[index])\n",
313
+ "print()\n",
314
+ "print(\"Source after preprocessing (one-hot):\", Xoh[index])\n",
315
+ "print(\"Target after preprocessing (one-hot):\", Yoh[index])"
316
+ ]
317
+ },
318
+ {
319
+ "cell_type": "markdown",
320
+ "metadata": {
321
+ "id": "94o4RYbOh3Mi"
322
+ },
323
+ "source": [
324
+ "<a name='2'></a>\n",
325
+ "## 2 - Neural Machine Translation with Attention\n",
326
+ "\n",
327
+ "* 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. \n",
328
+ "* 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. \n",
329
+ "* The attention mechanism tells a Neural Machine Translation model where it should pay attention to at any step. \n",
330
+ "\n",
331
+ "<a name='2-1'></a>\n",
332
+ "### 2.1 - Attention Mechanism\n",
333
+ "\n",
334
+ "In this part, you will implement the attention mechanism presented in the lecture videos. \n",
335
+ "* Here is a figure to remind you how the model works. \n",
336
+ " * The diagram on the left shows the attention model. \n",
337
+ " * The diagram on the right shows what one \"attention\" step does to calculate the attention variables $\\alpha^{\\langle t, t' \\rangle}$.\n",
338
+ " * 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$). \n",
339
+ "\n",
340
+ "<table>\n",
341
+ "<td> \n",
342
+ "<img src=\"images/attn_model.png\" style=\"width:500;height:500px;\"> <br>\n",
343
+ "</td> \n",
344
+ "<td> \n",
345
+ "<img src=\"images/attn_mechanism.png\" style=\"width:500;height:500px;\"> <br>\n",
346
+ "</td> \n",
347
+ "</table>\n",
348
+ "<caption><center> **Figure 1**: Neural machine translation with attention</center></caption>\n"
349
+ ]
350
+ },
351
+ {
352
+ "cell_type": "markdown",
353
+ "metadata": {
354
+ "id": "b2TkQnykh3Mi"
355
+ },
356
+ "source": [
357
+ "Here are some properties of the model that you may notice: \n",
358
+ "\n",
359
+ "#### Pre-attention and Post-attention LSTMs on both sides of the attention mechanism\n",
360
+ "- There are two separate LSTMs in this model (see diagram on the left): pre-attention and post-attention LSTMs.\n",
361
+ "- *Pre-attention* Bi-LSTM is the one at the bottom of the picture is a Bi-directional LSTM and comes *before* the attention mechanism.\n",
362
+ " - The attention mechanism is shown in the middle of the left-hand diagram.\n",
363
+ " - The pre-attention Bi-LSTM goes through $T_x$ time steps\n",
364
+ "- *Post-attention* LSTM: at the top of the diagram comes *after* the attention mechanism. \n",
365
+ " - The post-attention LSTM goes through $T_y$ time steps. \n",
366
+ "\n",
367
+ "- The post-attention LSTM passes the hidden state $s^{\\langle t \\rangle}$ and cell state $c^{\\langle t \\rangle}$ from one time step to the next. "
368
+ ]
369
+ },
370
+ {
371
+ "cell_type": "markdown",
372
+ "metadata": {
373
+ "id": "JpznWuWqh3Mi"
374
+ },
375
+ "source": [
376
+ "#### An LSTM has both a hidden state and cell state\n",
377
+ "* In the lecture videos, we were using only a basic RNN for the post-attention sequence model\n",
378
+ " * This means that the state captured by the RNN was outputting only the hidden state $s^{\\langle t\\rangle}$. \n",
379
+ "* In this assignment, we are using an LSTM instead of a basic RNN.\n",
380
+ " * So the LSTM has both the hidden state $s^{\\langle t\\rangle}$ and the cell state $c^{\\langle t\\rangle}$. "
381
+ ]
382
+ },
383
+ {
384
+ "cell_type": "markdown",
385
+ "metadata": {
386
+ "id": "85btUzl4h3Mj"
387
+ },
388
+ "source": [
389
+ "#### Each time step does not use predictions from the previous time step\n",
390
+ "* Unlike previous text generation examples earlier in the course, in this model, the post-attention LSTM at time $t$ does not take the previous time step's prediction $y^{\\langle t-1 \\rangle}$ as input.\n",
391
+ "* The post-attention LSTM at time 't' only takes the hidden state $s^{\\langle t\\rangle}$ and cell state $c^{\\langle t\\rangle}$ as input. \n",
392
+ "* 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."
393
+ ]
394
+ },
395
+ {
396
+ "cell_type": "markdown",
397
+ "metadata": {
398
+ "id": "NYT3v7rUh3Mk"
399
+ },
400
+ "source": [
401
+ "#### Concatenation of hidden states from the forward and backward pre-attention LSTMs\n",
402
+ "- $\\overrightarrow{a}^{\\langle t \\rangle}$: hidden state of the forward-direction, pre-attention LSTM.\n",
403
+ "- $\\overleftarrow{a}^{\\langle t \\rangle}$: hidden state of the backward-direction, pre-attention LSTM.\n",
404
+ "- $a^{\\langle t \\rangle} = [\\overrightarrow{a}^{\\langle t \\rangle}, \\overleftarrow{a}^{\\langle t \\rangle}]$: the concatenation of the activations of both the forward-direction $\\overrightarrow{a}^{\\langle t \\rangle}$ and backward-directions $\\overleftarrow{a}^{\\langle t \\rangle}$ of the pre-attention Bi-LSTM. "
405
+ ]
406
+ },
407
+ {
408
+ "cell_type": "markdown",
409
+ "metadata": {
410
+ "id": "97GUKCqwh3Mk"
411
+ },
412
+ "source": [
413
+ "#### Computing \"energies\" $e^{\\langle t, t' \\rangle}$ as a function of $s^{\\langle t-1 \\rangle}$ and $a^{\\langle t' \\rangle}$\n",
414
+ "- Recall in the lesson videos \"Attention Model\", at time 6:45 to 8:16, the definition of \"e\" as a function of $s^{\\langle t-1 \\rangle}$ and $a^{\\langle t \\rangle}$.\n",
415
+ " - \"e\" is called the \"energies\" variable.\n",
416
+ " - $s^{\\langle t-1 \\rangle}$ is the hidden state of the post-attention LSTM\n",
417
+ " - $a^{\\langle t' \\rangle}$ is the hidden state of the pre-attention LSTM.\n",
418
+ " - $s^{\\langle t-1 \\rangle}$ and $a^{\\langle t \\rangle}$ are fed into a simple neural network, which learns the function to output $e^{\\langle t, t' \\rangle}$.\n",
419
+ " - $e^{\\langle t, t' \\rangle}$ is then used when computing the attention $\\alpha^{\\langle t, t' \\rangle}$ that $y^{\\langle t \\rangle}$ should pay to $a^{\\langle t' \\rangle}$."
420
+ ]
421
+ },
422
+ {
423
+ "cell_type": "markdown",
424
+ "metadata": {
425
+ "id": "scu_HnPNh3Mk"
426
+ },
427
+ "source": [
428
+ "- The diagram on the right of figure 1 uses a `RepeatVector` node to copy $s^{\\langle t-1 \\rangle}$'s value $T_x$ times.\n",
429
+ "- Then it uses `Concatenation` to concatenate $s^{\\langle t-1 \\rangle}$ and $a^{\\langle t \\rangle}$.\n",
430
+ "- The concatenation of $s^{\\langle t-1 \\rangle}$ and $a^{\\langle t \\rangle}$ is fed into a \"Dense\" layer, which computes $e^{\\langle t, t' \\rangle}$. \n",
431
+ "- $e^{\\langle t, t' \\rangle}$ is then passed through a softmax to compute $\\alpha^{\\langle t, t' \\rangle}$.\n",
432
+ "- Note that the diagram doesn't explicitly show variable $e^{\\langle t, t' \\rangle}$, but $e^{\\langle t, t' \\rangle}$ is above the Dense layer and below the Softmax layer in the diagram in the right half of figure 1.\n",
433
+ "- We'll explain how to use `RepeatVector` and `Concatenation` in Keras below. "
434
+ ]
435
+ },
436
+ {
437
+ "cell_type": "markdown",
438
+ "metadata": {
439
+ "id": "_ukmqe_Yh3Ml"
440
+ },
441
+ "source": [
442
+ "#### Implementation Details\n",
443
+ " \n",
444
+ "Let's implement this neural translator. You will start by implementing two functions: `one_step_attention()` and `model()`.\n",
445
+ "\n",
446
+ "#### one_step_attention\n",
447
+ "* The inputs to the one_step_attention at time step $t$ are:\n",
448
+ " - $[a^{<1>},a^{<2>}, ..., a^{<T_x>}]$: all hidden states of the pre-attention Bi-LSTM.\n",
449
+ " - $s^{<t-1>}$: the previous hidden state of the post-attention LSTM \n",
450
+ "* one_step_attention computes:\n",
451
+ " - $[\\alpha^{<t,1>},\\alpha^{<t,2>}, ..., \\alpha^{<t,T_x>}]$: the attention weights\n",
452
+ " - $context^{ \\langle t \\rangle }$: the context vector:\n",
453
+ " \n",
454
+ "$$context^{<t>} = \\sum_{t' = 1}^{T_x} \\alpha^{<t,t'>}a^{<t'>}\\tag{1}$$ \n",
455
+ "\n",
456
+ "##### Clarifying 'context' and 'c'\n",
457
+ "- In the lecture videos, the context was denoted $c^{\\langle t \\rangle}$\n",
458
+ "- In the assignment, we are calling the context $context^{\\langle t \\rangle}$.\n",
459
+ " - This is to avoid confusion with the post-attention LSTM's internal memory cell variable, which is also denoted $c^{\\langle t \\rangle}$."
460
+ ]
461
+ },
462
+ {
463
+ "cell_type": "markdown",
464
+ "metadata": {
465
+ "id": "LIfLKkwoh3Ml"
466
+ },
467
+ "source": [
468
+ "<a name='ex-1'></a>\n",
469
+ "### Exercise 1 - one_step_attention \n",
470
+ "\n",
471
+ "Implement `one_step_attention()`. \n",
472
+ "\n",
473
+ "* The function `model()` will call the layers in `one_step_attention()` $T_y$ times using a for-loop.\n",
474
+ "* It is important that all $T_y$ copies have the same weights. \n",
475
+ " * It should not reinitialize the weights every time. \n",
476
+ " * In other words, all $T_y$ steps should have shared weights. \n",
477
+ "* Here's how you can implement layers with shareable weights in Keras:\n",
478
+ " 1. 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.\n",
479
+ " - Note that defining these variables inside the scope of the function `model` would technically work, since `model` will then call the `one_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.\n",
480
+ " 2. Call these objects when propagating the input.\n",
481
+ "* We have defined the layers you need as global variables. \n",
482
+ " * Please run the following cells to create them. \n",
483
+ " * 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.\n",
484
+ "* Please check the Keras documentation to learn more about these layers. The layers are functions. Below are examples of how to call these functions.\n",
485
+ " * [RepeatVector()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/RepeatVector)\n",
486
+ "```Python\n",
487
+ "var_repeated = repeat_layer(var1)\n",
488
+ "```\n",
489
+ " * [Concatenate()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Concatenate) \n",
490
+ "```Python\n",
491
+ "concatenated_vars = concatenate_layer([var1,var2,var3])\n",
492
+ "```\n",
493
+ " * [Dense()](https://keras.io/layers/core/#dense) \n",
494
+ "```Python\n",
495
+ "var_out = dense_layer(var_in)\n",
496
+ "```\n",
497
+ " * [Activation()](https://keras.io/layers/core/#activation) \n",
498
+ "```Python\n",
499
+ "activation = activation_layer(var_in) \n",
500
+ "```\n",
501
+ " * [Dot()](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dot) \n",
502
+ "```Python\n",
503
+ "dot_product = dot_layer([var1,var2])\n",
504
+ "```"
505
+ ]
506
+ },
507
+ {
508
+ "cell_type": "code",
509
+ "execution_count": null,
510
+ "metadata": {
511
+ "deletable": false,
512
+ "editable": false
513
+ },
514
+ "outputs": [],
515
+ "source": [
516
+ "# You cannot edit this cell\n",
517
+ "\n",
518
+ "# Defined shared layers as global variables\n",
519
+ "repeator = RepeatVector(Tx)\n",
520
+ "concatenator = Concatenate(axis=-1)\n",
521
+ "densor1 = Dense(10, activation = \"tanh\")\n",
522
+ "densor2 = Dense(1, activation = \"relu\")\n",
523
+ "activator = Activation(softmax, name='attention_weights') # We are using a custom softmax(axis = 1) loaded in this notebook\n",
524
+ "dotor = Dot(axes = 1)"
525
+ ]
526
+ },
527
+ {
528
+ "cell_type": "code",
529
+ "execution_count": null,
530
+ "metadata": {
531
+ "executionInfo": {
532
+ "elapsed": 16950,
533
+ "status": "ok",
534
+ "timestamp": 1612468514159,
535
+ "user": {
536
+ "displayName": "Mubsi K",
537
+ "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64",
538
+ "userId": "08094225471505108399"
539
+ },
540
+ "user_tz": -300
541
+ },
542
+ "id": "mZuMOnTDh3Mn"
543
+ },
544
+ "outputs": [],
545
+ "source": [
546
+ "# UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n",
547
+ "# GRADED FUNCTION: one_step_attention\n",
548
+ "\n",
549
+ "def one_step_attention(a, s_prev):\n",
550
+ " \"\"\"\n",
551
+ " Performs one step of attention: Outputs a context vector computed as a dot product of the attention weights\n",
552
+ " \"alphas\" and the hidden states \"a\" of the Bi-LSTM.\n",
553
+ " \n",
554
+ " Arguments:\n",
555
+ " a -- hidden state output of the Bi-LSTM, numpy-array of shape (m, Tx, 2*n_a)\n",
556
+ " s_prev -- previous hidden state of the (post-attention) LSTM, numpy-array of shape (m, n_s)\n",
557
+ " \n",
558
+ " Returns:\n",
559
+ " context -- context vector, input of the next (post-attention) LSTM cell\n",
560
+ " \"\"\"\n",
561
+ " \n",
562
+ " ### START CODE HERE ###\n",
563
+ " # 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)\n",
564
+ " s_prev = None\n",
565
+ " # Use concatenator to concatenate a and s_prev on the last axis (≈ 1 line)\n",
566
+ " # For grading purposes, please list 'a' first and 's_prev' second, in this order.\n",
567
+ " concat = None\n",
568
+ " # Use densor1 to propagate concat through a small fully-connected neural network to compute the \"intermediate energies\" variable e. (≈1 lines)\n",
569
+ " e = None\n",
570
+ " # Use densor2 to propagate e through a small fully-connected neural network to compute the \"energies\" variable energies. (≈1 lines)\n",
571
+ " energies = None\n",
572
+ " # Use \"activator\" on \"energies\" to compute the attention weights \"alphas\" (≈ 1 line)\n",
573
+ " alphas = None\n",
574
+ " # Use dotor together with \"alphas\" and \"a\", in this order, to compute the context vector to be given to the next (post-attention) LSTM-cell (≈ 1 line)\n",
575
+ " context = None\n",
576
+ " ### END CODE HERE ###\n",
577
+ " \n",
578
+ " return context"
579
+ ]
580
+ },
581
+ {
582
+ "cell_type": "code",
583
+ "execution_count": null,
584
+ "metadata": {
585
+ "deletable": false,
586
+ "editable": false
587
+ },
588
+ "outputs": [],
589
+ "source": [
590
+ "### You cannot edit this cell\n",
591
+ "\n",
592
+ "# UNIT TEST\n",
593
+ "def one_step_attention_test(target):\n",
594
+ " np.random.seed(10)\n",
595
+ " tf.random.set_seed(10)\n",
596
+ "\n",
597
+ " m = 10\n",
598
+ " Tx = 30\n",
599
+ " n_a = 32\n",
600
+ " n_s = 64\n",
601
+ " \n",
602
+ " a = np.random.uniform(1, 0, (m, Tx, 2 * n_a)).astype(np.float32)\n",
603
+ " s_prev =np.random.uniform(1, 0, (m, n_s)).astype(np.float32) * 1\n",
604
+ " context = target(a, s_prev)\n",
605
+ " \n",
606
+ " expected_output = np.load('expected_output_ex1.npy')\n",
607
+ " \n",
608
+ " assert type(context) == tf.python.framework.ops.EagerTensor, \"Unexpected type. It should be a Tensor\"\n",
609
+ " assert tuple(context.shape) == (m, 1, n_s), \"Unexpected output shape\"\n",
610
+ " assert np.all(context.numpy() == expected_output), \"Unexpected values in the result\"\n",
611
+ " \n",
612
+ " print(\"\\033[92mAll tests passed!\")\n",
613
+ " \n",
614
+ "one_step_attention_test(one_step_attention)"
615
+ ]
616
+ },
617
+ {
618
+ "cell_type": "markdown",
619
+ "metadata": {
620
+ "id": "vcmC3WcQh3Mn"
621
+ },
622
+ "source": [
623
+ "<a name='ex-2'></a>\n",
624
+ "### Exercise 2 - modelf\n",
625
+ "\n",
626
+ "Implement `modelf()` as explained in figure 1 and the instructions:\n",
627
+ "\n",
628
+ "* `modelf` first runs the input through a Bi-LSTM to get $[a^{<1>},a^{<2>}, ..., a^{<T_x>}]$. \n",
629
+ "* Then, `modelf` calls `one_step_attention()` $T_y$ times using a `for` loop. At each iteration of this loop:\n",
630
+ " - It gives the computed context vector $context^{<t>}$ to the post-attention LSTM.\n",
631
+ " - It runs the output of the post-attention LSTM through a dense layer with softmax activation.\n",
632
+ " - The softmax generates a prediction $\\hat{y}^{<t>}$.\n",
633
+ " \n",
634
+ "Again, we have defined global layers that will share weights to be used in `modelf()`."
635
+ ]
636
+ },
637
+ {
638
+ "cell_type": "code",
639
+ "execution_count": null,
640
+ "metadata": {
641
+ "deletable": false,
642
+ "editable": false
643
+ },
644
+ "outputs": [],
645
+ "source": [
646
+ "### You cannot edit this cell\n",
647
+ "\n",
648
+ "n_a = 32 # number of units for the pre-attention, bi-directional LSTM's hidden state 'a'\n",
649
+ "n_s = 64 # number of units for the post-attention LSTM's hidden state \"s\"\n",
650
+ "\n",
651
+ "# Please note, this is the post attention LSTM cell. \n",
652
+ "post_activation_LSTM_cell = LSTM(n_s, return_state = True) # Please do not modify this global variable.\n",
653
+ "output_layer = Dense(len(machine_vocab), activation=softmax)"
654
+ ]
655
+ },
656
+ {
657
+ "cell_type": "markdown",
658
+ "metadata": {
659
+ "id": "lGkKpb1Nh3Mo"
660
+ },
661
+ "source": [
662
+ "Now you can use these layers $T_y$ 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: \n",
663
+ "\n",
664
+ "1. Propagate the input `X` into a bi-directional LSTM.\n",
665
+ " * [Bidirectional](https://keras.io/layers/wrappers/#bidirectional) \n",
666
+ " * [LSTM](https://keras.io/layers/recurrent/#lstm)\n",
667
+ " * Remember that we want the LSTM to return a full sequence instead of just the last hidden state. \n",
668
+ " \n",
669
+ "Sample code:\n",
670
+ "\n",
671
+ "```Python\n",
672
+ "sequence_of_hidden_states = Bidirectional(LSTM(units=..., return_sequences=...))(the_input_X)\n",
673
+ "```\n",
674
+ " \n",
675
+ "2. Iterate for $t = 0, \\cdots, T_y-1$: \n",
676
+ " 1. Call `one_step_attention()`, passing in the sequence of hidden states $[a^{\\langle 1 \\rangle},a^{\\langle 2 \\rangle}, ..., a^{ \\langle T_x \\rangle}]$ from the pre-attention bi-directional LSTM, and the previous hidden state $s^{<t-1>}$ from the post-attention LSTM to calculate the context vector $context^{<t>}$.\n",
677
+ " 2. Give $context^{<t>}$ to the post-attention LSTM cell. \n",
678
+ " - Remember to pass in the previous hidden-state $s^{\\langle t-1\\rangle}$ and cell-states $c^{\\langle t-1\\rangle}$ of this LSTM \n",
679
+ " * This outputs the new hidden state $s^{<t>}$ and the new cell state $c^{<t>}$. \n",
680
+ "\n",
681
+ " Sample code:\n",
682
+ " ```Python\n",
683
+ " _, next_hidden_state, next_cell_state = \n",
684
+ " post_activation_LSTM_cell(inputs=..., initial_state=[prev_hidden_state, prev_cell_state])\n",
685
+ " ``` \n",
686
+ " 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.\n",
687
+ " 3. Apply a dense, softmax layer to $s^{<t>}$, get the output. \n",
688
+ " Sample code:\n",
689
+ " ```Python\n",
690
+ " output = output_layer(inputs=...)\n",
691
+ " ```\n",
692
+ " 4. Save the output by adding it to the list of outputs.\n",
693
+ "\n",
694
+ "3. Create your Keras model instance.\n",
695
+ " * It should have three inputs:\n",
696
+ " * `X`, the one-hot encoded inputs to the model, of shape ($T_{x}, humanVocabSize)$\n",
697
+ " * $s^{\\langle 0 \\rangle}$, the initial hidden state of the post-attention LSTM\n",
698
+ " * $c^{\\langle 0 \\rangle}$, the initial cell state of the post-attention LSTM\n",
699
+ " * The output is the list of outputs. \n",
700
+ " Sample code\n",
701
+ " ```Python\n",
702
+ " model = Model(inputs=[...,...,...], outputs=...)\n",
703
+ " ```"
704
+ ]
705
+ },
706
+ {
707
+ "cell_type": "code",
708
+ "execution_count": null,
709
+ "metadata": {
710
+ "executionInfo": {
711
+ "elapsed": 16948,
712
+ "status": "ok",
713
+ "timestamp": 1612468514160,
714
+ "user": {
715
+ "displayName": "Mubsi K",
716
+ "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64",
717
+ "userId": "08094225471505108399"
718
+ },
719
+ "user_tz": -300
720
+ },
721
+ "id": "qeKbeDOvh3Mo"
722
+ },
723
+ "outputs": [],
724
+ "source": [
725
+ "# UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n",
726
+ "# GRADED FUNCTION: model\n",
727
+ "\n",
728
+ "def modelf(Tx, Ty, n_a, n_s, human_vocab_size, machine_vocab_size=None):\n",
729
+ " \"\"\"\n",
730
+ " Arguments:\n",
731
+ " Tx -- length of the input sequence\n",
732
+ " Ty -- length of the output sequence\n",
733
+ " n_a -- hidden state size of the Bi-LSTM\n",
734
+ " n_s -- hidden state size of the post-attention LSTM\n",
735
+ " human_vocab_size -- size of the python dictionary \"human_vocab\"\n",
736
+ " machine_vocab_size -- integer, optional, size of the python dictionary \"machine_vocab\"\n",
737
+ " This is not being used\n",
738
+ "\n",
739
+ " Returns:\n",
740
+ " model -- Keras model instance\n",
741
+ " \"\"\"\n",
742
+ " \n",
743
+ " # Define the inputs of your model with a shape (Tx, human_vocab_size)\n",
744
+ " # Define s0 (initial hidden state) and c0 (initial cell state)\n",
745
+ " # for the decoder LSTM with shape (n_s,)\n",
746
+ " X = Input(shape=(Tx, human_vocab_size))\n",
747
+ " # initial hidden state\n",
748
+ " s0 = Input(shape=(n_s,), name='s0')\n",
749
+ " # initial cell state\n",
750
+ " c0 = Input(shape=(n_s,), name='c0')\n",
751
+ " # hidden state\n",
752
+ " s = s0\n",
753
+ " # cell state\n",
754
+ " c = c0\n",
755
+ " \n",
756
+ " # Initialize empty list of outputs\n",
757
+ " outputs = []\n",
758
+ " \n",
759
+ " ### START CODE HERE ###\n",
760
+ " \n",
761
+ " # Step 1: Define your pre-attention Bi-LSTM. (≈ 1 line)\n",
762
+ " a = None\n",
763
+ " \n",
764
+ " # Step 2: Iterate for Ty steps\n",
765
+ " for t in range(None):\n",
766
+ " \n",
767
+ " # Step 2.A: Perform one step of the attention mechanism to get back the context vector at step t (≈ 1 line)\n",
768
+ " context = None\n",
769
+ " \n",
770
+ " # Step 2.B: Apply the post-attention LSTM cell to the \"context\" vector. (≈ 1 line)\n",
771
+ " # Don't forget to pass: initial_state = [hidden state, cell state] \n",
772
+ " # Remember: s = hidden state, c = cell state\n",
773
+ " _, s, c = None\n",
774
+ " \n",
775
+ " # Step 2.C: Apply Dense layer to the hidden state output of the post-attention LSTM (≈ 1 line)\n",
776
+ " out = None\n",
777
+ " \n",
778
+ " # Step 2.D: Append \"out\" to the \"outputs\" list (≈ 1 line)\n",
779
+ " None\n",
780
+ " \n",
781
+ " # Step 3: Create model instance taking three inputs and returning the list of outputs. (≈ 1 line)\n",
782
+ " model = None\n",
783
+ " \n",
784
+ " ### END CODE HERE ###\n",
785
+ " \n",
786
+ " return model"
787
+ ]
788
+ },
789
+ {
790
+ "cell_type": "code",
791
+ "execution_count": null,
792
+ "metadata": {
793
+ "deleteable": false,
794
+ "editable": false
795
+ },
796
+ "outputs": [],
797
+ "source": [
798
+ "### You cannot edit this cell\n",
799
+ "\n",
800
+ "# UNIT TEST 1\n",
801
+ "from test_utils import *\n",
802
+ "\n",
803
+ "def modelf_test(target):\n",
804
+ " Tx = 30\n",
805
+ " n_a = 32\n",
806
+ " n_s = 64\n",
807
+ " len_human_vocab = 37\n",
808
+ " \n",
809
+ " \n",
810
+ " model = target(Tx, Ty, n_a, n_s, len_human_vocab)\n",
811
+ " \n",
812
+ " print(summary(model))\n",
813
+ "\n",
814
+ " \n",
815
+ " expected_summary = [['InputLayer', [(None, 30, 37)], 0],\n",
816
+ " ['InputLayer', [(None, 64)], 0],\n",
817
+ " ['Bidirectional', (None, 30, 64), 17920],\n",
818
+ " ['RepeatVector', (None, 30, 64), 0, 30],\n",
819
+ " ['Concatenate', (None, 30, 128), 0],\n",
820
+ " ['Dense', (None, 30, 10), 1290, 'tanh'],\n",
821
+ " ['Dense', (None, 30, 1), 11, 'relu'],\n",
822
+ " ['Activation', (None, 30, 1), 0],\n",
823
+ " ['Dot', (None, 1, 64), 0],\n",
824
+ " ['InputLayer', [(None, 64)], 0],\n",
825
+ " ['LSTM',[(None, 64), (None, 64), (None, 64)], 33024,[(None, 1, 64), (None, 64), (None, 64)],'tanh'],\n",
826
+ " ['Dense', (None, 11), 715, 'softmax']]\n",
827
+ "\n",
828
+ " assert len(model.outputs) == 10, f\"Wrong output shape. Expected 10 != {len(model.outputs)}\"\n",
829
+ "\n",
830
+ " comparator(summary(model), expected_summary)\n",
831
+ " \n",
832
+ "\n",
833
+ "modelf_test(modelf)"
834
+ ]
835
+ },
836
+ {
837
+ "cell_type": "markdown",
838
+ "metadata": {},
839
+ "source": [
840
+ "Run the test in the next cell to check if your `modelf` function is correctly updating the (next) `hidden state` and `cell state`."
841
+ ]
842
+ },
843
+ {
844
+ "cell_type": "code",
845
+ "execution_count": null,
846
+ "metadata": {
847
+ "deleteable": false,
848
+ "editable": false
849
+ },
850
+ "outputs": [],
851
+ "source": [
852
+ "### You cannot edit this cell\n",
853
+ "\n",
854
+ "# UNIT TEST 2\n",
855
+ "\n",
856
+ "def modelf_states_test(target):\n",
857
+ " Tx = 30\n",
858
+ " n_a = 32\n",
859
+ " n_s = 64\n",
860
+ " len_human_vocab = 37\n",
861
+ "\n",
862
+ " model = target(Tx, Ty, n_a, n_s, len_human_vocab)\n",
863
+ "\n",
864
+ " # Create test inputs\n",
865
+ " X_test = np.random.rand(1, Tx, len_human_vocab)\n",
866
+ " s0_test = np.zeros((1, n_s))\n",
867
+ " c0_test = np.zeros((1, n_s))\n",
868
+ "\n",
869
+ " @tf.function(input_signature=[\n",
870
+ " tf.TensorSpec(shape=[None, Tx, len_human_vocab], dtype=tf.float32),\n",
871
+ " tf.TensorSpec(shape=[None, n_s], dtype=tf.float32),\n",
872
+ " tf.TensorSpec(shape=[None, n_s], dtype=tf.float32)\n",
873
+ " ])\n",
874
+ " def predict_function(X, s0, c0):\n",
875
+ " # Call the model directly with input tensors\n",
876
+ " return model([X, s0, c0]) \n",
877
+ "\n",
878
+ " # Get the outputs of the model for the first five time steps\n",
879
+ " outputs = predict_function(X_test, s0_test, c0_test)\n",
880
+ "\n",
881
+ " # Extract the hidden states (s) from the LSTM outputs for each time step\n",
882
+ " hidden_states = [np.array(output) for output in outputs]\n",
883
+ "\n",
884
+ " # Check if consecutive hidden states are different\n",
885
+ " for i in range(len(hidden_states) - 1):\n",
886
+ " assert not np.allclose(hidden_states[i], hidden_states[i + 1]), (\n",
887
+ " \"Consecutive hidden states should be different.\\n\"\n",
888
+ " \"Check if the LSTM cell is using the correct previous states.\\n\"\n",
889
+ " \"Make sure you are using s and c, and NOT using s0 and c0 in Step 2.B.\"\n",
890
+ " )\n",
891
+ "\n",
892
+ " print(\"\\033[32mAll tests passed!\\033[0m\")\n",
893
+ "\n",
894
+ "modelf_states_test(modelf)"
895
+ ]
896
+ },
897
+ {
898
+ "cell_type": "markdown",
899
+ "metadata": {
900
+ "id": "--RX7hSsh3Mo"
901
+ },
902
+ "source": [
903
+ "Run the following cell to create your model."
904
+ ]
905
+ },
906
+ {
907
+ "cell_type": "code",
908
+ "execution_count": null,
909
+ "metadata": {
910
+ "deleteable": false,
911
+ "editable": false
912
+ },
913
+ "outputs": [],
914
+ "source": [
915
+ "## You cannot edit this cell\n",
916
+ "model = modelf(Tx, Ty, n_a, n_s, len(human_vocab))"
917
+ ]
918
+ },
919
+ {
920
+ "cell_type": "markdown",
921
+ "metadata": {
922
+ "id": "nUJw7Xohh3Mp"
923
+ },
924
+ "source": [
925
+ "#### Troubleshooting Note\n",
926
+ "* 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. \n",
927
+ "* A solution is to save and restart your kernel (or shutdown then restart your notebook), and re-run the cells."
928
+ ]
929
+ },
930
+ {
931
+ "cell_type": "markdown",
932
+ "metadata": {
933
+ "id": "VgeU_I9_h3Mp"
934
+ },
935
+ "source": [
936
+ "Let's get a summary of the model to check if it matches the expected output."
937
+ ]
938
+ },
939
+ {
940
+ "cell_type": "code",
941
+ "execution_count": null,
942
+ "metadata": {
943
+ "colab": {
944
+ "base_uri": "https://localhost:8080/"
945
+ },
946
+ "executionInfo": {
947
+ "elapsed": 20835,
948
+ "status": "ok",
949
+ "timestamp": 1612468518050,
950
+ "user": {
951
+ "displayName": "Mubsi K",
952
+ "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64",
953
+ "userId": "08094225471505108399"
954
+ },
955
+ "user_tz": -300
956
+ },
957
+ "id": "tX0vaYmPh3Mq",
958
+ "outputId": "336b9248-70b0-4379-be95-95366874c02a"
959
+ },
960
+ "outputs": [],
961
+ "source": [
962
+ "model.summary()"
963
+ ]
964
+ },
965
+ {
966
+ "cell_type": "markdown",
967
+ "metadata": {
968
+ "id": "uiqCePt5h3Mr"
969
+ },
970
+ "source": [
971
+ "**Expected Output**:\n",
972
+ "\n",
973
+ "Here is the summary you should see\n",
974
+ "<table>\n",
975
+ " <tr>\n",
976
+ " <td>\n",
977
+ " **Total params:**\n",
978
+ " </td>\n",
979
+ " <td>\n",
980
+ " 52,960\n",
981
+ " </td>\n",
982
+ " </tr>\n",
983
+ " <tr>\n",
984
+ " <td>\n",
985
+ " **Trainable params:**\n",
986
+ " </td>\n",
987
+ " <td>\n",
988
+ " 52,960\n",
989
+ " </td>\n",
990
+ " </tr>\n",
991
+ " <tr>\n",
992
+ " <td>\n",
993
+ " **Non-trainable params:**\n",
994
+ " </td>\n",
995
+ " <td>\n",
996
+ " 0\n",
997
+ " </td>\n",
998
+ " </tr>\n",
999
+ " <tr>\n",
1000
+ " <td>\n",
1001
+ " **bidirectional_1's output shape **\n",
1002
+ " </td>\n",
1003
+ " <td>\n",
1004
+ " (None, 30, 64) \n",
1005
+ " </td>\n",
1006
+ " </tr>\n",
1007
+ " <tr>\n",
1008
+ " <td>\n",
1009
+ " **repeat_vector_1's output shape **\n",
1010
+ " </td>\n",
1011
+ " <td>\n",
1012
+ " (None, 30, 64) \n",
1013
+ " </td>\n",
1014
+ " </tr>\n",
1015
+ " <tr>\n",
1016
+ " <td>\n",
1017
+ " **concatenate_1's output shape **\n",
1018
+ " </td>\n",
1019
+ " <td>\n",
1020
+ " (None, 30, 128) \n",
1021
+ " </td>\n",
1022
+ " </tr>\n",
1023
+ " <tr>\n",
1024
+ " <td>\n",
1025
+ " **attention_weights's output shape **\n",
1026
+ " </td>\n",
1027
+ " <td>\n",
1028
+ " (None, 30, 1) \n",
1029
+ " </td>\n",
1030
+ " </tr>\n",
1031
+ " <tr>\n",
1032
+ " <td>\n",
1033
+ " **dot_1's output shape **\n",
1034
+ " </td>\n",
1035
+ " <td>\n",
1036
+ " (None, 1, 64)\n",
1037
+ " </td>\n",
1038
+ " </tr>\n",
1039
+ " <tr>\n",
1040
+ " <td>\n",
1041
+ " **dense_3's output shape **\n",
1042
+ " </td>\n",
1043
+ " <td>\n",
1044
+ " (None, 11) \n",
1045
+ " </td>\n",
1046
+ " </tr>\n",
1047
+ "</table>\n"
1048
+ ]
1049
+ },
1050
+ {
1051
+ "cell_type": "markdown",
1052
+ "metadata": {
1053
+ "id": "8u3D9Odhh3Ms"
1054
+ },
1055
+ "source": [
1056
+ "<a name='ex-3'></a>\n",
1057
+ "### Exercise 3 - Compile the Model\n",
1058
+ "\n",
1059
+ "* After creating your model in Keras, you need to compile it and define the loss function, optimizer and metrics you want to use. \n",
1060
+ " * Loss function: 'categorical_crossentropy'.\n",
1061
+ " * Optimizer: [Adam](https://keras.io/optimizers/#adam) [optimizer](https://keras.io/optimizers/#usage-of-optimizers)\n",
1062
+ " - learning rate = 0.005 \n",
1063
+ " - $\\beta_1 = 0.9$\n",
1064
+ " - $\\beta_2 = 0.999$\n",
1065
+ " - decay = 0.01 \n",
1066
+ " * metric: 'accuracy'\n",
1067
+ " \n",
1068
+ "Sample code\n",
1069
+ "```Python\n",
1070
+ "optimizer = Adam(lr=..., beta_1=..., beta_2=..., decay=...)\n",
1071
+ "model.compile(optimizer=..., loss=..., metrics=[...])\n",
1072
+ "```"
1073
+ ]
1074
+ },
1075
+ {
1076
+ "cell_type": "code",
1077
+ "execution_count": null,
1078
+ "metadata": {
1079
+ "executionInfo": {
1080
+ "elapsed": 20835,
1081
+ "status": "ok",
1082
+ "timestamp": 1612468518051,
1083
+ "user": {
1084
+ "displayName": "Mubsi K",
1085
+ "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64",
1086
+ "userId": "08094225471505108399"
1087
+ },
1088
+ "user_tz": -300
1089
+ },
1090
+ "id": "sBFRJ49rh3Ms"
1091
+ },
1092
+ "outputs": [],
1093
+ "source": [
1094
+ "### START CODE HERE ### (≈2 lines)\n",
1095
+ "opt = None # Adam(...) \n",
1096
+ "model.compile(loss = None, optimizer = None, metrics = None)\n",
1097
+ "### END CODE HERE ###"
1098
+ ]
1099
+ },
1100
+ {
1101
+ "cell_type": "code",
1102
+ "execution_count": null,
1103
+ "metadata": {
1104
+ "deleteable": false,
1105
+ "editable": false
1106
+ },
1107
+ "outputs": [],
1108
+ "source": [
1109
+ "### You cannot edit this cell\n",
1110
+ "\n",
1111
+ "# UNIT TESTS\n",
1112
+ "assert opt.lr == 0.005, \"Set the lr parameter to 0.005\"\n",
1113
+ "assert opt.beta_1 == 0.9, \"Set the beta_1 parameter to 0.9\"\n",
1114
+ "assert opt.beta_2 == 0.999, \"Set the beta_2 parameter to 0.999\"\n",
1115
+ "assert opt.decay == 0.01, \"Set the decay parameter to 0.01\"\n",
1116
+ "assert model.loss == \"categorical_crossentropy\", \"Wrong loss. Use 'categorical_crossentropy'\"\n",
1117
+ "assert model.optimizer == opt, \"Use the optimizer that you have instantiated\"\n",
1118
+ "assert model.compiled_metrics._user_metrics[0] == 'accuracy', \"set metrics to ['accuracy']\"\n",
1119
+ "\n",
1120
+ "print(\"\\033[92mAll tests passed!\")"
1121
+ ]
1122
+ },
1123
+ {
1124
+ "cell_type": "markdown",
1125
+ "metadata": {
1126
+ "id": "Qz71nM3oh3Ms"
1127
+ },
1128
+ "source": [
1129
+ "#### Define inputs and outputs, and fit the model\n",
1130
+ "The last step is to define all your inputs and outputs to fit the model:\n",
1131
+ "- You have input `Xoh` of shape $(m = 10000, T_x = 30, human\\_vocab=37)$ containing the training examples.\n",
1132
+ "- You need to create `s0` and `c0` to initialize your `post_attention_LSTM_cell` with zeros.\n",
1133
+ "- Given the `model()` you coded, you need the \"outputs\" to be a list of 10 elements of shape (m, T_y). \n",
1134
+ " - The list `outputs[i][0], ..., outputs[i][Ty]` represents the true labels (characters) corresponding to the $i^{th}$ training example (`Xoh[i]`). \n",
1135
+ " - `outputs[i][j]` is the true label of the $j^{th}$ character in the $i^{th}$ training example."
1136
+ ]
1137
+ },
1138
+ {
1139
+ "cell_type": "code",
1140
+ "execution_count": null,
1141
+ "metadata": {
1142
+ "deleteable": false,
1143
+ "editable": false
1144
+ },
1145
+ "outputs": [],
1146
+ "source": [
1147
+ "### You cannot edit this cell\n",
1148
+ "s0 = np.zeros((m, n_s))\n",
1149
+ "c0 = np.zeros((m, n_s))\n",
1150
+ "outputs = list(Yoh.swapaxes(0,1))"
1151
+ ]
1152
+ },
1153
+ {
1154
+ "cell_type": "markdown",
1155
+ "metadata": {
1156
+ "id": "FVkITGi3h3Mt"
1157
+ },
1158
+ "source": [
1159
+ "Let's now fit the model and run it for one epoch."
1160
+ ]
1161
+ },
1162
+ {
1163
+ "cell_type": "code",
1164
+ "execution_count": null,
1165
+ "metadata": {
1166
+ "deleteable": false,
1167
+ "editable": false
1168
+ },
1169
+ "outputs": [],
1170
+ "source": [
1171
+ "### You cannot edit this cell\n",
1172
+ "model.fit([Xoh, s0, c0], outputs, epochs=1, batch_size=100)"
1173
+ ]
1174
+ },
1175
+ {
1176
+ "cell_type": "markdown",
1177
+ "metadata": {
1178
+ "id": "SUikskCoh3Mt"
1179
+ },
1180
+ "source": [
1181
+ "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: \n",
1182
+ "\n",
1183
+ "<img src=\"images/table.png\" style=\"width:700;height:200px;\"> <br>\n",
1184
+ "<caption><center>Thus, <mark> dense_2_8_accuracy: 0.89 </mark> means that you are predicting the 9th character of the output correctly 89% of the time in the current batch of data. </center></caption>\n",
1185
+ "\n",
1186
+ "\n",
1187
+ "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.) "
1188
+ ]
1189
+ },
1190
+ {
1191
+ "cell_type": "code",
1192
+ "execution_count": null,
1193
+ "metadata": {
1194
+ "deleteable": false,
1195
+ "editable": false
1196
+ },
1197
+ "outputs": [],
1198
+ "source": [
1199
+ "### You cannot edit this cell\n",
1200
+ "model.load_weights('models/model.h5')"
1201
+ ]
1202
+ },
1203
+ {
1204
+ "cell_type": "markdown",
1205
+ "metadata": {
1206
+ "id": "yUUD9yXxh3Mu"
1207
+ },
1208
+ "source": [
1209
+ "You can now see the results on new examples."
1210
+ ]
1211
+ },
1212
+ {
1213
+ "cell_type": "code",
1214
+ "execution_count": null,
1215
+ "metadata": {
1216
+ "deleteable": false,
1217
+ "editable": false
1218
+ },
1219
+ "outputs": [],
1220
+ "source": [
1221
+ "### You cannot edit this cell\n",
1222
+ "\n",
1223
+ "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']\n",
1224
+ "s00 = np.zeros((1, n_s))\n",
1225
+ "c00 = np.zeros((1, n_s))\n",
1226
+ "for example in EXAMPLES:\n",
1227
+ " source = string_to_int(example, Tx, human_vocab)\n",
1228
+ " #print(source)\n",
1229
+ " source = np.array(list(map(lambda x: to_categorical(x, num_classes=len(human_vocab)), source))).swapaxes(0,1)\n",
1230
+ " source = np.swapaxes(source, 0, 1)\n",
1231
+ " source = np.expand_dims(source, axis=0)\n",
1232
+ " prediction = model.predict([source, s00, c00])\n",
1233
+ " prediction = np.argmax(prediction, axis = -1)\n",
1234
+ " output = [inv_machine_vocab[int(i)] for i in prediction]\n",
1235
+ " print(\"source:\", example)\n",
1236
+ " print(\"output:\", ''.join(output),\"\\n\")"
1237
+ ]
1238
+ },
1239
+ {
1240
+ "cell_type": "markdown",
1241
+ "metadata": {
1242
+ "id": "vjdEQiIDh3Mv"
1243
+ },
1244
+ "source": [
1245
+ "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. "
1246
+ ]
1247
+ },
1248
+ {
1249
+ "cell_type": "markdown",
1250
+ "metadata": {
1251
+ "id": "1XIxtN4xh3Mv"
1252
+ },
1253
+ "source": [
1254
+ "<a name='3'></a>\n",
1255
+ "## 3 - Visualizing Attention (Optional / Ungraded)\n",
1256
+ "\n",
1257
+ "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.\n",
1258
+ "\n",
1259
+ "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: \n",
1260
+ "\n",
1261
+ "<img src=\"images/date_attention.png\" style=\"width:600;height:300px;\"> <br>\n",
1262
+ "<caption><center> **Figure 8**: Full Attention Map</center></caption>\n",
1263
+ "\n",
1264
+ "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 make the translation. The year mostly requires it to pay attention to the input's \"18\" in order to generate \"2018.\" "
1265
+ ]
1266
+ },
1267
+ {
1268
+ "cell_type": "markdown",
1269
+ "metadata": {
1270
+ "id": "FrP893IFh3Mv"
1271
+ },
1272
+ "source": [
1273
+ "<a name='3-1'></a>\n",
1274
+ "### 3.1 - Getting the Attention Weights From the Network\n",
1275
+ "\n",
1276
+ "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}$. \n",
1277
+ "\n",
1278
+ "To figure out where the attention values are located, let's start by printing a summary of the model ."
1279
+ ]
1280
+ },
1281
+ {
1282
+ "cell_type": "code",
1283
+ "execution_count": null,
1284
+ "metadata": {
1285
+ "colab": {
1286
+ "base_uri": "https://localhost:8080/"
1287
+ },
1288
+ "executionInfo": {
1289
+ "elapsed": 53826,
1290
+ "status": "ok",
1291
+ "timestamp": 1612468551078,
1292
+ "user": {
1293
+ "displayName": "Mubsi K",
1294
+ "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gip7OjOkdNkKxKDyWEQAq1o8ccGN_HrBTGdqjgQ=s64",
1295
+ "userId": "08094225471505108399"
1296
+ },
1297
+ "user_tz": -300
1298
+ },
1299
+ "id": "RfiLrfKIh3Mv",
1300
+ "outputId": "b6690603-209c-40d7-f352-235a689d1aea"
1301
+ },
1302
+ "outputs": [],
1303
+ "source": [
1304
+ "model.summary()"
1305
+ ]
1306
+ },
1307
+ {
1308
+ "cell_type": "markdown",
1309
+ "metadata": {
1310
+ "id": "zbcprBCPh3Mv"
1311
+ },
1312
+ "source": [
1313
+ "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.\n",
1314
+ "\n",
1315
+ "The function `plot_attention_map()` pulls out the attention values from your model and plots them.\n",
1316
+ "\n",
1317
+ "**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 have passed all implementations of the exercises above, don’t worry about the error, it will not affect the grading for this assignment."
1318
+ ]
1319
+ },
1320
+ {
1321
+ "cell_type": "code",
1322
+ "execution_count": null,
1323
+ "metadata": {},
1324
+ "outputs": [],
1325
+ "source": [
1326
+ "attention_map = plot_attention_map(model, human_vocab, inv_machine_vocab, \"Tuesday 09 Oct 1993\", num = 7, n_s = 64);"
1327
+ ]
1328
+ },
1329
+ {
1330
+ "cell_type": "markdown",
1331
+ "metadata": {
1332
+ "id": "pQ3qbIjqh3Mx"
1333
+ },
1334
+ "source": [
1335
+ "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.\n",
1336
+ "\n",
1337
+ "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."
1338
+ ]
1339
+ },
1340
+ {
1341
+ "cell_type": "markdown",
1342
+ "metadata": {
1343
+ "id": "IkpGu1Jkh3Mx"
1344
+ },
1345
+ "source": [
1346
+ "### Congratulations!\n",
1347
+ "\n",
1348
+ "\n",
1349
+ "You have come to the end of this assignment \n",
1350
+ "\n",
1351
+ "#### Here's what you should remember\n",
1352
+ "\n",
1353
+ "- 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. \n",
1354
+ "- An attention mechanism allows a network to focus on the most relevant parts of the input when producing a specific part of the output. \n",
1355
+ "- 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. \n",
1356
+ "- You can visualize attention weights $\\alpha^{\\langle t,t' \\rangle}$ to see what the network is paying attention to while generating each output."
1357
+ ]
1358
+ },
1359
+ {
1360
+ "cell_type": "markdown",
1361
+ "metadata": {
1362
+ "id": "ZaKA2u4uh3My"
1363
+ },
1364
+ "source": [
1365
+ "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. "
1366
+ ]
1367
+ }
1368
+ ],
1369
+ "metadata": {
1370
+ "kernelspec": {
1371
+ "display_name": "Python 3",
1372
+ "language": "python",
1373
+ "name": "python3"
1374
+ },
1375
+ "language_info": {
1376
+ "codemirror_mode": {
1377
+ "name": "ipython",
1378
+ "version": 3
1379
+ },
1380
+ "file_extension": ".py",
1381
+ "mimetype": "text/x-python",
1382
+ "name": "python",
1383
+ "nbconvert_exporter": "python",
1384
+ "pygments_lexer": "ipython3",
1385
+ "version": "3.7.6"
1386
+ }
1387
+ },
1388
+ "nbformat": 4,
1389
+ "nbformat_minor": 1
1390
+ }
Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/Neural_machine_translation_with_attention_v4a.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/__pycache__/nmt_utils.cpython-37.pyc ADDED
Binary file (7.97 kB). View file
 
Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/__pycache__/test_utils.cpython-37.pyc ADDED
Binary file (1.82 kB). View file
 
Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/expected_output_ex1.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a07c969d1cc85d193c3078b618bde6a2dde392b441676d1e066baf9d905de24
3
+ size 2688
Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/generateTestCases.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # New Generate Test Cases
2
+ import numpy as np
3
+ import math
4
+ import os,sys
5
+ from testCase import get_testCase
6
+ # import copy
7
+ # from keras.callbacks import History
8
+ # import tensorflow as tf
9
+ sys.path.append('../')
10
+ sys.path.append('../../')
11
+
12
+ from grader_support import stdout_redirector
13
+ from grader_support import util
14
+
15
+ os.environ['TF_CPP_MIN_LOG_LEVEL']='3'
16
+
17
+ # This grader is for the Emojify assignment
18
+
19
+ mFiles = [
20
+ "one_step_attention.py",
21
+ "model.py"
22
+ ]
23
+ class suppress_stdout_stderr(object):
24
+ '''
25
+ A context manager for doing a "deep suppression" of stdout and stderr in
26
+ Python, i.e. will suppress all print, even if the print originates in a
27
+ compiled C/Fortran sub-function.
28
+ This will not suppress raised exceptions, since exceptions are printed
29
+ to stderr just before a script exits, and after the context manager has
30
+ exited (at least, I think that is why it lets exceptions through).
31
+
32
+ '''
33
+ def __init__(self):
34
+ # Open a pair of null files
35
+ self.null_fds = [os.open(os.devnull,os.O_RDWR) for x in range(2)]
36
+ # Save the actual stdout (1) and stderr (2) file descriptors.
37
+ self.save_fds = [os.dup(1), os.dup(2)]
38
+
39
+ def __enter__(self):
40
+ # Assign the null pointers to stdout and stderr.
41
+ os.dup2(self.null_fds[0],1)
42
+ os.dup2(self.null_fds[1],2)
43
+
44
+ def __exit__(self, *_):
45
+ # Re-assign the real stdout/stderr back to (1) and (2)
46
+ os.dup2(self.save_fds[0],1)
47
+ os.dup2(self.save_fds[1],2)
48
+ # Close all file descriptors
49
+ for fd in self.null_fds + self.save_fds:
50
+ os.close(fd)
51
+ np.random.seed(3)
52
+ with suppress_stdout_stderr():
53
+ from solutions import *
54
+ from testCase import get_testCase
55
+ n_a = 64
56
+ n_s = 128
57
+ m = 10
58
+ dataset, human_vocab, machine_vocab, inv_machine_vocab = load_dataset(m)
59
+
60
+ human_vocab_size = len(human_vocab)
61
+ machine_vocab_size = len(machine_vocab)
62
+
63
+ im = model(Tx, Ty, n_a, n_s, human_vocab_size, machine_vocab_size)
64
+ cp1 = im.count_params()
65
+ mi1 = len(im.inputs)
66
+ mo1 = len(im.outputs)
67
+ ml1 = len(im.layers)
68
+ m_out1 = np.asarray((cp1, mi1, mo1, ml1))
69
+
70
+
71
+ # GRADED FUNCTION: one_step_attention
72
+
73
+ m_out2 = get_testCase()
74
+
75
+ def generateTestCases():
76
+ testCases = {
77
+ 'one_step_attention': {
78
+ 'partId': 'zcQIs',
79
+ 'testCases': [
80
+ {
81
+ 'testInput': 0,
82
+ 'testOutput': m_out2
83
+ }
84
+ ]
85
+ },
86
+ 'model': {
87
+ 'partId': 'PTKef',
88
+ 'testCases': [
89
+ {
90
+ 'testInput': (Tx, Ty, n_a, n_s, human_vocab_size, machine_vocab_size),
91
+ 'testOutput': m_out1
92
+ }
93
+ ]
94
+ }
95
+ }
96
+ return testCases
97
+
Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/attn_mechanism.png ADDED

Git LFS Details

  • SHA256: 5be039ab61ed159d1597f980675f18952f80afd2bc42a61b2440a9e468eae8a0
  • Pointer size: 131 Bytes
  • Size of remote file: 172 kB
Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/attn_model.png ADDED

Git LFS Details

  • SHA256: 8173c9f33ac0f823e6e0afcf2cab53648828e2d006e33bc38d73e6547a5bf314
  • Pointer size: 131 Bytes
  • Size of remote file: 243 kB
Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/date_attention.png ADDED

Git LFS Details

  • SHA256: 373158944d9499ac510c298e1f4012902ab5753b760baea6fba8ef8cd7b2ada4
  • Pointer size: 131 Bytes
  • Size of remote file: 134 kB
Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/date_attention2.png ADDED

Git LFS Details

  • SHA256: f8290f9c51034e935569c59cfa1d2a35e86a920733c161e912b3364e2f77669d
  • Pointer size: 131 Bytes
  • Size of remote file: 133 kB
Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/poorly_trained_model.png ADDED
Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/images/table.png ADDED
Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/models/model.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:908b9a19d6528c5efcf0374b2eb7de6c79443269b8f53c1440268e6e3399e80a
3
+ size 698400
Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/nmt_utils.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from faker import Faker
3
+ import random
4
+ from tqdm import tqdm
5
+ from babel.dates import format_date
6
+ from tensorflow.keras.utils import to_categorical
7
+ import tensorflow.keras.backend as K
8
+ from tensorflow.keras.models import Model
9
+ import matplotlib.pyplot as plt
10
+
11
+ fake = Faker()
12
+ Faker.seed(12345)
13
+ random.seed(12345)
14
+
15
+ # Define format of the data we would like to generate
16
+ FORMATS = ['short',
17
+ 'medium',
18
+ 'long',
19
+ 'full',
20
+ 'full',
21
+ 'full',
22
+ 'full',
23
+ 'full',
24
+ 'full',
25
+ 'full',
26
+ 'full',
27
+ 'full',
28
+ 'full',
29
+ 'd MMM YYY',
30
+ 'd MMMM YYY',
31
+ 'dd MMM YYY',
32
+ 'd MMM, YYY',
33
+ 'd MMMM, YYY',
34
+ 'dd, MMM YYY',
35
+ 'd MM YY',
36
+ 'd MMMM YYY',
37
+ 'MMMM d YYY',
38
+ 'MMMM d, YYY',
39
+ 'dd.MM.YY']
40
+
41
+ # change this if you want it to work with another language
42
+ LOCALES = ['en_US']
43
+
44
+ def load_date():
45
+ """
46
+ Loads some fake dates
47
+ :returns: tuple containing human readable string, machine readable string, and date object
48
+ """
49
+ dt = fake.date_object()
50
+
51
+ try:
52
+ human_readable = format_date(dt, format=random.choice(FORMATS), locale='en_US') # locale=random.choice(LOCALES))
53
+ human_readable = human_readable.lower()
54
+ human_readable = human_readable.replace(',','')
55
+ machine_readable = dt.isoformat()
56
+
57
+ except AttributeError as e:
58
+ return None, None, None
59
+
60
+ return human_readable, machine_readable, dt
61
+
62
+ def load_dataset(m):
63
+ """
64
+ Loads a dataset with m examples and vocabularies
65
+ :m: the number of examples to generate
66
+ """
67
+
68
+ human_vocab = set()
69
+ machine_vocab = set()
70
+ dataset = []
71
+ Tx = 30
72
+
73
+
74
+ for i in tqdm(range(m)):
75
+ h, m, _ = load_date()
76
+ if h is not None:
77
+ dataset.append((h, m))
78
+ human_vocab.update(tuple(h))
79
+ machine_vocab.update(tuple(m))
80
+
81
+ human = dict(zip(sorted(human_vocab) + ['<unk>', '<pad>'],
82
+ list(range(len(human_vocab) + 2))))
83
+ inv_machine = dict(enumerate(sorted(machine_vocab)))
84
+ machine = {v:k for k,v in inv_machine.items()}
85
+
86
+ return dataset, human, machine, inv_machine
87
+
88
+ def preprocess_data(dataset, human_vocab, machine_vocab, Tx, Ty):
89
+
90
+ X, Y = zip(*dataset)
91
+
92
+ X = np.array([string_to_int(i, Tx, human_vocab) for i in X])
93
+ Y = [string_to_int(t, Ty, machine_vocab) for t in Y]
94
+
95
+ Xoh = np.array(list(map(lambda x: to_categorical(x, num_classes=len(human_vocab)), X)))
96
+ Yoh = np.array(list(map(lambda x: to_categorical(x, num_classes=len(machine_vocab)), Y)))
97
+
98
+
99
+
100
+ return X, np.array(Y), Xoh, Yoh
101
+
102
+ def string_to_int(string, length, vocab):
103
+ """
104
+ Converts all strings in the vocabulary into a list of integers representing the positions of the
105
+ input string's characters in the "vocab"
106
+
107
+ Arguments:
108
+ string -- input string, e.g. 'Wed 10 Jul 2007'
109
+ length -- the number of time steps you'd like, determines if the output will be padded or cut
110
+ vocab -- vocabulary, dictionary used to index every character of your "string"
111
+
112
+ Returns:
113
+ rep -- list of integers (or '<unk>') (size = length) representing the position of the string's character in the vocabulary
114
+ """
115
+
116
+ #make lower to standardize
117
+ string = string.lower()
118
+ string = string.replace(',','')
119
+
120
+ if len(string) > length:
121
+ string = string[:length]
122
+
123
+ rep = list(map(lambda x: vocab.get(x, '<unk>'), string))
124
+
125
+ if len(string) < length:
126
+ rep += [vocab['<pad>']] * (length - len(string))
127
+
128
+ #print (rep)
129
+ return rep
130
+
131
+
132
+ def int_to_string(ints, inv_vocab):
133
+ """
134
+ Output a machine readable list of characters based on a list of indexes in the machine's vocabulary
135
+
136
+ Arguments:
137
+ ints -- list of integers representing indexes in the machine's vocabulary
138
+ inv_vocab -- dictionary mapping machine readable indexes to machine readable characters
139
+
140
+ Returns:
141
+ l -- list of characters corresponding to the indexes of ints thanks to the inv_vocab mapping
142
+ """
143
+
144
+ l = [inv_vocab[i] for i in ints]
145
+ return l
146
+
147
+
148
+ EXAMPLES = ['3 May 1979', '5 Apr 09', '20th February 2016', 'Wed 10 Jul 2007']
149
+
150
+ def run_example(model, input_vocabulary, inv_output_vocabulary, text):
151
+ encoded = string_to_int(text, TIME_STEPS, input_vocabulary)
152
+ prediction = model.predict(np.array([encoded]))
153
+ prediction = np.argmax(prediction[0], axis=-1)
154
+ return int_to_string(prediction, inv_output_vocabulary)
155
+
156
+ def run_examples(model, input_vocabulary, inv_output_vocabulary, examples=EXAMPLES):
157
+ predicted = []
158
+ for example in examples:
159
+ predicted.append(''.join(run_example(model, input_vocabulary, inv_output_vocabulary, example)))
160
+ print('input:', example)
161
+ print('output:', predicted[-1])
162
+ return predicted
163
+
164
+
165
+ def softmax(x, axis=1):
166
+ """Softmax activation function.
167
+ # Arguments
168
+ x : Tensor.
169
+ axis: Integer, axis along which the softmax normalization is applied.
170
+ # Returns
171
+ Tensor, output of softmax transformation.
172
+ # Raises
173
+ ValueError: In case `dim(x) == 1`.
174
+ """
175
+ ndim = K.ndim(x)
176
+ if ndim == 2:
177
+ return K.softmax(x)
178
+ elif ndim > 2:
179
+ e = K.exp(x - K.max(x, axis=axis, keepdims=True))
180
+ s = K.sum(e, axis=axis, keepdims=True)
181
+ return e / s
182
+ else:
183
+ raise ValueError('Cannot apply softmax to a tensor that is 1D')
184
+
185
+
186
+ def plot_attention_map(modelx, input_vocabulary, inv_output_vocabulary, text, n_s = 128, num = 7):
187
+ """
188
+ Plot the attention map.
189
+
190
+ """
191
+ attention_map = np.zeros((10, 30))
192
+ layer = modelx.get_layer('attention_weights')
193
+
194
+ Ty, Tx = attention_map.shape
195
+
196
+ human_vocab_size = 37
197
+
198
+ # Well, this is cumbersome but this version of tensorflow-keras has a bug that affects the
199
+ # reuse of layers in a model with the functional API.
200
+ # So, I have to recreate the model based on the functional
201
+ # components and connect then one by one.
202
+ # ideally it can be done simply like this:
203
+ # layer = modelx.layers[num]
204
+ # f = Model(modelx.inputs, [layer.get_output_at(t) for t in range(Ty)])
205
+ #
206
+
207
+ X = modelx.inputs[0]
208
+ s0 = modelx.inputs[1]
209
+ c0 = modelx.inputs[2]
210
+ s = s0
211
+ c = s0
212
+
213
+ a = modelx.layers[2](X)
214
+ outputs = []
215
+
216
+ for t in range(Ty):
217
+ s_prev = s
218
+ s_prev = modelx.layers[3](s_prev)
219
+ concat = modelx.layers[4]([a, s_prev])
220
+ e = modelx.layers[5](concat)
221
+ energies = modelx.layers[6](e)
222
+ alphas = modelx.layers[7](energies)
223
+ context = modelx.layers[8]([alphas, a])
224
+ # Don't forget to pass: initial_state = [hidden state, cell state] (≈ 1 line)
225
+ s, _, c = modelx.layers[10](context, initial_state = [s, c])
226
+ outputs.append(energies)
227
+
228
+ f = Model(inputs=[X, s0, c0], outputs = outputs)
229
+
230
+
231
+ s0 = np.zeros((1, n_s))
232
+ c0 = np.zeros((1, n_s))
233
+ encoded = np.array(string_to_int(text, Tx, input_vocabulary)).reshape((1, 30))
234
+ encoded = np.array(list(map(lambda x: to_categorical(x, num_classes=len(input_vocabulary)), encoded)))
235
+
236
+
237
+ r = f([encoded, s0, c0])
238
+
239
+ for t in range(Ty):
240
+ for t_prime in range(Tx):
241
+ attention_map[t][t_prime] = r[t][0, t_prime]
242
+
243
+ # Normalize attention map
244
+ row_max = attention_map.max(axis=1)
245
+ attention_map = attention_map / row_max[:, None]
246
+
247
+ prediction = modelx.predict([encoded, s0, c0])
248
+
249
+ predicted_text = []
250
+ for i in range(len(prediction)):
251
+ predicted_text.append(int(np.argmax(prediction[i], axis=1)))
252
+
253
+ predicted_text = list(predicted_text)
254
+ predicted_text = int_to_string(predicted_text, inv_output_vocabulary)
255
+ text_ = list(text)
256
+
257
+ # get the lengths of the string
258
+ input_length = len(text)
259
+ output_length = Ty
260
+
261
+ # Plot the attention_map
262
+ plt.clf()
263
+ f = plt.figure(figsize=(8, 8.5))
264
+ ax = f.add_subplot(1, 1, 1)
265
+
266
+ # add image
267
+ i = ax.imshow(attention_map, interpolation='nearest', cmap='Blues')
268
+
269
+ # add colorbar
270
+ cbaxes = f.add_axes([0.2, 0, 0.6, 0.03])
271
+ cbar = f.colorbar(i, cax=cbaxes, orientation='horizontal')
272
+ cbar.ax.set_xlabel('Alpha value (Probability output of the "softmax")', labelpad=2)
273
+
274
+ # add labels
275
+ ax.set_yticks(range(output_length))
276
+ ax.set_yticklabels(predicted_text[:output_length])
277
+
278
+ ax.set_xticks(range(input_length))
279
+ ax.set_xticklabels(text_[:input_length], rotation=45)
280
+
281
+ ax.set_xlabel('Input Sequence')
282
+ ax.set_ylabel('Output Sequence')
283
+
284
+ # add grid and legend
285
+ ax.grid()
286
+
287
+ #f.show()
288
+
289
+ return attention_map
Seq2Seq/Neural_MT_without_Teacher_Forcing/home/jovyan/work/W3A1/test_utils.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from termcolor import colored
2
+
3
+ from tensorflow.keras.layers import Input
4
+ from tensorflow.keras.layers import Conv2D
5
+ from tensorflow.keras.layers import MaxPooling2D
6
+ from tensorflow.keras.layers import Dropout
7
+ from tensorflow.keras.layers import Conv2DTranspose
8
+ from tensorflow.keras.layers import concatenate
9
+ from tensorflow.keras.layers import ZeroPadding2D
10
+ from tensorflow.keras.layers import Dense
11
+ from tensorflow.keras.layers import LSTM
12
+ from tensorflow.keras.layers import RepeatVector
13
+
14
+
15
+ # Compare the two inputs
16
+ def comparator(learner, instructor):
17
+ if len(learner) != len(instructor):
18
+ raise AssertionError("Error in test. The lists contain a different number of elements")
19
+ for index, a in enumerate(instructor):
20
+ b = learner[index]
21
+ if tuple(a) != tuple(b):
22
+ print(colored(f"Test failed at index {index}", attrs=['bold']),
23
+ "\n Expected value \n\n", colored(f"{a}", "green"),
24
+ "\n\n does not match the input value: \n\n",
25
+ colored(f"{b}", "red"))
26
+ raise AssertionError("Error in test")
27
+ print(colored("All tests passed!", "green"))
28
+
29
+ # extracts the description of a given model
30
+ def summary(model):
31
+ model.compile(optimizer='adam',
32
+ loss='categorical_crossentropy',
33
+ metrics=['accuracy'])
34
+ result = []
35
+ for layer in model.layers:
36
+ descriptors = [layer.__class__.__name__, layer.output_shape, layer.count_params()]
37
+ if (type(layer) == Conv2D):
38
+ descriptors.append(layer.padding)
39
+ descriptors.append(layer.activation.__name__)
40
+ descriptors.append(layer.kernel_initializer.__class__.__name__)
41
+ if (type(layer) == MaxPooling2D):
42
+ descriptors.append(layer.pool_size)
43
+ descriptors.append(layer.strides)
44
+ descriptors.append(layer.padding)
45
+ if (type(layer) == Dropout):
46
+ descriptors.append(layer.rate)
47
+ if (type(layer) == ZeroPadding2D):
48
+ descriptors.append(layer.padding)
49
+ if (type(layer) == Dense):
50
+ descriptors.append(layer.activation.__name__)
51
+ if (type(layer) == LSTM):
52
+ descriptors.append(layer.input_shape)
53
+ descriptors.append(layer.activation.__name__)
54
+ if (type(layer) == RepeatVector):
55
+ descriptors.append(layer.n)
56
+ result.append(descriptors)
57
+ return result