การฝึกและทดสอบโมเดล RNN ร่วมกับ Attention
ทีมงานที่ PyBooks ได้สร้างโมเดล RNN สำหรับทำนายคำโดยไม่มี attention mechanism มาก่อนหน้านี้ โมเดลเริ่มต้นนี้เรียกว่า rnn_model ซึ่งได้รับการฝึกแล้วและโหลดไว้ให้เรียบร้อย ภารกิจของคุณคือฝึก RNNWithAttentionModel ตัวใหม่ แล้วเปรียบเทียบผลการทำนายกับ rnn_model เดิม
สิ่งต่อไปนี้ถูกโหลดไว้ให้แล้ว:
inputs: รายการของ input sequence ในรูปแบบ tensortargets: tensor ที่เก็บคำเป้าหมายสำหรับแต่ละ input sequenceoptimizer: ฟังก์ชัน Adam optimizercriterion: ฟังก์ชัน CrossEntropyLosspad_sequences: ฟังก์ชันสำหรับ pad input sequence เพื่อใช้ในการ batchingattention_model: คลาสโมเดลที่กำหนดไว้จากแบบฝึกหัดก่อนหน้าrnn_model: โมเดล RNN ที่ฝึกแล้วจากทีม PyBooks
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Deep Learning สำหรับข้อความด้วย PyTorch
คำแนะนำการฝึกหัด
- ตั้งค่าโมเดล RNN ให้อยู่ในโหมดประเมินผลก่อนทดสอบด้วยข้อมูล test
- รับผลลัพธ์จาก RNN โดยส่ง input ที่เหมาะสมเข้าไปในโมเดล RNN
- ดึงคำที่มีคะแนนการทำนายสูงสุดออกจากผลลัพธ์ของ RNN
- ในทำนองเดียวกัน สำหรับ attention model ให้ดึงคำที่มีคะแนนการทำนายสูงสุดออกจากผลลัพธ์ของ attention
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
for epoch in range(epochs):
attention_model.train()
optimizer.zero_grad()
padded_inputs = pad_sequences(inputs)
outputs = attention_model(padded_inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
for input_seq, target in zip(input_data, target_data):
input_test = torch.tensor(input_seq, dtype=torch.long).unsqueeze(0)
# Set the RNN model to evaluation mode
rnn_model.____()
# Get the RNN output by passing the appropriate input
rnn_output = ____(____)
# Extract the word with the highest prediction score
rnn_prediction = ix_to_word[torch.____(____).item()]
attention_model.eval()
attention_output = attention_model(input_test)
# Extract the word with the highest prediction score
attention_prediction = ix_to_word[torch.____(____).item()]
print(f"\nInput: {' '.join([ix_to_word[ix] for ix in input_seq])}")
print(f"Target: {ix_to_word[target]}")
print(f"RNN prediction: {rnn_prediction}")
print(f"RNN with Attention prediction: {attention_prediction}")