Sentiment Analysis

Sentiment Analysis

Guides an AI agent to classify text sentiment with lexicon methods and machine learning for opinion mining and customer feedback analysis.

Skill files3 files

scripts/

templates/

SKILL.md314 lines
1
---
2
name: Sentiment Analysis
3
description: Classify text sentiment using NLP techniques, lexicon-based analysis, and machine learning for opinion mining, brand monitoring, and customer feedback analysis
4
---
5
6
# Sentiment Analysis
7
8
## Overview
9
10
Sentiment analysis determines emotional tone and opinions in text, enabling understanding of customer satisfaction, brand perception, and feedback analysis.
11
12
## Approaches
13
14
- **Lexicon-based**: Using sentiment dictionaries
15
- **Machine Learning**: Training classifiers on labeled data
16
- **Deep Learning**: Neural networks for complex patterns
17
- **Aspect-based**: Sentiment about specific features
18
- **Multilingual**: Non-English text analysis
19
20
## Sentiment Types
21
22
- **Positive**: Favorable, satisfied
23
- **Negative**: Unfavorable, dissatisfied
24
- **Neutral**: Factual, no clear sentiment
25
- **Mixed**: Combination of sentiments
26
27
## Implementation with Python
28
29
```python
30
import pandas as pd
31
import numpy as np
32
import matplotlib.pyplot as plt
33
import seaborn as sns
34
from sklearn.feature_extraction.text import TfidfVectorizer
35
from sklearn.naive_bayes import MultinomialNB
36
from sklearn.pipeline import Pipeline
37
from sklearn.model_selection import train_test_split
38
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
39
import re
40
from collections import Counter
41
42
# Sample review data
43
reviews_data = [
44
"This product is amazing! I love it so much.",
45
"Terrible quality, very disappointed.",
46
"It's okay, nothing special.",
47
"Best purchase ever! Highly recommend.",
48
"Worst product I've ever bought.",
49
"Pretty good, satisfied with the purchase.",
50
"Excellent service and fast delivery.",
51
"Poor quality and bad customer support.",
52
"Not bad, does what it's supposed to.",
53
"Absolutely fantastic! Five stars!",
54
"Mediocre product, expected better.",
55
"Love everything about this!",
56
"Complete waste of money.",
57
"Good value for the price.",
58
"Very satisfied, will buy again!",
59
"Horrible experience from start to finish.",
60
"It works as described.",
61
"Outstanding quality and design!",
62
"Disappointed with the results.",
63
"Perfect! Exactly what I wanted.",
64
]
65
66
sentiments = [
67
'Positive', 'Negative', 'Neutral', 'Positive', 'Negative',
68
'Positive', 'Positive', 'Negative', 'Neutral', 'Positive',
69
'Negative', 'Positive', 'Negative', 'Positive', 'Positive',
70
'Negative', 'Neutral', 'Positive', 'Negative', 'Positive'
71
]
72
73
df = pd.DataFrame({'review': reviews_data, 'sentiment': sentiments})
74
75
print("Sample Reviews:")
76
print(df.head(10))
77
78
# 1. Lexicon-based Sentiment Analysis
79
from nltk.sentiment import SentimentIntensityAnalyzer
80
try:
81
import nltk
82
nltk.download('vader_lexicon', quiet=True)
83
sia = SentimentIntensityAnalyzer()
84
85
df['vader_scores'] = df['review'].apply(lambda x: sia.polarity_scores(x))
86
df['vader_compound'] = df['vader_scores'].apply(lambda x: x['compound'])
87
df['vader_sentiment'] = df['vader_compound'].apply(
88
lambda x: 'Positive' if x > 0.05 else ('Negative' if x < -0.05 else 'Neutral')
89
)
90
91
print("\n1. VADER Sentiment Scores:")
92
print(df[['review', 'vader_compound', 'vader_sentiment']].head())
93
except:
94
print("NLTK not available, skipping VADER analysis")
95
96
# 2. Textblob Sentiment (alternative)
97
try:
98
from textblob import TextBlob
99
100
df['textblob_polarity'] = df['review'].apply(lambda x: TextBlob(x).sentiment.polarity)
101
df['textblob_sentiment'] = df['textblob_polarity'].apply(
102
lambda x: 'Positive' if x > 0.1 else ('Negative' if x < -0.1 else 'Neutral')
103
)
104
105
print("\n2. TextBlob Sentiment Scores:")
106
print(df[['review', 'textblob_polarity', 'textblob_sentiment']].head())
107
except:
108
print("TextBlob not available")
109
110
# 3. Feature Extraction for ML
111
vectorizer = TfidfVectorizer(max_features=100, stop_words='english')
112
X = vectorizer.fit_transform(df['review'])
113
y = df['sentiment']
114
115
print(f"\n3. Feature Matrix Shape: {X.shape}")
116
print(f"Features extracted: {len(vectorizer.get_feature_names_out())}")
117
118
# 4. Machine Learning Model
119
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
120
121
# Naive Bayes classifier
122
nb_model = MultinomialNB()
123
nb_model.fit(X_train, y_train)
124
y_pred = nb_model.predict(X_test)
125
126
print("\n4. Machine Learning Results:")
127
print(f"Accuracy: {accuracy_score(y_test, y_pred):.2f}")
128
print("\nClassification Report:")
129
print(classification_report(y_test, y_pred))
130
131
# 5. Sentiment Distribution
132
fig, axes = plt.subplots(2, 2, figsize=(14, 8))
133
134
# Distribution of sentiments
135
sentiment_counts = df['sentiment'].value_counts()
136
axes[0, 0].bar(sentiment_counts.index, sentiment_counts.values, color=['green', 'red', 'gray'], alpha=0.7, edgecolor='black')
137
axes[0, 0].set_title('Sentiment Distribution')
138
axes[0, 0].set_ylabel('Count')
139
axes[0, 0].grid(True, alpha=0.3, axis='y')
140
141
# Pie chart
142
axes[0, 1].pie(sentiment_counts.values, labels=sentiment_counts.index, autopct='%1.1f%%',
143
colors=['green', 'red', 'gray'], startangle=90)
144
axes[0, 1].set_title('Sentiment Proportion')
145
146
# VADER compound scores distribution
147
if 'vader_compound' in df.columns:
148
axes[1, 0].hist(df['vader_compound'], bins=20, color='steelblue', edgecolor='black', alpha=0.7)
149
axes[1, 0].axvline(x=0.05, color='green', linestyle='--', label='Positive threshold')
150
axes[1, 0].axvline(x=-0.05, color='red', linestyle='--', label='Negative threshold')
151
axes[1, 0].set_xlabel('VADER Compound Score')
152
axes[1, 0].set_ylabel('Frequency')
153
axes[1, 0].set_title('VADER Score Distribution')
154
axes[1, 0].legend()
155
156
# Confusion matrix
157
cm = confusion_matrix(y_test, y_pred)
158
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', ax=axes[1, 1],
159
xticklabels=np.unique(y_test), yticklabels=np.unique(y_test))
160
axes[1, 1].set_title('Classification Confusion Matrix')
161
axes[1, 1].set_ylabel('True Label')
162
axes[1, 1].set_xlabel('Predicted Label')
163
164
plt.tight_layout()
165
plt.show()
166
167
# 6. Most Informative Features
168
feature_names = vectorizer.get_feature_names_out()
169
170
# Get feature importance from Naive Bayes
171
for sentiment_class, idx in enumerate(np.unique(y)):
172
class_idx = list(np.unique(y)).index(idx)
173
top_features_idx = np.argsort(nb_model.feature_log_prob_[class_idx])[-5:]
174
175
print(f"\nTop features for '{idx}':")
176
for feature_idx in reversed(top_features_idx):
177
print(f" {feature_names[feature_idx]}")
178
179
# 7. Word frequency analysis
180
positive_words = ' '.join(df[df['sentiment'] == 'Positive']['review'].values).lower()
181
negative_words = ' '.join(df[df['sentiment'] == 'Negative']['review'].values).lower()
182
183
# Clean and tokenize
184
def get_words(text):
185
text = re.sub(r'[^a-z\s]', '', text)
186
words = text.split()
187
return [w for w in words if len(w) > 2]
188
189
pos_word_freq = Counter(get_words(positive_words))
190
neg_word_freq = Counter(get_words(negative_words))
191
192
# Visualization
193
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
194
195
# Positive words
196
top_pos_words = dict(pos_word_freq.most_common(10))
197
axes[0].barh(list(top_pos_words.keys()), list(top_pos_words.values()), color='green', alpha=0.7, edgecolor='black')
198
axes[0].set_xlabel('Frequency')
199
axes[0].set_title('Top Words in Positive Reviews')
200
axes[0].invert_yaxis()
201
202
# Negative words
203
top_neg_words = dict(neg_word_freq.most_common(10))
204
axes[1].barh(list(top_neg_words.keys()), list(top_neg_words.values()), color='red', alpha=0.7, edgecolor='black')
205
axes[1].set_xlabel('Frequency')
206
axes[1].set_title('Top Words in Negative Reviews')
207
axes[1].invert_yaxis()
208
209
plt.tight_layout()
210
plt.show()
211
212
# 8. Trend analysis (simulated over time)
213
dates = pd.date_range('2023-01-01', periods=len(df))
214
df['date'] = dates
215
df['rolling_sentiment_score'] = df['vader_compound'].rolling(window=3, center=True).mean()
216
217
fig, ax = plt.subplots(figsize=(12, 5))
218
ax.plot(df['date'], df['rolling_sentiment_score'], marker='o', linewidth=2, label='Rolling Avg (3-day)')
219
ax.scatter(df['date'], df['vader_compound'], alpha=0.5, s=30, label='Daily Score')
220
ax.axhline(y=0, color='black', linestyle='--', alpha=0.3)
221
ax.fill_between(df['date'], df['rolling_sentiment_score'], 0,
222
where=(df['rolling_sentiment_score'] > 0), alpha=0.3, color='green', label='Positive')
223
ax.fill_between(df['date'], df['rolling_sentiment_score'], 0,
224
where=(df['rolling_sentiment_score'] <= 0), alpha=0.3, color='red', label='Negative')
225
ax.set_xlabel('Date')
226
ax.set_ylabel('Sentiment Score')
227
ax.set_title('Sentiment Trend Over Time')
228
ax.legend()
229
ax.grid(True, alpha=0.3)
230
plt.tight_layout()
231
plt.show()
232
233
# 9. Aspect-based sentiment (simulated)
234
aspects = ['Quality', 'Price', 'Delivery', 'Customer Service']
235
aspect_sentiments = []
236
237
for aspect in aspects:
238
keywords = {
239
'Quality': ['quality', 'product', 'design', 'material'],
240
'Price': ['price', 'cost', 'expensive', 'value'],
241
'Delivery': ['delivery', 'fast', 'shipping', 'arrived'],
242
'Customer Service': ['service', 'support', 'customer', 'help']
243
}
244
245
# Count mentions and associated sentiment
246
aspect_reviews = df[df['review'].str.contains('|'.join(keywords[aspect]), case=False)]
247
if len(aspect_reviews) > 0:
248
avg_sentiment = aspect_reviews['vader_compound'].mean()
249
aspect_sentiments.append({
250
'Aspect': aspect,
251
'Avg Sentiment': avg_sentiment,
252
'Count': len(aspect_reviews)
253
})
254
255
aspect_df = pd.DataFrame(aspect_sentiments)
256
257
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
258
259
# Aspect sentiment scores
260
colors_aspect = ['green' if x > 0 else 'red' for x in aspect_df['Avg Sentiment']]
261
axes[0].barh(aspect_df['Aspect'], aspect_df['Avg Sentiment'], color=colors_aspect, alpha=0.7, edgecolor='black')
262
axes[0].set_xlabel('Average Sentiment Score')
263
axes[0].set_title('Sentiment by Aspect')
264
axes[0].axvline(x=0, color='black', linestyle='-', linewidth=0.8)
265
axes[0].grid(True, alpha=0.3, axis='x')
266
267
# Mention count
268
axes[1].bar(aspect_df['Aspect'], aspect_df['Count'], color='steelblue', alpha=0.7, edgecolor='black')
269
axes[1].set_ylabel('Number of Mentions')
270
axes[1].set_title('Aspect Mention Frequency')
271
axes[1].grid(True, alpha=0.3, axis='y')
272
273
plt.tight_layout()
274
plt.show()
275
276
# 10. Summary report
277
print("\n" + "="*50)
278
print("SENTIMENT ANALYSIS SUMMARY")
279
print("="*50)
280
print(f"Total Reviews: {len(df)}")
281
print(f"Positive: {len(df[df['sentiment'] == 'Positive'])} ({len(df[df['sentiment'] == 'Positive'])/len(df)*100:.1f}%)")
282
print(f"Negative: {len(df[df['sentiment'] == 'Negative'])} ({len(df[df['sentiment'] == 'Negative'])/len(df)*100:.1f}%)")
283
print(f"Neutral: {len(df[df['sentiment'] == 'Neutral'])} ({len(df[df['sentiment'] == 'Neutral'])/len(df)*100:.1f}%)")
284
if 'vader_compound' in df.columns:
285
print(f"\nAverage VADER Score: {df['vader_compound'].mean():.3f}")
286
print(f"Model Accuracy: {accuracy_score(y_test, y_pred):.2%}")
287
print("="*50)
288
```
289
290
## Methods Comparison
291
292
- **Lexicon-based**: Fast, interpretable, limited context
293
- **Machine Learning**: Requires training data, good accuracy
294
- **Deep Learning**: Complex patterns, needs large dataset
295
- **Hybrid**: Combines multiple approaches
296
297
## Applications
298
299
- Customer feedback analysis
300
- Product reviews monitoring
301
- Social media sentiment
302
- Brand perception tracking
303
- Chatbot sentiment detection
304
305
## Deliverables
306
307
- Sentiment distribution analysis
308
- Classified sentiments for all texts
309
- Confidence scores
310
- Feature importance for classification
311
- Trend analysis visualizations
312
- Aspect-based sentiment breakdown
313
- Executive summary with insights
314

© AJ Geddes · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…