Thanks to theidioms.com









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

Sentiment Analysis using Python and Deep Learning
Data Science

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



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}]

Build your data skills online by learning Python, SQL, R, Excel, and much more: Join Datacamp!


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

Leave your thought here

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