Bird
Raised Fist0
NlpProgramBeginner · 2 min read

NLP Program to Analyze Sentiment with Example

Use the Hugging Face transformers library with pipeline('sentiment-analysis') to create an NLP program that analyzes sentiment, like from transformers import pipeline; sentiment = pipeline('sentiment-analysis'); print(sentiment('I love this!')).
📋

Examples

InputI love this product!
Output[{'label': 'POSITIVE', 'score': 0.9998}]
InputThis is the worst movie I have ever seen.
Output[{'label': 'NEGATIVE', 'score': 0.9997}]
Input
Output[]
🧠

How to Think About It

To analyze sentiment, the program takes a text input and uses a pre-trained model to classify the text as positive or negative. The model looks at the words and their context to decide the overall feeling. We use a ready-made tool that handles this complex task so we only need to give it the text and get the sentiment result.
📐

Algorithm

1
Import the sentiment analysis tool from the NLP library.
2
Create a sentiment analysis pipeline or model instance.
3
Input the text to analyze.
4
Run the text through the model to get sentiment prediction.
5
Output the sentiment label and confidence score.
💻

Code

python
from transformers import pipeline

sentiment = pipeline('sentiment-analysis')

texts = [
    'I love this product!',
    'This is the worst movie I have ever seen.',
    ''
]

for text in texts:
    result = sentiment(text) if text else []
    print(f'Text: "{text}" -> Sentiment: {result}')
Output
Text: "I love this product!" -> Sentiment: [{'label': 'POSITIVE', 'score': 0.9998}] Text: "This is the worst movie I have ever seen." -> Sentiment: [{'label': 'NEGATIVE', 'score': 0.9997}] Text: "" -> Sentiment: []
🔍

Dry Run

Let's trace the input 'I love this product!' through the code.

1

Import pipeline

Load the sentiment-analysis pipeline from transformers.

2

Create sentiment pipeline

sentiment = pipeline('sentiment-analysis') creates the model ready to analyze text.

3

Input text

Text to analyze: 'I love this product!'

4

Run analysis

Call sentiment('I love this product!') which returns [{'label': 'POSITIVE', 'score': 0.9998}]

5

Print output

Prints: Text: "I love this product!" -> Sentiment: [{'label': 'POSITIVE', 'score': 0.9998}]

StepInput TextOutput Sentiment
1I love this product![{'label': 'POSITIVE', 'score': 0.9998}]
💡

Why This Works

Step 1: Use pre-trained model

The pipeline('sentiment-analysis') loads a model trained on many texts to understand positive or negative feelings.

Step 2: Input text processing

The model reads the input text and converts it into numbers it can understand.

Step 3: Prediction output

The model outputs a label like POSITIVE or NEGATIVE with a confidence score showing how sure it is.

🔄

Alternative Approaches

TextBlob library
python
from textblob import TextBlob

def analyze_sentiment(text):
    blob = TextBlob(text)
    polarity = blob.sentiment.polarity
    label = 'POSITIVE' if polarity > 0 else 'NEGATIVE' if polarity < 0 else 'NEUTRAL'
    return {'label': label, 'score': abs(polarity)}

print(analyze_sentiment('I love this product!'))
TextBlob is simpler and faster but less accurate than transformer models.
VADER Sentiment Analyzer
python
from nltk.sentiment import SentimentIntensityAnalyzer

sia = SentimentIntensityAnalyzer()

text = 'I love this product!'
scores = sia.polarity_scores(text)
label = 'POSITIVE' if scores['compound'] > 0 else 'NEGATIVE' if scores['compound'] < 0 else 'NEUTRAL'
print({'label': label, 'score': scores['compound']})
VADER works well for social media text and is lightweight but less nuanced.

Complexity: O(n) time, O(n) space

Time Complexity

The time depends linearly on the length of the input text n because the model processes each token once.

Space Complexity

Space grows with input size n to store tokenized text and intermediate model states.

Which Approach is Fastest?

TextBlob and VADER are faster but less accurate; transformer pipelines are slower but provide better results.

ApproachTimeSpaceBest For
Hugging Face pipelineO(n)O(n)High accuracy, general use
TextBlobO(n)O(n)Simple, fast, less accurate
VADERO(n)O(n)Social media, lightweight
💡
Use Hugging Face's pipeline('sentiment-analysis') for quick and accurate sentiment analysis without training your own model.
⚠️
Beginners often forget to handle empty input strings, which can cause errors or empty results.