Testing the Sentiment Analysis CNN Model
Now that model is trained, PyBooks wants to check its performance on some new book reviews.
You need to check if the sentiment in a review is positive or negative.
The following packages have been imported for you:
torch
, torch.nn
as nn
, torch.nn.functional
as F
, torch.optim
as optim
.
An instance of TextClassificationCNN()
with arguments vocab_size
and embed_dim
has also been loaded and saved as model
.
This exercise is part of the course
Deep Learning for Text with PyTorch
Exercise instructions
- Iterate over the
book_reviews
list, converting the words in each review into a tensor. - Get the model's output for each
input_tensor
. - Find the index of the most likely sentiment category from the
outputs.data
. - Extract and convert the
predicted_label
item into a sentiment string where1
is a "Positive" label.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
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")