Sentiment Analysis
Sentiment analysis determines the emotional tone of a piece of text: positive, negative, or neutral. It is one of the most widely used NLP applications in business.
What Sentiment Analysis Does
Sentiment analysis reads text and classifies the writer's emotional attitude.
Input: 'The customer service was absolutely terrible and I will never come back'
Output: Negative (95% confidence)
Input: 'The product exceeded my expectations in every way'
Output: Positive (97% confidence)
Businesses use this to:
- Monitor brand perception on social media
- Analyze product reviews at scale
- Track customer support ticket urgency
- Understand public reaction to news events or product launches
Deep Learning ⊂ Machine Learning ⊂ Artificial Intelligence
Simple Sentiment Analysis
# Rule-based sentiment analysis (illustrates the concept)
# Real models use deep learning trained on millions of labeled reviews
positive_words = {
"great", "excellent", "amazing", "fantastic", "wonderful", "love",
"perfect", "best", "brilliant", "outstanding", "happy", "recommend",
"helpful", "easy", "fast", "reliable", "impressive"
}
negative_words = {
"terrible", "awful", "horrible", "hate", "worst", "bad", "poor",
"broken", "useless", "disappointed", "frustrating", "slow", "waste",
"never", "problem", "difficult", "annoying", "terrible"
}
def analyze_sentiment(text):
"""Simple rule-based sentiment classifier."""
words = text.lower().split()
positive_count = sum(1 for w in words if w.strip("!.,?") in positive_words)
negative_count = sum(1 for w in words if w.strip("!.,?") in negative_words)
score = positive_count - negative_count
if score > 0:
label = "Positive"
confidence = min(0.5 + score * 0.1, 0.99)
elif score < 0:
label = "Negative"
confidence = min(0.5 + abs(score) * 0.1, 0.99)
else:
label = "Neutral"
confidence = 0.5
return label, confidence, positive_count, negative_count
# Test on product reviews
reviews = [
"This product is absolutely amazing and works perfectly!",
"Terrible quality, broke after one day. Total waste of money.",
"Arrived on time. Does what it says.",
"Love it! Fast shipping and excellent packaging.",
"Horrible experience. Customer service was awful and unhelpful.",
]
print("Sentiment Analysis Results:")
print()
for review in reviews:
label, confidence, pos, neg = analyze_sentiment(review)
print(f" '{review[:50]}...' " if len(review) > 50 else f" '{review}'")
print(f" Sentiment: {label} ({confidence*100:.0f}%) | Positive words: {pos}, Negative: {neg}")
print()Try It Yourself
Line 10: Malformed tag: "< 0: return f"Negative (pos={pos}, neg={neg})" return f"Neutral (pos={pos}, neg={neg})" # Analyze your own sentences: your_reviews = [ "The AI course was fantastic and very helpful!", "I had a horrible time understanding this concept.", "The explanation was clear and easy to follow.", ] for review in your_reviews: print(f"'{review}'") print(f" ->"
Tip: Tags must use valid HTML names and be properly formed. Example: <div>, <p class="text">