Login

Register

Login

Register

✆+91-9916812177 | contact@beingdatum.com

Step-by-Step Guide for building Sentiment Analysis model using Flask/Flair

Guide for building Sentiment Analysis model using Flask/Flair

Sentiment Analysis is the process of computationally identifying and categorizing opinions expressed in a piece of text, especially in order to determine whether the writer’s attitude towards a particular topic, product, etc. is positive, negative, or neutral.

Flair is:

  • A powerful NLP library. Flair allows to apply the state-of-the-art natural language processing (NLP) models to input text, such as named entity recognition (NER), part-of-speech tagging (PoS), sense disambiguation and classification.
  • Multilingual. Thanks to the Flair community, because of which they support a rapidly growing number of languages. They also now include ‘one model, many languages‘ taggers, i.e. single models that predict PoS or NER tags for input text in various languages.
  • A text embedding library. Flair has simple interfaces that allow you to use and combine different word and document embedding, BERT embedding and ELMo embedding.
  • A PyTorch NLP framework. The framework builds directly on PyTorch, making it easy to train your own models and experiment with new approaches using Flair embedding and classes.

    Further information can be found here

 

After completing this tutorial, you will know:

  • How to build sentiment analysis Micro-service with flair and flask framework.

 

Installing flair & flask packages

To install Flair and Flask we will use pip as shown below:

$ conda install pytorch torchvision cudatoolkit=9.0 -c pytorch
$ pip install flair flask

The above command will install all the required packages needed to build our Micro-service. It will also install PyTorch which flair uses to do the heavy lifting.

 

 

Loading Page of our Sentiment Analysis App

Importing flask module in the project is mandatory. An object of Flask class is our WSGI application. Flask constructor takes the name of current module (__name__) as argument. The route() function of the Flask class is a decorator, which tells the application which URL should call the associated function.

from flask import abort, Flask, request
from flair.models import TextClassifier
from flair.data import Sentence
from flask import render_template

app = Flask(__name__)

@app.route("/")
def loadPage():
	return render_template('home.html', query="")

 

Defining the classifier

  • Import TextClassifier and Sentence classes from flair package
  • Next, we load the model related to sentiment analysis en-sentiment. The sentiment analysis model is based on IMDB dataset. When the below line runs, it will download the sentiment analysis model and store it into the .flair sub-folder of the home directory. This will take few minutes depending on your internet speed.
classifier = TextClassifier.load('en-sentiment')

 

Defining the POST method to be called

@app.route('/', methods=['POST'])
def sentimentAnalysis():

We will now go through the contents inside our method “sentimentAnalysis” line by line for a better understanding.

The text passed being passed from the front end is captured here as inputQuery, and the .predict function is called, which tells us the sentiment of the text along with the label.score, and the response is captured and sent back to the front end.

@app.route('/', methods=['POST'])
def sentimentAnalysis():
    inputQuery = request.form['query']
    sentence = Sentence(inputQuery)
    classifier.predict(sentence)
    print('Sentiment: ', sentence.labels)
    label = sentence.labels[0]
    labscore = (label.score)*100
    response = {'result': label.value, 'score':"%.2f" % labscore}
    return render_template('home.html', query=inputQuery, output=response)

Finally the run() method of Flask class runs the application on the local development server.

if __name__ == "__main__":
    app.run()

The above given Python script is executed from Python shell.

python app.py

The shell looks like the below, once it’s seen open the URL: localhost:5000/ in the browser, and you can test your application.

The application looks like this:

flask/flair app frontend

Note: This is the simplest version of Sentiment Analysis done by the help of the TextClassifier. The main motive was to convert our Python codes to Flask API’s so that it can be deploy-able.

To understand more on how to convert Machine learning models to Flask API’s, please go through similar posts.

 

Keep following us at beingdatum, cheers!!

2 responses on "Step-by-Step Guide for building Sentiment Analysis model using Flask/Flair"

  1. Hi, I really enjoyed your post, but how can I do the same to translate from one language to another.
    I have trained my data-set using the code(Transformer with tensorflow 2 I found on the internet and it works fine but the challenge is in on how to deploy it

  2. how can I use the same approach to deploy a translation model(transformer with TensorFlow 2.0)

Leave a Message

Your email address will not be published. Required fields are marked *

© BeingDatum. All rights reserved.
X