构建带注意力机制的 RNN 模型
在 PyBooks,团队一直在探索多种深度学习架构。经过调研,您决定实现一个带注意力机制(Attention)的 RNN,用来预测句子中的下一个词。系统已为您提供由句子构建的数据集以及基于它们生成的词表。
已为您导入以下包:torch、nn。
已为您预加载以下内容:
vocab和vocab_size:词汇表及其大小word_to_ix和ix_to_word:词到索引、索引到词的映射字典input_data和target_data:转换后的输入-输出配对数据集embedding_dim和hidden_dim:嵌入向量(embedding — 向量表示)维度与 RNN 隐状态维度
您可以在控制台中查看变量 data,以了解示例句子。
本练习是课程的一部分
使用 PyTorch 的文本深度学习
练习说明
- 为给定词表创建一个维度为
embedding_dim的嵌入层。 - 对 RNN 的序列输出应用线性变换,得到注意力分数。
- 根据分数计算注意力权重。
- 将 RNN 输出与注意力权重做加权求和,计算上下文向量。
交互式实操练习
通过完成这段示例代码来试试这个练习。
class RNNWithAttentionModel(nn.Module):
def __init__(self):
super(RNNWithAttentionModel, self).__init__()
# Create an embedding layer for the vocabulary
self.embeddings = nn.____(vocab_size, embedding_dim)
self.rnn = nn.RNN(embedding_dim, hidden_dim, batch_first=True)
# Apply a linear transformation to get the attention scores
self.attention = nn.____(____, 1)
self.fc = nn.____(hidden_dim, vocab_size)
def forward(self, x):
x = self.embeddings(x)
out, _ = self.rnn(x)
# Get the attention weights
attn_weights = torch.nn.functional.____(self.____(out).____(2), dim=1)
# Compute the context vector
context = torch.sum(____.____(2) * out, dim=1)
out = self.fc(context)
return out
attention_model = RNNWithAttentionModel()
optimizer = torch.optim.Adam(attention_model.parameters(), lr=0.01)
criterion = nn.CrossEntropyLoss()
print("Model Instantiated")