การฝึกและทดสอบโมเดล Transformer
เมื่อมีโมเดล TransformerEncoder พร้อมแล้ว ขั้นตอนถัดไปของ PyBooks คือการฝึกโมเดลด้วยรีวิวตัวอย่างและประเมินประสิทธิภาพ การฝึกด้วยรีวิวเหล่านี้จะช่วยให้ PyBooks เข้าใจแนวโน้มความรู้สึก (sentiment) ในคลังข้อมูลขนาดใหญ่ของตน เมื่อโมเดลมีประสิทธิภาพดีพอ PyBooks จะสามารถวิเคราะห์ sentiment โดยอัตโนมัติ เพื่อให้คำแนะนำและ feedback ที่มีประโยชน์แก่ผู้อ่าน
แพ็กเกจต่อไปนี้ถูกนำเข้าให้แล้ว: torch, nn, optim
อินสแตนซ์ model ของคลาส TransformerEncoder, token_embeddings รวมถึง train_sentences, train_labels, test_sentences และ test_labels ถูกโหลดไว้ให้เรียบร้อยแล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Deep Learning สำหรับข้อความด้วย PyTorch
คำแนะนำการฝึกหัด
- ในลูปการฝึก ให้แบ่งประโยคเป็นโทเค็นและ stack embedding เข้าด้วยกัน
- รีเซ็ตค่า gradient เป็นศูนย์ จากนั้นทำ backward pass
- ในฟังก์ชัน
predictให้ปิดการคำนวณ gradient แล้วดึงค่าการทำนาย sentiment
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
for epoch in range(5):
for sentence, label in zip(train_sentences, train_labels):
# Split the sentences into tokens and stack the embeddings
tokens = ____
data = torch.____([token_embeddings[token] for token in ____], dim=1)
output = model(data)
loss = criterion(output, torch.tensor([label]))
# Zero the gradients and perform a backward pass
optimizer.____()
loss.____()
optimizer.step()
print(f"Epoch {epoch}, Loss: {loss.item()}")
def predict(sentence):
model.eval()
# Deactivate the gradient computations and get the sentiment prediction.
with torch.____():
tokens = sentence.split()
data = torch.stack([token_embeddings.get(token, torch.rand((1, 512))) for token in tokens], dim=1)
output = model(data)
predicted = torch.____(output, dim=1)
return "Positive" if predicted.item() == 1 else "Negative"
sample_sentence = "This product can be better"
print(f"'{sample_sentence}' is {predict(sample_sentence)}")