ทดสอบโมเดล CNN วิเคราะห์ความรู้สึก
เมื่อฝึกโมเดลเสร็จแล้ว PyBooks ต้องการตรวจสอบประสิทธิภาพของโมเดลกับรีวิวหนังสือใหม่
ให้ตรวจสอบว่ารีวิวแต่ละรายการมีความรู้สึกเชิงบวกหรือเชิงลบ
แพ็กเกจต่อไปนี้ถูก import มาให้แล้ว:
torch, torch.nn as nn, torch.nn.functional as F, torch.optim as optim
นอกจากนี้ยังมีอินสแตนซ์ของ TextClassificationCNN() ที่ระบุอาร์กิวเมนต์ vocab_size และ embed_dim โหลดไว้แล้วในตัวแปร model
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Deep Learning สำหรับข้อความด้วย PyTorch
คำแนะนำการฝึกหัด
- วนซ้ำผ่านรายการ
book_reviewsแล้วแปลงคำในแต่ละรีวิวให้เป็น tensor - นำ
input_tensorแต่ละตัวผ่านโมเดลเพื่อรับผลลัพธ์ - หาดัชนีของหมวดความรู้สึกที่มีโอกาสสูงสุดจาก
outputs.data - ดึงค่าของ
predicted_labelแล้วแปลงเป็น string แสดงความรู้สึก โดยที่1หมายถึง "Positive"
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
book_reviews = [
"I love this book".split(),
"I do not like this book".split()
]
for review in book_reviews:
# Convert the review words into tensor form
input_tensor = ____.____([word_to_ix[w] for w in review], dtype=torch.long).unsqueeze(0)
# Get the model's output
outputs = model(____)
# Find the index of the most likely sentiment category
_, predicted_label = ____.____(outputs.data, 1)
# Convert the predicted label into a sentiment string
sentiment = "Positive" if ____ else "Negative"
print(f"Book Review: {' '.join(review)}")
print(f"Sentiment: {sentiment}\n")