建立具備注意力機制的 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,看看範例句子。
本練習屬於課程
Deep Learning for Text with 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")