0
0
NLPml~5 mins

Sentiment analysis pipeline in NLP

Choose your learning style9 modes available
Introduction

We use a sentiment analysis pipeline to quickly find out if text feels positive, negative, or neutral. It helps us understand opinions in reviews, tweets, or messages without reading all of them.

Checking if customer reviews are happy or unhappy about a product.
Understanding public mood from social media posts during events.
Sorting emails or feedback into positive or negative categories automatically.
Helping chatbots respond better by knowing user feelings.
Analyzing survey answers to see general satisfaction.
Syntax
NLP
from transformers import pipeline

sentiment_pipeline = pipeline('sentiment-analysis')
results = sentiment_pipeline(['I love this!', 'This is bad.'])

The pipeline function loads a ready-to-use model for sentiment analysis.

Input is a list of texts, and output gives labels like 'POSITIVE' or 'NEGATIVE' with scores.

Examples
Simple example to analyze one sentence and print the sentiment result.
NLP
from transformers import pipeline

sentiment = pipeline('sentiment-analysis')
print(sentiment(['I am happy']))
Analyze multiple sentences and print each label with confidence score.
NLP
from transformers import pipeline

sentiment = pipeline('sentiment-analysis')
texts = ['I hate waiting.', 'What a wonderful day!']
results = sentiment(texts)
for r in results:
    print(f"Label: {r['label']}, Score: {r['score']:.2f}")
Sample Model

This program uses a ready-made sentiment analysis model to classify three example sentences. It prints the sentiment label and confidence score for each.

NLP
from transformers import pipeline

# Load the sentiment analysis pipeline
sentiment = pipeline('sentiment-analysis')

# Sample texts to analyze
texts = [
    'I love this product, it works great!',
    'This is the worst experience I have ever had.',
    'It is okay, not too bad but not great either.'
]

# Get sentiment results
results = sentiment(texts)

# Print results
for text, result in zip(texts, results):
    print(f"Text: {text}")
    print(f"Sentiment: {result['label']}, Confidence: {result['score']:.2f}")
    print()
OutputSuccess
Important Notes

The pipeline uses a model trained on many examples to guess sentiment quickly.

Confidence scores close to 1 mean the model is very sure about its prediction.

Sometimes neutral or mixed feelings may be labeled as positive or negative depending on the model.

Summary

Sentiment analysis pipeline helps find feelings in text automatically.

It is easy to use with just a few lines of code.

Useful for understanding opinions in many real-life situations.