NLP Program to Analyze Sentiment with Example
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
How to Think About It
Algorithm
Code
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}')
Dry Run
Let's trace the input 'I love this product!' through the code.
Import pipeline
Load the sentiment-analysis pipeline from transformers.
Create sentiment pipeline
sentiment = pipeline('sentiment-analysis') creates the model ready to analyze text.
Input text
Text to analyze: 'I love this product!'
Run analysis
Call sentiment('I love this product!') which returns [{'label': 'POSITIVE', 'score': 0.9998}]
Print output
Prints: Text: "I love this product!" -> Sentiment: [{'label': 'POSITIVE', 'score': 0.9998}]
| Step | Input Text | Output Sentiment |
|---|---|---|
| 1 | I 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
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!'))
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']})
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Hugging Face pipeline | O(n) | O(n) | High accuracy, general use |
| TextBlob | O(n) | O(n) | Simple, fast, less accurate |
| VADER | O(n) | O(n) | Social media, lightweight |
pipeline('sentiment-analysis') for quick and accurate sentiment analysis without training your own model.