LoslegenKostenlos loslegen

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.

Diese Übung ist Teil des Kurses

Deep Learning for Text with PyTorch

Kurs anzeigen

Anleitung zur Übung

  • 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 where 1 is a "Positive" label.

Interaktive Übung

Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.

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")
Code bearbeiten und ausführen