Sentiment Analysis using Python and Deep Learning in 3 lines of code

Greetings! Some links on this site are affiliate links. That means that, if you choose to make a purchase, The Click Reader may earn a small commission at no extra cost to you. We greatly appreciate your support!

Learn to perform sentiment analysis using the transformers library from Hugging Face in just 3 lines of code with Python and Deep Learning.


Sentiment analysis is the process of determining whether a piece of writing is positive, negative, or neutral. This kind of analysis is very helpful when trying to extract insights from product or service reviews, customer feedbacks, and much more.

First, let us install the transformers library for sentiment analysis,

pip install transformers

Next, importing the pipeline function from the transformers library,

# Importing the pipeline function from the transformers library
from transformers import pipeline
Pipeline Method

The pipeline method is responsible for:

  • Pre-processing: Converting raw text input to numerical input for the pre-trained GPT-2 model
  • Model Inference: Making a prediction using the pre-trained GPT-2 model
  • Post-processing: Converting prediction to a proper output

Calling the pipeline function by specifying the task as ‘sentiment-analysis’ and model as ‘distilbert-base-uncased-finetuned-sst-2-english’,

# Creating a TextClassificationPipeline for Sentiment Analysis
pipe = pipeline(task='sentiment-analysis', model='distilbert-base-uncased-finetuned-sst-2-english')

The DistilBERT is a transformers model, smaller and faster than BERT, which was pretrained on the same corpus in a self-supervised fashion, using the BERT base model as a teacher. This means it was pretrained on the raw texts only, with no humans labelling them in any way (which is why it can use lots of publicly available data) with an automatic process to generate inputs and labels from those texts using the BERT base model.

It’s time to perform sentiment analysis! We can use the TextClassificationPipeline, that is, pipe in the following way to perform sentiment analysis,

# Analyzing sentiment
pipe("I like this hat.")
[{'label': 'POSITIVE', 'score': 0.9995846152305603}]

Sentiment Analysis using Python and Deep Learning in 3 lines of codeSentiment Analysis using Python and Deep Learning in 3 lines of code

Do you want to learn Python, Data Science, and Machine Learning while getting certified? Here are some best selling Datacamp courses that we recommend you enroll in:

  1. Introduction to Python (Free Course) - 1,000,000+ students already enrolled!
  2. Introduction to Data Science  in Python- 400,000+ students already enrolled!
  3. Introduction to TensorFlow for Deep Learning with Python - 90,000+ students already enrolled!
  4. Data Science and Machine Learning Bootcamp with R - 70,000+ students already enrolled!

Leave a Comment