測試情感分析 CNN 模型
現在模型已經訓練完成,PyBooks 想用一些新的書評來檢查它的表現。
你需要判斷每則評論的情感是正向還是負向。
以下套件已為你匯入:
torch、torch.nn 作為 nn、torch.nn.functional 作為 F、torch.optim 作為 optim。
一個以 vocab_size 和 embed_dim 作為引數建立的 TextClassificationCNN() 實例也已載入並儲存為 model。
本練習屬於課程
Deep Learning for Text with PyTorch
練習說明
- 逐一走訪
book_reviews清單,將每則評論中的單字轉換為張量。 - 取得每個
input_tensor對應的模型輸出。 - 從
outputs.data中找出最可能的情感類別索引。 - 擷取並轉換
predicted_label的項目為情感字串,其中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")