这个项目需要配置环境 Faker==4.0.2
欢迎来到本周的第一份编程作业!
你将建立一个神经机器翻译(NMT)模型,以将人类可读的日期(“25th of June, 2009”)转换为机器可读的日期(“2009-06-25”)。 你将使用注意力模型来完成此任务,注意力模型是序列模型中最复杂的序列之一。
此笔记本是与NVIDIA深度学习研究所共同编写的。
让我们加载此作业所需的所有软件包。
In [1]:
cd /home/kesci/input/deeplearning175678
/home/kesci/input/deeplearning175678
In [2]:
from keras.layers import Bidirectional, Concatenate, Permute, Dot, Input, LSTM, Multiply
from keras.layers import RepeatVector, Dense, Activation, Lambda
from keras.optimizers import Adam
from keras.utils import to_categorical
from keras.models import load_model, Model
import keras.backend as K
import numpy as np
from faker import Faker
import random
from tqdm import tqdm_notebook as tqdm
from babel.dates import format_date
from nmt_utils import *
import matplotlib.pyplot as plt
%matplotlib inline
Using TensorFlow backend.
/opt/conda/lib/python3.6/site-packages/requests/__init__.py:80: RequestsDependencyWarning: urllib3 (1.25.7) or chardet (3.0.4) doesn't match a supported version!
RequestsDependencyWarning)
1 将人类可读的日期转换成机器可读的日期
你在此处构建的模型可用于将一种语言翻译成另一种语言,例如从英语翻译成印地语。但是,语言翻译需要大量的数据集,通常需要花费数天时间在GPU上进行训练。为了给你提供一个即使不使用大量数据集也可以试验这些模型的地方,我们将使用更简单的“日期转换”任务。
网络将以各种可能的格式输入日期(例如 “the 29th of August 1958”, “03/30/1968”, “24 JUNE 1987”),并将其转换为标准化的机器可读日期(例如"1958-08-29", “1968-03-30”, “1987-06-24”)。我们将让网络学习如何以通用的机器可读格式YYYY-MM-DD输出日期。
查看nmtutils.py
以查看所有格式。计算并弄清楚格式如何工作,之后你将需要应用这些知识。
1.1 数据集
我们将在10000个人类可读日期及其等效的标准化机器可读日期的数据集上训练模型。让我们运行以下单元格以加载数据集并打印一些示例。
In [3]:
m = 10000
dataset, human_vocab, machine_vocab, inv_machine_vocab = load_dataset(m)
100%|██████████| 10000/10000 [00:00<00:00, 22610.25it/s]
In [4]:
dataset[:10]
Out[4]:
[('9 may 1998', '1998-05-09'),
('10.11.19', '2019-11-10'),
('9/10/70', '1970-09-10'),
('saturday april 28 1990', '1990-04-28'),
('thursday january 26 1995', '1995-01-26'),
('monday march 7 1983', '1983-03-07'),
('sunday may 22 1988', '1988-05-22'),
('08 jul 2008', '2008-07-08'),
('8 sep 1999', '1999-09-08'),
('thursday january 1 1981', '1981-01-01')]
你已加载:
dataset
:(人可读日期,机器可读日期)元组列表human_vocab
:python字典,将人类可读日期中使用的所有字符映射到整数索引machine_vocab
:python字典,将机器可读日期中使用的所有字符映射到整数索引。这些索引不一定与human_vocab
一致。inv_machine_vocab
:machine_vocab
的逆字典,从索引映射回字符。
让我们预处理数据并将原始文本数据映射到索引值。我们还将使用Tx = 30(我们假设这是人类可读日期的最大长度;如果输入的时间更长,则必须截断它)和Ty = 10(因为“YYYY-MM-DD”为10个长字符)。
In [5]:
Tx = 30
Ty = 10
X, Y, Xoh, Yoh = preprocess_data(dataset, human_vocab, machine_vocab, Tx, Ty)
print("X.shape:", X.shape)
print("Y.shape:", Y.shape)
print("Xoh.shape:", Xoh.shape)
print("Yoh.shape:", Yoh.shape)
X.shape: (10000, 30)
Y.shape: (10000, 10)
Xoh.shape: (10000, 30, 37)
Yoh.shape: (10000, 10, 11)
你现在拥有:
X
:训练集中人类可读日期的处理版本,其中每个字符都由通过human_vocab
映射到该字符的索引替换。每个日期都用特殊字符()进一步填充为 T x T_x Tx值。X.shape = (m, Tx)
Y
:训练集中机器可读日期的处理版本,其中每个字符都被映射为machine_vocab
中映射到的索引替换。你应该具有Y.shape = (m, Ty)
。Xoh
:X
的一个独热版本,由于human_vocab
,将“1”条目的索引映射到该字符。Xoh.shape = (m, Tx, len(human_vocab))
Yoh
:Y
的一个独热版本,由于使用machine_vocab
,因此将“1”条目的索引映射到了该字符。Yoh.shape = (m, Tx, len(machine_vocab))
在这里,因为有11个字符(“-”以及0-9),所以len(machine_vocab) = 11
。
我们再看一些预处理训练集的示例。你可以在下面的单元格中随意使用index
来查看数据集,并查看如何对source/target日期进行预处理。
In [6]:
index = 0
print("Source date:", dataset[index][0])
print("Target date:", dataset[index][1])
print()
print("Source after preprocessing (indices):", X[index])
print("Target after preprocessing (indices):", Y[index])
print()
print("Source after preprocessing (one-hot):", Xoh[index])
print("Target after preprocessing (one-hot):", Yoh[index])
Source date: 9 may 1998
Target date: 1998-05-09
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 36 36 36 36 36]
Target after preprocessing (indices): [ 2 10 10 9 0 1 6 0 1 10]
Source after preprocessing (one-hot): [[0. 0. 0. ... 0. 0. 0.]
[1. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
...
[0. 0. 0. ... 0. 0. 1.]
[0. 0. 0. ... 0. 0. 1.]
[0. 0. 0. ... 0. 0. 1.]]
Target after preprocessing (one-hot): [[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]
2 带注意力机制的神经机器翻译
如果你必须将一本书的段落从法语翻译为英语,则无需阅读整个段落然后关闭该书并进行翻译。即使在翻译过程中,你也会阅读/重新阅读并专注于与你所写下的英语部分相对应的法语段落部分。
注意机制告诉神经机器翻译模型在任何步骤都应该注意到的地方。
2.1 注意力机制
在这一部分中,你将实现讲座视频中介绍的注意力机制。这是一个提醒你该模型如何工作的图。左图显示了注意力模型。右图显示了“注意”步骤用于计算注意变量 α ⟨ t , t ′ ⟩ \alpha^{\langle t, t' \rangle} α⟨t,t′⟩,这些变量用于计算上下文变量 c o n t e x t ⟨ t ⟩ context^{\langle t \rangle} context⟨t⟩输出中的每个时间步长 t = 1 , … , T y t=1, \ldots, T_y t=1,…,Ty。
图1:带注意力机制的神经机器翻译
你可能会注意到以下一些模型属性:
- 此模型中有两个单独的LSTM(请参见左侧的图)。因为图片底部的一个是双向LSTM,并且在“注意力机制”之前出现,所以我们将其称为pre-attention Bi-LSTM。图表顶部的LSTM在注意力机制之后,因此我们将其称为post-attention LSTM。pre-attention Bi-LSTM经过 T x T_x Tx个时间步长;post-attention LSTM经过 T y T_y Ty个时间步长。
- post-attention LSTM 从一个时间步长传递到下一个步长,传递 s ⟨ t ⟩ , c ⟨ t ⟩ s^{\langle t \rangle}, c^{\langle t \rangle} s⟨t⟩,c⟨t⟩ 。在讲座视频中,我们仅将基本RNN用于激活后序列模型,因此RNN输出激活捕获的状态 s ⟨ t ⟩ s^{\langle t\rangle} s⟨t⟩。但是,由于我们在这里使用LSTM,因此LSTM既具有输出激活 s ⟨ t ⟩ s^{\langle t\rangle} s⟨t⟩,也具有隐藏单元状态 c ⟨ t ⟩ c^{\langle t\rangle} c⟨t⟩。但是,与先前的文本生成示例(例如第1周的恐龙)不同,在此模型中,时间t的激活后LSTM不会将特定的生成的 y ⟨ t − 1 ⟩ y^{\langle t-1 \rangle} y⟨t−1⟩作为输入只需将 s ⟨ t ⟩ s^{\langle t\rangle} s⟨t⟩ 和 c ⟨ t ⟩ c^{\langle t\rangle} c⟨t⟩ 作为输入。我们以这种方式设计了模型,因为(与相邻字符高度相关的语言生成不同),在YYYY-MM-DD日期中,上一个字符与下一个字符之间没有那么强的依赖性。
- 我们使用 a ⟨ t ⟩ = [ a → ⟨ t ⟩ ; a ← ⟨ t ⟩ ] a^{\langle t \rangle} = [\overrightarrow{a}^{\langle t \rangle}; \overleftarrow{a}^{\langle t \rangle}] a⟨t⟩=[a⟨t⟩;a⟨t⟩]表示pre-attention Bi-LSTM的正向和反向激活的串联。
- 右图使用
RepeatVector
节点复制 s ⟨ t − 1 ⟩ s^{\langle t-1 \rangle} s⟨t−1⟩的值 T x T_x Tx次,然后使用Concatenation
来连接 s ⟨ t − 1 ⟩ s^{\langle t-1 \rangle} s⟨t−1⟩ 和 a ⟨ t ⟩ a^{\langle t \rangle} a⟨t⟩来计算 e ⟨ t , t ′ ⟩ e^{\langle t, t'\rangle} e⟨t,t′⟩,然后将其传递给softmax以计算 α ⟨ t , t ′ ⟩ \alpha^{\langle t, t' \rangle} α⟨t,t′⟩。我们将在下面的Keras中说明如何使用RepeatVector
和Concatenation
。
让我们实现这个模型。你将从实现one_step_attention()
和 model()
两个函数开始:
1)one_step_attention()
:在步骤t中,给出Bi-LSTM的所有隐藏状态(
[
a
<
1
>
,
a
<
2
>
,
.
.
.
,
a
]
[a^{<1>},a^{<2>}, ..., a^{}]
[a<1>,a<2>,...,a]和第二个LSTM的先前隐藏状态(
s
s^{}
s),one_step_attention()
将计算注意力权重(
[
α
,
α
,
.
.
.
,
α
]
[\alpha^{},\alpha^{}, ..., \alpha^{}]
[α,α,...,α]并输出上下文向量(详细信息请参见图1(右)):$ context^{} = \sum_{t’ = 0}^{T_x} \alpha{}a{}\tag{1} $
请注意,我们在此笔记本中将注意力表示为 c o n t e x t ⟨ t ⟩ context^{\langle t \rangle} context⟨t⟩。在讲座视频中,上下文被表示为 c ⟨ t ⟩ c^{\langle t \rangle} c⟨t⟩,但在这里我们将其称为 c o n t e x t ⟨ t ⟩ context^{\langle t \rangle} context⟨t⟩,以避免与(post-attention)LSTM内部记忆单元变量混淆,有时也称为 c ⟨ t ⟩ c^{\langle t \rangle} c⟨t⟩。
2)model()
:实现整个模型。它首先通过Bi-LSTM运行输入以获取
[
a
<
1
>
,
a
<
2
>
,
.
.
.
,
a
]
[a^{<1>},a^{<2>}, ..., a^{}]
[a<1>,a<2>,...,a]。然后,它调用one_step_attention()
Ty次(“for”循环)。在此循环的每次迭代中,它将计算出上下文向量
c
c^{}
c提供给第二个,并通过具有激活的密集层运行的输出,以生成预测提供给第二个LSTM,并通过具有softmax激活的密集层运行LSTM的输出,以生成预测
y
^
\hat{y}^{}
y^。
练习:实现one_step_attention()
。函数 model()
将使用for循环调用one_step_attention()
T
y
T_y
Ty中的层,重要的是所有
T
y
T_y
Ty副本具有相同的权重。即,它不应该每次都重新初始化权重。换句话说,所有
T
y
T_y
Ty步骤均应具有权重。这是在Keras中实现可共享权重的层的方法:
- 定义层对象(例如,作为全局变量)。
- 在传播输入时调用这些对象。
我们已经将你需要的层定义为全局变量。请运行以下单元格以创建它们。请检查Keras文档以确保你了解这些层是什么:RepeatVector(), Concatenate(), Dense(), Activation(), Dot()。
In [7]:
# Defined shared layers as global variables
repeator = RepeatVector(Tx)
concatenator = Concatenate(axis=-1)
densor1 = Dense(10, activation = "tanh")
densor2 = Dense(1, activation = "relu")
activator = Activation(softmax, name='attention_weights') # We are using a custom softmax(axis = 1) loaded in this notebook
dotor = Dot(axes = 1)
现在你可以使用这些层来实现one_step_attention()
。 为了通过这些层之一传播Keras张量对象X,请使用layer(X)
(如果需要多个输入则使用layer([X,Y])
)。densor(X)
将通过上面定义的 Dense(1)
层传播X。
In [8]:
# GRADED FUNCTION: one_step_attention
def one_step_attention(a, s_prev):
"""
Performs one step of attention: Outputs a context vector computed as a dot product of the attention weights
"alphas" and the hidden states "a" of the Bi-LSTM.
Arguments:
a -- hidden state output of the Bi-LSTM, numpy-array of shape (m, Tx, 2*n_a)
s_prev -- previous hidden state of the (post-attention) LSTM, numpy-array of shape (m, n_s)
Returns:
context -- context vector, input of the next (post-attetion) LSTM cell
"""
### START CODE HERE ###
# 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)
s_prev = repeator(s_prev)
# Use concatenator to concatenate a and s_prev on the last axis (≈ 1 line)
concat = concatenator([a, s_prev])
# Use densor1 to propagate concat through a small fully-connected neural network to compute the "intermediate energies" variable e. (≈1 lines)
e = densor1(concat)
# Use densor2 to propagate e through a small fully-connected neural network to compute the "energies" variable energies. (≈1 lines)
energies = densor2(e)
# Use "activator" on "energies" to compute the attention weights "alphas" (≈ 1 line)
alphas = activator(energies)
# Use dotor together with "alphas" and "a" to compute the context vector to be given to the next (post-attention) LSTM-cell (≈ 1 line)
context = dotor([alphas,a])
### END CODE HERE ###
return context
在对model()
函数进行编码之后,你将能够检查one_step_attention()
的预期输出。
练习:按照图2和上面的文字中的说明实现model()
。再次,我们定义了全局层,这些全局层将共享将在model()
中使用的权重。
In [9]:
n_a = 32
n_s = 64
post_activation_LSTM_cell = LSTM(n_s, return_state = True)
output_layer = Dense(len(machine_vocab), activation=softmax)
现在你可以在for循环中使用这些层 T y T_y Ty次来生成输出,并且它们的参数将不会重新初始化。你将必须执行以下步骤:
- 将输入传播到Bidirectional LSTM
- 迭代
t
=
0
,
…
,
T
y
−
1
t = 0, \dots, T_y-1
t=0,…,Ty−1:
- 在
[
α
,
α
,
.
.
.
,
α
]
和和
s
[\alpha^{},\alpha^{}, ..., \alpha^{}]和和s^{}
[α,α,...,α]和和s上调用
one_step_attention()
以获取上下文向量 c o n t e x t context^{} context。 - 将
c
o
n
t
e
x
t
context^{}
context分配给post-attention LSTM单元。请记住,使用
initial_state= [previous hidden state, previous cell state]
传递此LSTM的前一个隐藏状态 s ⟨ t − 1 ⟩ s^{\langle t-1\rangle} s⟨t−1⟩和单元状态 c ⟨ t − 1 ⟩ c^{\langle t-1\rangle} c⟨t−1⟩。取回新的隐藏状态 s s^{} s和新的单元状态和新的单元状态 c c^{} c。 - 将softmax层应用于 s s^{} s,获得输出。
- 通过将输出添加到输出列表中来保存输出。
- 在
[
α
,
α
,
.
.
.
,
α
]
和和
s
[\alpha^{},\alpha^{}, ..., \alpha^{}]和和s^{}
[α,α,...,α]和和s上调用
- 创建你的Keras模型实例,它应该具有三个输入(“inputs”, s<0> and c<0>)并输出"outputs"列表。
In [10]:
# GRADED FUNCTION: model
def model(Tx, Ty, n_a, n_s, human_vocab_size, machine_vocab_size):
"""
Arguments:
Tx -- length of the input sequence
Ty -- length of the output sequence
n_a -- hidden state size of the Bi-LSTM
n_s -- hidden state size of the post-attention LSTM
human_vocab_size -- size of the python dictionary "human_vocab"
machine_vocab_size -- size of the python dictionary "machine_vocab"
Returns:
model -- Keras model instance
"""
# Define the inputs of your model with a shape (Tx,)
# Define s0 and c0, initial hidden state for the decoder LSTM of shape (n_s,)
X = Input(shape=(Tx, human_vocab_size))
s0 = Input(shape=(n_s,), name='s0')
c0 = Input(shape=(n_s,), name='c0')
s = s0
c = c0
# Initialize empty list of outputs
outputs = []
### START CODE HERE ###
# Step 1: Define your pre-attention Bi-LSTM. Remember to use return_sequences=True. (≈ 1 line)
a = Bidirectional(LSTM(n_a, return_sequences=True))(X)
# Step 2: Iterate for Ty steps
for t in range(Ty):
# Step 2.A: Perform one step of the attention mechanism to get back the context vector at step t (≈ 1 line)
context = one_step_attention(a,s)
# Step 2.B: Apply the post-attention LSTM cell to the "context" vector.
# Don't forget to pass: initial_state = [hidden state, cell state] (≈ 1 line)
s, _, c = post_activation_LSTM_cell(context, initial_state=[s,c])
# Step 2.C: Apply Dense layer to the hidden state output of the post-attention LSTM (≈ 1 line)
out = output_layer(s)
# Step 2.D: Append "out" to the "outputs" list (≈ 1 line)
outputs.append(out)
# Step 3: Create model instance taking three inputs and returning the list of outputs. (≈ 1 line)
model = Model(inputs=[X, s0, c0], outputs=outputs)
### END CODE HERE ###
return model
运行以下单元格以创建模型。
In [11]:
model = model(Tx, Ty, n_a, n_s, len(human_vocab), len(machine_vocab))
WARNING:tensorflow:From /opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
让我们获得模型的总结,以检查其是否与预期输出匹配。
In [12]:
model.summary()
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
input_1 (InputLayer) (None, 30, 37) 0
__________________________________________________________________________________________________
s0 (InputLayer) (None, 64) 0
__________________________________________________________________________________________________
bidirectional_1 (Bidirectional) (None, 30, 64) 17920 input_1[0][0]
__________________________________________________________________________________________________
repeat_vector_1 (RepeatVector) (None, 30, 64) 0 s0[0][0]
lstm_1[0][0]
lstm_1[1][0]
lstm_1[2][0]
lstm_1[3][0]
lstm_1[4][0]
lstm_1[5][0]
lstm_1[6][0]
lstm_1[7][0]
lstm_1[8][0]
__________________________________________________________________________________________________
concatenate_1 (Concatenate) (None, 30, 128) 0 bidirectional_1[0][0]
repeat_vector_1[0][0]
bidirectional_1[0][0]
repeat_vector_1[1][0]
bidirectional_1[0][0]
repeat_vector_1[2][0]
bidirectional_1[0][0]
repeat_vector_1[3][0]
bidirectional_1[0][0]
repeat_vector_1[4][0]
bidirectional_1[0][0]
repeat_vector_1[5][0]
bidirectional_1[0][0]
repeat_vector_1[6][0]
bidirectional_1[0][0]
repeat_vector_1[7][0]
bidirectional_1[0][0]
repeat_vector_1[8][0]
bidirectional_1[0][0]
repeat_vector_1[9][0]
__________________________________________________________________________________________________
dense_1 (Dense) (None, 30, 10) 1290 concatenate_1[0][0]
concatenate_1[1][0]
concatenate_1[2][0]
concatenate_1[3][0]
concatenate_1[4][0]
concatenate_1[5][0]
concatenate_1[6][0]
concatenate_1[7][0]
concatenate_1[8][0]
concatenate_1[9][0]
__________________________________________________________________________________________________
dense_2 (Dense) (None, 30, 1) 11 dense_1[0][0]
dense_1[1][0]
dense_1[2][0]
dense_1[3][0]
dense_1[4][0]
dense_1[5][0]
dense_1[6][0]
dense_1[7][0]
dense_1[8][0]
dense_1[9][0]
__________________________________________________________________________________________________
attention_weights (Activation) (None, 30, 1) 0 dense_2[0][0]
dense_2[1][0]
dense_2[2][0]
dense_2[3][0]
dense_2[4][0]
dense_2[5][0]
dense_2[6][0]
dense_2[7][0]
dense_2[8][0]
dense_2[9][0]
__________________________________________________________________________________________________
dot_1 (Dot) (None, 1, 64) 0 attention_weights[0][0]
bidirectional_1[0][0]
attention_weights[1][0]
bidirectional_1[0][0]
attention_weights[2][0]
bidirectional_1[0][0]
attention_weights[3][0]
bidirectional_1[0][0]
attention_weights[4][0]
bidirectional_1[0][0]
attention_weights[5][0]
bidirectional_1[0][0]
attention_weights[6][0]
bidirectional_1[0][0]
attention_weights[7][0]
bidirectional_1[0][0]
attention_weights[8][0]
bidirectional_1[0][0]
attention_weights[9][0]
bidirectional_1[0][0]
__________________________________________________________________________________________________
c0 (InputLayer) (None, 64) 0
__________________________________________________________________________________________________
lstm_1 (LSTM) [(None, 64), (None, 33024 dot_1[0][0]
s0[0][0]
c0[0][0]
dot_1[1][0]
lstm_1[0][0]
lstm_1[0][2]
dot_1[2][0]
lstm_1[1][0]
lstm_1[1][2]
dot_1[3][0]
lstm_1[2][0]
lstm_1[2][2]
dot_1[4][0]
lstm_1[3][0]
lstm_1[3][2]
dot_1[5][0]
lstm_1[4][0]
lstm_1[4][2]
dot_1[6][0]
lstm_1[5][0]
lstm_1[5][2]
dot_1[7][0]
lstm_1[6][0]
lstm_1[6][2]
dot_1[8][0]
lstm_1[7][0]
lstm_1[7][2]
dot_1[9][0]
lstm_1[8][0]
lstm_1[8][2]
__________________________________________________________________________________________________
dense_3 (Dense) (None, 11) 715 lstm_1[0][0]
lstm_1[1][0]
lstm_1[2][0]
lstm_1[3][0]
lstm_1[4][0]
lstm_1[5][0]
lstm_1[6][0]
lstm_1[7][0]
lstm_1[8][0]
lstm_1[9][0]
==================================================================================================
Total params: 52,960
Trainable params: 52,960
Non-trainable params: 0
__________________________________________________________________________________________________
预期输出:
Here is the summary you should see
Total params: | 185,484 |
---|---|
Trainable params: | 185,484 |
Non-trainable params: | 0 |
bidirectional_1’s output shape | (None, 30, 128) |
repeat_vector_1’s output shape | (None, 30, 128) |
concatenate_1’s output shape | (None, 30, 256) |
attention_weights’s output shape | (None, 30, 1) |
dot_1’s output shape | (None, 1, 128) |
dense_2’s output shape | (None, 11) |
与往常一样,在Keras中创建模型后,你需要对其进行编译并定义要使用的损失,优化器和评价指标。 使用categorical_crossentropy
损失,自定义Adam optimizer(learning rate = 0.005
,
β
1
=
0.9
\beta_1 = 0.9
β1=0.9,
β
2
=
0.999
\beta_2 = 0.999
β2=0.999, decay = 0.01
)和['accuracy']
指标:
In [13]:
### START CODE HERE ### (≈2 lines)
opt = Adam(lr=0.0005, beta_1=0.9, beta_2=0.999, decay=0.01)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
### END CODE HERE ###
最后一步是定义所有输入和输出以适合模型:
- 你已经拥有包含训练示例的维度为 ( m = 10000 , T x = 30 ) (m = 10000, T_x = 30) (m=10000,Tx=30)的X。
- 你需要创建
s0
和c0
以将你的post_activation_LSTM_cell
初始化为0。 - 根据你编码的
model()
,你需要"outputs"作为11个维度元素(m,T_y)的列表。因此:outputs[i][0], ..., outputs[i][Ty]
代表与 i t h i^{th} ith训练示例(X[i]
)。更一般而言,outputs[i][j]
是 i t h i^{th} ith训练示例中 j t h j^{th} jth字符的真实标签。
In [14]:
s0 = np.zeros((m, n_s))
c0 = np.zeros((m, n_s))
outputs = list(Yoh.swapaxes(0,1))
现在让我们拟合模型并运行一个epoch。
In [15]:
model.fit([Xoh, s0, c0], outputs, epochs=1, batch_size=100)
WARNING:tensorflow:From /opt/conda/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.cast instead.
WARNING:tensorflow:From /opt/conda/lib/python3.6/site-packages/tensorflow/python/ops/math_grad.py:102: div (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Deprecated in favor of operator or tf.math.divide.
Epoch 1/1
10000/10000 [==============================] - 23s 2ms/step - loss: 22.0543 - dense_3_loss: 2.7764 - dense_3_acc: 9.0000e-04 - dense_3_acc_1: 0.2327 - dense_3_acc_2: 0.0709 - dense_3_acc_3: 0.0217 - dense_3_acc_4: 0.9262 - dense_3_acc_5: 0.0340 - dense_3_acc_6: 0.0084 - dense_3_acc_7: 0.9422 - dense_3_acc_8: 0.0110 - dense_3_acc_9: 0.0040
Out[15]:
<keras.callbacks.History at 0x7fd60aaac898>
训练时,你可以看到输出的10个位置中的每个位置的损失以及准确性。下表为你提供了一个示例,说明该批次有2个示例时的精确度:
因此,dense_2_acc_8: 0.89
意味着你在当前数据批次中有89%的时间正确预测了输出的第7个字符。
我们对该模型运行了更长的时间,并节省了权重。运行下一个单元格以加载我们的体重。(通过训练模型几分钟,你应该可以获得准确度相似的模型,但是加载我们的模型可以节省你的时间。)
In [16]:
model.load_weights('models/model.h5')
现在,你可以在新示例中查看结果。
In [17]:
EXAMPLES = ['3 May 1979', '5 April 09', '21th of August 2016', 'Tue 10 Jul 2007', 'Saturday May 9 2018', 'March 3 2001', 'March 3rd 2001', '1 March 2001']
for example in EXAMPLES:
source = string_to_int(example, Tx, human_vocab)
source = np.array(list(map(lambda x: to_categorical(x, num_classes=len(human_vocab)), source)))
prediction = model.predict([[source], s0, c0])
prediction = np.argmax(prediction, axis = -1)
output = [inv_machine_vocab[int(i)] for i in prediction]
print("source:", example)
print("output:", ''.join(output))
source: 3 May 1979
output: 1979-05-03
source: 5 April 09
output: 2009-05-05
source: 21th of August 2016
output: 2016-08-21
source: Tue 10 Jul 2007
output: 2007-07-10
source: Saturday May 9 2018
output: 2018-05-09
source: March 3 2001
output: 2001-03-03
source: March 3rd 2001
output: 2001-03-03
source: 1 March 2001
output: 2001-03-01
你也可以更改这些示例,以使用自己的示例进行测试。下一部分将使你更好地了解注意力机制的作用-即生成特定输出字符时网络要注意的输入部分。
3 可视化注意力(可选练习)
由于问题的输出长度固定为10,因此还可以使用10个不同的softmax单元来执行此任务,以生成10个字符的输出。但是注意力模型的一个优点是输出的每个部分(例如月份)都知道它只需要依赖输入的一小部分(输入中代表月份的字符)。我们可以可视化输出的哪一部分正在查看输入的哪一部分。
考虑将"Saturday 9 May 2018"转换为"2018-05-09"的任务。如果我们可视化计算出的 α ⟨ t , t ′ ⟩ \alpha^{\langle t, t' \rangle} α⟨t,t′⟩,我们将得到:
图8 :Full Attention Map
注意输出如何忽略输入的"Saturday"部分。没有一个输出时间步长关注输入的那部分。我们还看到9已被翻译为09,May已被正确翻译为05,而输出则注意进行翻译所需的部分输入。该年份主要要求它注意输入的“18”以生成“2018”。
3.1 从网络获取激活
现在让我们可视化你网络中的注意力值。我们将通过网络传播一个示例,然后可视化 α ⟨ t , t ′ ⟩ \alpha^{\langle t, t' \rangle} α⟨t,t′⟩的值。
为了弄清注意值的位置,让我们开始打印模型摘要。
In [18]:
model.summary()
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
input_1 (InputLayer) (None, 30, 37) 0
__________________________________________________________________________________________________
s0 (InputLayer) (None, 64) 0
__________________________________________________________________________________________________
bidirectional_1 (Bidirectional) (None, 30, 64) 17920 input_1[0][0]
__________________________________________________________________________________________________
repeat_vector_1 (RepeatVector) (None, 30, 64) 0 s0[0][0]
lstm_1[0][0]
lstm_1[1][0]
lstm_1[2][0]
lstm_1[3][0]
lstm_1[4][0]
lstm_1[5][0]
lstm_1[6][0]
lstm_1[7][0]
lstm_1[8][0]
__________________________________________________________________________________________________
concatenate_1 (Concatenate) (None, 30, 128) 0 bidirectional_1[0][0]
repeat_vector_1[0][0]
bidirectional_1[0][0]
repeat_vector_1[1][0]
bidirectional_1[0][0]
repeat_vector_1[2][0]
bidirectional_1[0][0]
repeat_vector_1[3][0]
bidirectional_1[0][0]
repeat_vector_1[4][0]
bidirectional_1[0][0]
repeat_vector_1[5][0]
bidirectional_1[0][0]
repeat_vector_1[6][0]
bidirectional_1[0][0]
repeat_vector_1[7][0]
bidirectional_1[0][0]
repeat_vector_1[8][0]
bidirectional_1[0][0]
repeat_vector_1[9][0]
__________________________________________________________________________________________________
dense_1 (Dense) (None, 30, 10) 1290 concatenate_1[0][0]
concatenate_1[1][0]
concatenate_1[2][0]
concatenate_1[3][0]
concatenate_1[4][0]
concatenate_1[5][0]
concatenate_1[6][0]
concatenate_1[7][0]
concatenate_1[8][0]
concatenate_1[9][0]
__________________________________________________________________________________________________
dense_2 (Dense) (None, 30, 1) 11 dense_1[0][0]
dense_1[1][0]
dense_1[2][0]
dense_1[3][0]
dense_1[4][0]
dense_1[5][0]
dense_1[6][0]
dense_1[7][0]
dense_1[8][0]
dense_1[9][0]
__________________________________________________________________________________________________
attention_weights (Activation) (None, 30, 1) 0 dense_2[0][0]
dense_2[1][0]
dense_2[2][0]
dense_2[3][0]
dense_2[4][0]
dense_2[5][0]
dense_2[6][0]
dense_2[7][0]
dense_2[8][0]
dense_2[9][0]
__________________________________________________________________________________________________
dot_1 (Dot) (None, 1, 64) 0 attention_weights[0][0]
bidirectional_1[0][0]
attention_weights[1][0]
bidirectional_1[0][0]
attention_weights[2][0]
bidirectional_1[0][0]
attention_weights[3][0]
bidirectional_1[0][0]
attention_weights[4][0]
bidirectional_1[0][0]
attention_weights[5][0]
bidirectional_1[0][0]
attention_weights[6][0]
bidirectional_1[0][0]
attention_weights[7][0]
bidirectional_1[0][0]
attention_weights[8][0]
bidirectional_1[0][0]
attention_weights[9][0]
bidirectional_1[0][0]
__________________________________________________________________________________________________
c0 (InputLayer) (None, 64) 0
__________________________________________________________________________________________________
lstm_1 (LSTM) [(None, 64), (None, 33024 dot_1[0][0]
s0[0][0]
c0[0][0]
dot_1[1][0]
lstm_1[0][0]
lstm_1[0][2]
dot_1[2][0]
lstm_1[1][0]
lstm_1[1][2]
dot_1[3][0]
lstm_1[2][0]
lstm_1[2][2]
dot_1[4][0]
lstm_1[3][0]
lstm_1[3][2]
dot_1[5][0]
lstm_1[4][0]
lstm_1[4][2]
dot_1[6][0]
lstm_1[5][0]
lstm_1[5][2]
dot_1[7][0]
lstm_1[6][0]
lstm_1[6][2]
dot_1[8][0]
lstm_1[7][0]
lstm_1[7][2]
dot_1[9][0]
lstm_1[8][0]
lstm_1[8][2]
__________________________________________________________________________________________________
dense_3 (Dense) (None, 11) 715 lstm_1[0][0]
lstm_1[1][0]
lstm_1[2][0]
lstm_1[3][0]
lstm_1[4][0]
lstm_1[5][0]
lstm_1[6][0]
lstm_1[7][0]
lstm_1[8][0]
lstm_1[9][0]
==================================================================================================
Total params: 52,960
Trainable params: 52,960
Non-trainable params: 0
__________________________________________________________________________________________________
浏览上面的model.summary()
的输出。你可以看到,在每个时间步dot_2
计算
t
=
0
,
…
,
T
y
−
1
t = 0, \ldots, T_y-1
t=0,…,Ty−1上下文向量之前,名为attention_weights
的层都会输出维度为(m, 30, 1)的alphas
。让我们从该层获取激活。
函数attention_map()
从模型中提取注意力值并绘制它们。
In [19]:
attention_map = plot_attention_map(model, human_vocab, inv_machine_vocab, "Tuesday 09 Oct 1993", num = 7, n_s = 64)
<Figure size 432x288 with 0 Axes>
在生成的图上,你可以观察预测输出的每个字符的注意权重值。检查此图,并检查网络对你的关注是否有意义。
在日期转换应用程序中,你会发现大部分时间的注意力都有助于预测年份,并且对预测日期/月份没有太大影响。
恭喜!你已结束本作业
这是你在此笔记本中应记住的内容:
- 机器翻译模型可用于从一个序列映射到另一个序列。它们不仅对翻译人类语言(如法语->英语)有用,而且对日期格式翻译等任务也很有用。
- 注意机制允许网络在产生输出的特定部分时将注意力集中在输入的最相关部分。
- 使用注意力机制的网络可以将长度为 T x T_x Tx的输入转换为长度为 T y T_y Ty的输出,其中 T x T_x Tx和 T y T_y Ty可以不同。
- 你可以可视化注意权重 α ⟨ t , t ′ ⟩ \alpha^{\langle t,t' \rangle} α⟨t,t′⟩,以查看网络在生成每个输出时要注意的内容。
恭喜你完成此作业! 现在,你可以实现注意力模型,并使用它来学习从一个序列到另一个序列的复杂映射。