Allennlp-Based Sentiment Analysis with Pre-trained Model

  • Share this:

Code introduction


This function uses a pre-trained text classification model from the Allennlp library to perform sentiment analysis. It takes a piece of text as input and then uses the pre-trained model to predict the sentiment label of the text.


Technology Stack : Allennlp

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def random_sentiment_analysis(text):
    from allennlp.predictors import TextClassifierPredictor
    from allennlp.data import Sentence
    from allennlp.data import Instance
    from allennlp.data.fields import TextField
    from allennlp.models import saved_model

    # Load the pre-trained model
    model = saved_model.load('https://storage.googleapis.com/allennlp-public-models/bert-base-sentiment-analysis-2020.11.19.tar.gz')
    predictor = TextClassifierPredictor.from_path(model)

    # Create an instance from the text
    sentence = Sentence(text)
    instance = Instance({'text': TextField(sentence)})

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

    return prediction.label                
              
Tags: