感情分析CNNモデルのテスト
モデルの学習が完了したので、PyBooks は新しい書評で性能を確認したいと考えています。
レビューの感情がポジティブかネガティブかを判定します。
次のパッケージはインポート済みです:
torch、torch.nn は nn、torch.nn.functional は F、torch.optim は optim。
vocab_size と embed_dim を引数にした TextClassificationCNN() のインスタンスも読み込まれており、model として保存されています。
この演習はコースの一部です
PyTorch で学ぶテキストの Deep Learning
演習の手順
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")