การสร้างโมเดล RNN พร้อม Attention
ทีมงานของ PyBooks กำลังศึกษาสถาปัตยกรรม deep learning หลากหลายรูปแบบ หลังจากค้นคว้าข้อมูล คุณตัดสินใจนำ RNN ที่มี Attention mechanism มาใช้เพื่อทำนายคำถัดไปในประโยค โดยมีชุดข้อมูลที่ประกอบด้วยประโยคต่าง ๆ และ vocabulary ที่สร้างจากชุดข้อมูลนั้น
แพ็กเกจต่อไปนี้ถูก import ไว้ให้แล้ว: torch, nn
ตัวแปรต่อไปนี้ถูกโหลดไว้ให้แล้ว:
vocabและvocab_size: ชุด vocabulary และขนาดของมันword_to_ixและix_to_word: dictionary สำหรับการแมปคำกับดัชนี และดัชนีกับคำinput_dataและtarget_data: ชุดข้อมูลที่แปลงเป็นคู่ input-output แล้วembedding_dimและhidden_dim: มิติสำหรับ embedding และ hidden state ของ RNN
สามารถตรวจสอบตัวแปร data ใน console เพื่อดูตัวอย่างประโยคได้
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Deep Learning สำหรับข้อความด้วย PyTorch
คำแนะนำการฝึกหัด
- สร้าง embedding layer สำหรับ vocabulary โดยใช้
embedding_dimที่กำหนดให้ - ใช้การแปลงเชิงเส้นกับ sequence output ของ RNN เพื่อคำนวณ attention scores
- คำนวณ attention weights จาก scores ที่ได้
- คำนวณ context vector จากผลรวมถ่วงน้ำหนักของ RNN outputs และ attention weights
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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")