เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

ทดสอบโมเดล 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")
แก้ไขและรันโค้ด