Predict Sentiment Using Allennlp in Python

  • Share this:

Code introduction


This function uses the Allennlp third-party library to predict the sentiment of a given text. It first loads the sentiment analysis model from a specified URL, then tokenizes the input text, creates an instance, and uses the model for prediction.


Technology Stack : Allennlp, Predictor, Instance, TextField, Tokenizer

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
from allennlp.predictors import Predictor
from allennlp.data import Instance
from allennlp.data.tokenizers import Tokenizer
from allennlp.data.fields import TextField

def predict_sentiment(text):
    """
    Predicts the sentiment of a given text using the Allennlp's Sentiment Analysis model.
    """
    # Load the sentiment analysis predictor
    predictor = Predictor.from_path("https://storage.googleapis.com/allennlp-public-models/sentiment-analysis-2020.11.01.tar.gz")

    # Tokenize the input text
    tokenizer = Tokenizer()
    tokens = tokenizer.tokenize(text)

    # Create an instance from the tokens
    instance = Instance(TextField(tokens))

    # Predict the sentiment
    prediction = predictor.predict(instance)

    return prediction