测试情感分析 CNN 模型
现在模型已经训练完毕,PyBooks 想在一些新的图书评论上检查其表现。
您需要判断每条评论的情感是正面还是负面。
以下包已为您导入:
torch、将 torch.nn 导入为 nn、将 torch.nn.functional 导入为 F、将 torch.optim 导入为 optim。
同时,带有参数 vocab_size 和 embed_dim 的 TextClassificationCNN() 实例也已加载并保存为 model。
本练习是课程的一部分
使用 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")