EmpezarEmpieza gratis

Prueba del modelo CNN de análisis de sentimiento

Ahora que el modelo está entrenado, PyBooks quiere comprobar su rendimiento con algunas reseñas nuevas de libros.

Necesitas verificar si el sentimiento en una reseña es positivo o negativo.

Se han importado los siguientes paquetes por ti: torch, torch.nn como nn, torch.nn.functional como F, torch.optim como optim.

También se ha cargado una instancia de TextClassificationCNN() con los argumentos vocab_size y embed_dim, y se ha guardado como model.

Este ejercicio forma parte del curso

Deep Learning para texto con PyTorch

Ver curso

Instrucciones del ejercicio

  • Recorre la lista book_reviews, convirtiendo las palabras de cada reseña en un tensor.
  • Obtén la salida del modelo para cada input_tensor
  • Encuentra el índice de la categoría de sentimiento más probable en outputs.data.
  • Extrae y convierte el elemento predicted_label en una cadena de sentimiento donde 1 es la etiqueta "Positive".

ejercicio interactivo práctico

Prueba este ejercicio completando este código de ejemplo.

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")
Editar y ejecutar código