Sub topic 1
What sentiment analysis is and how to frame it
Prerequisites
This chapter assumes you know basic Python, can work with lists and dictionaries, and can install packages with pip. You should also understand training data and test data in supervised learning.
Defining the task
Sentiment analysis assigns a label to text that expresses an opinion. The label scheme is a choice you make first. Common schemes are positive, negative, and neutral, or a five-point scale that matches star ratings. Decide the granularity too: a whole review, a single post, or a specific aspect such as "battery" within a phone review. Every later step depends on these decisions.
Where labels come from
Star ratings
A 5-star review is often mapped to positive and a 1-star review to negative. This is cheap, but a 3-star review can still contain praise or complaints, so the mapping is noisy.
Human annotation
Annotators read each text and assign a label. This is slower and more reliable. Measure agreement between annotators before trusting the labels.
Weak labels
Rules, emoticons, or keyword heuristics assign labels automatically. Treat these as a starting point, not ground truth.
Cleaning noisy text
Social posts contain URLs, @mentions, #hashtags, and emojis. Handle each one on purpose. Replace URLs and mentions with placeholders, keep the words in hashtags, and keep emojis and punctuation, because they often carry sentiment.
import re
def normalize_post(text):
text = re.sub(r"https?://\S+", "<url>", text)
text = re.sub(r"@\w+", "@user", text)
text = re.sub(r"#(\w+)", r"\1", text)
return re.sub(r"\s+", " ", text).strip()
print(normalize_post("Loving the new phone!! @shopfan #bestbuy https://example.com/x"))A quick baseline with VADER
VADER is a lexicon-based scorer. It holds a list of words with sentiment values and applies rules for capitalization, punctuation, and intensifiers. Its compound score runs from -1 (most negative) to +1 (most positive). A common mapping uses 0.05 as the cutoff.
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
scores = analyzer.polarity_scores("The battery life is great, but the screen is awful.")
print(scores) # keys: 'neg', 'neu', 'pos', 'compound'
compound = scores["compound"]
if compound >= 0.05:
label = "positive"
elif compound <= -0.05:
label = "negative"
else:
label = "neutral"
print(label)Exercise
The text "The battery is great, but the screen is awful" gets a mixed score near zero. Why might a lexicon model still be useful as a baseline?
Show answer
It is fast, needs no labeled data, and gives a reference point. A trained model must beat it to justify its extra cost.