Python ML Sentiment Analysis
Sentiment analysis reads the feeling in a piece of text. A sentence can be positive, negative, or neutral.
VADER in three lines
The analyzer scores one happy sentence. The compound score is close to 1, which means strongly positive.
import nltk
nltk.download("vader_lexicon", quiet=True)
from nltk.sentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
print(analyzer.polarity_scores("I love this film, it is wonderful!"))Two feelings, two signs
A happy sentence scores above zero, and a dull sentence scores below zero. The sign is the verdict.
for text in ["I love this film, it is wonderful!", "A dull and boring waste of time."]:
print(round(analyzer.polarity_scores(text)["compound"], 4))A classifier learns a vocabulary
The vectorizer reads 1,190 news posts and learns 16,882 words. That vocabulary feeds the classifier.
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
news = fetch_20newsgroups(subset="train", categories=["sci.space", "rec.sport.baseball"], remove=("headers", "footers", "quotes"))
vectors = TfidfVectorizer(stop_words="english")
matrix = vectors.fit_transform(news.data)
print("Documents:", matrix.shape[0])
print("Vocabulary:", matrix.shape[1])Example
import nltk
nltk.download("vader_lexicon", quiet=True)
from nltk.sentiment import SentimentIntensityAnalyzer
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
analyzer = SentimentIntensityAnalyzer()
reviews = [
("I love this film, it is wonderful!", "pos"),
("A dull and boring waste of time.", "neg"),
("The acting was superb and the story moved me.", "pos"),
("I hated every minute of it.", "neg"),
]
correct = 0
for text, label in reviews:
score = analyzer.polarity_scores(text)["compound"]
guess = "pos" if score >= 0 else "neg"
print(round(score, 4), guess, label)
correct += guess == label
print("VADER correct:", correct, "of", len(reviews))
news = fetch_20newsgroups(subset="train",
categories=["sci.space", "rec.sport.baseball"],
remove=("headers", "footers", "quotes"))
X_train, X_test, y_train, y_test = train_test_split(
news.data, news.target, test_size=0.2, random_state=42)
vectors = TfidfVectorizer(stop_words="english")
X_train_vec = vectors.fit_transform(X_train)
X_test_vec = vectors.transform(X_test)
model = LogisticRegression(max_iter=1000, random_state=42)
model.fit(X_train_vec, y_train)
print("TF-IDF + Logistic Regression accuracy:",
round(accuracy_score(y_test, model.predict(X_test_vec)), 4))Key points
- Sentiment: the feeling in a piece of text, usually positive or negative
- VADER: a rule-based tool that scores feeling from a word list, with no training
- Compound score: one number from -1 to 1 that sums the feeling of a sentence
- Use SentimentIntensityAnalyzer to score a sentence in three lines
- Use a TF-IDF vectorizer plus LogisticRegression to train a text classifier
- A trained classifier needs labelled examples, while VADER needs none
In this example, VADER scores four short reviews first. The compound score is positive for the two happy reviews and negative for the two unhappy ones, so VADER gets 4 of 4 with no training at all. The second half trains a classifier on 20 Newsgroups posts about space and baseball. TfidfVectorizer turns the posts into numbers, and LogisticRegression learns to sort them. Its accuracy is 0.9244. VADER wins when the job is feeling and no labelled data exists. The trained classifier wins when the job is sorting topics and labelled posts exist. In short, sentiment analysis is teaching a computer to read the feeling in words, either from a ready-made word list or from labelled examples.
Note
VADER reads feelings, not topics. It cannot tell space news from baseball news.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does VADER need before it can score a sentence?