開始使用免費開始

測試情感分析 CNN 模型

現在模型已經訓練完成,PyBooks 想用一些新的書評來檢查它的表現。

你需要判斷每則評論的情感是正向還是負向。

以下套件已為你匯入: torchtorch.nn 作為 nntorch.nn.functional 作為 Ftorch.optim 作為 optim

一個以 vocab_sizeembed_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")
編輯並執行程式碼