Sub topic 1
What sentiment analysis is and how to frame it
Sentiment analysis is the task of assigning an opinion label to a piece of text, such as "positive", "negative", or "neutral". This chapter covers how to frame the task before you write any model code. Framing decides which labels you need, what data you must collect, and which metrics make sense later.
Prerequisites
This chapter assumes you have the following background:
- Basic Python programming, including functions, lists, and dictionaries.
- Experience installing packages with pip.
- The basic idea of supervised learning: training data, test data, and predictions.
You do not need to know any NLP library yet. Later chapters build the code step by step: normalizing text, lexicon scoring, TF-IDF features, a logistic regression baseline, evaluation, and pretrained transformers.
What the task is
Sentiment analysis maps text to an opinion signal. Most often that signal is polarity, meaning how positive or negative the writer feels. The text in this tutorial comes from two sources:
- Reviews: longer, fairly well-formed text with an explicit target (a product, a hotel, a film) and often a star rating attached.
- Social posts: short, noisy text with links, mentions, hashtags, emojis, slang, and sarcasm. The target is often implicit.
The same model usually behaves differently on these two sources. Chapter by chapter, you will see why.
Sentiment analysis is also not the same as emotion detection or stance detection. The table separates them.
| Task | Question it answers | Example labels |
|---|---|---|
| Sentiment (polarity) | Is the text favorable or unfavorable? | positive, neutral, negative |
| Emotion detection | Which emotion is expressed? | anger, joy, fear, sadness |
| Stance detection | Does the author support or oppose a specific claim or target? | favor, against, none |
| Subjectivity detection | Is the text opinionated or factual? | subjective, objective |
A post such as "Third outage this week. Unbelievable." is negative in polarity and probably angry in emotion. A post such as "I support the new tax, even though I hate paying it" has mixed polarity but a clear stance. Choosing the wrong task produces labels that do not answer your real question.
Choosing a label scheme
The label scheme is the set of classes your system predicts. Three common choices are listed here.
- Binary (positive, negative). Simple, and annotators agree more often. The cost is that neutral text must be forced into one class, which adds noise.
- Three-class (positive, neutral, negative). This matches how people actually write, since many posts are factual or have no opinion. The neutral class is usually the hardest to predict and often the largest.
- Ordinal or fine-grained (for example 1 to 5 stars). Labels have an order, so predicting 4 when the truth is 5 is a smaller error than predicting 1. Plain classification ignores this order, so consider regression or ordinal metrics.
A practical rule: pick the smallest scheme that supports the decision your users will make. If a support team only needs to find angry customers, a binary "negative vs. not negative" label may be enough.
Write the scheme down with a definition and an example for each class. Edge cases need explicit rules, such as:
- A factual complaint ("The package arrived on Tuesday, two weeks late") is negative, even without emotional words.
- A question ("Does anyone know if this works?") is neutral.
- A mixed review ("Great screen, terrible battery") needs a rule: label it mixed, label it by the overall tone, or split it by aspect.
Choosing the level of granularity
Sentiment can be measured at different levels of the text. Each level answers a different question.
| Level | Unit | Typical use | Main weakness |
|---|---|---|---|
| Document | A whole review or post | Overall rating, brand tracking | Hides mixed opinions |
| Sentence | One sentence | Summaries, finding the opinionated parts | Needs sentence splitting, loses context |
| Aspect | A target inside a sentence | "Battery good, screen bad" | Needs more annotation effort |
Short posts are often a single sentence, so document and sentence levels coincide. Long reviews often contain several opinions, and one label for the whole review can be misleading. Aspect-based sentiment, covered near the end of the tutorial, handles this by attaching a label to each target. For now, remember that granularity is a decision you make early because it changes the data format.
The following diagram shows how the framing decisions fit together and feed the rest of the pipeline.
Writing the task as a specification
Before touching data, write a short specification. It forces decisions that otherwise surface later as bugs. A useful specification includes:
- The question the output will answer and who will act on it.
- The text source (reviews, posts, or both) and the language or languages.
- The label scheme and the definitions of each label.
- The granularity: document, sentence, or aspect.
- The success measure and the minimum acceptable score.
- What the system must not be used for.
You can keep this as a small structure in your code, so that the scheme is explicit and reused by every later step.
from dataclasses import dataclass, field
@dataclass
class SentimentTask:
source: str
language: str
granularity: str
labels: list
definitions: dict = field(default_factory=dict)
def validate(self, label):
if label not in self.labels:
raise ValueError(f"Unknown label {label!r}; expected one of {self.labels}")
return label
task = SentimentTask(
source="product reviews and social posts",
language="en",
granularity="document",
labels=["negative", "neutral", "positive"],
definitions={
"negative": "The author expresses dissatisfaction, including factual complaints.",
"neutral": "No opinion, a question, or an announcement.",
"positive": "The author expresses satisfaction or approval.",
},
)
print(task.validate("positive"))
for name, text in task.definitions.items():
print(f"{name}: {text}")Running this prints positive followed by one line per definition. Calling task.validate("mixed") raises a ValueError, which is the behavior you want when a new label sneaks into the data.
Common framing errors
Most failed sentiment projects fail before modeling. These are the errors to watch for.
- Confusing the label source with the label meaning. A 3-star review is not automatically neutral. Many people give 3 stars to a mixed or disappointed experience. Chapter 2 covers this in detail.
- Ignoring the neutral class. If real data contains many neutral posts but the model only knows positive and negative, every neutral post becomes a false positive or false negative.
- Mixing sources without noting it. A model built from reviews and applied to social posts faces a domain shift. State the intended source in the specification.
- Treating opinion about the topic as opinion about the product. "I hate that the airline lost my bag, but the crew was lovely" has two targets. A document-level label will lose one of them.
- Using sentiment as a proxy for something else. Negative sentiment about a news event does not mean negative sentiment toward a person or company mentioned in it.
- Skipping a baseline. Without a simple reference score, you cannot tell whether a complex model helps.
How the approaches compare
The rest of the tutorial builds three families of method. Knowing their trade-offs now helps you plan data collection.
| Approach | Needs labeled data? | Strength | Typical weakness |
|---|---|---|---|
| Lexicon (such as VADER) | No, except for evaluation | Instant baseline, transparent | Misses context, domain-specific words, and sarcasm |
| TF-IDF plus logistic regression | Yes, thousands of examples | Fast, easy to inspect | Bag-of-words ignores word order beyond n-grams |
| Pretrained transformer | None to use, some to fine-tune | Handles context and varied phrasing | Heavier to run, can fail silently on a new domain |
Even if you plan to use a pretrained model, you still need a labeled sample to measure it. No framing is complete without a plan for evaluation data.
A framing walkthrough
Suppose a phone retailer wants to know what people say about a new model. They have store reviews with star ratings and a feed of social posts that mention the product.
- Question. The product team wants to find recurring complaints each week. The output is a list of negative items to read, so the main need is finding negatives reliably.
- Task. Polarity, not emotion. Stance is irrelevant because everyone is talking about the same product.
- Scheme. Three-class. Many posts are questions or announcements, and forcing them into positive or negative would flood the complaint list with noise.
- Granularity. Document for the first version. Reviews with mixed content are flagged for a later aspect-based pass.
- Data. Reviews come with star ratings, which can serve as weak labels. Social posts have none, so a sample must be annotated by hand.
- Success measure. Recall on the negative class matters most, with enough precision that readers do not waste time. Chapter 7 explains these metrics.
Notice that none of these steps involve a model. They determine which model and which metrics are appropriate.
Summary of decisions
- Name the task precisely and separate sentiment from emotion and stance.
- Choose the smallest label scheme that supports the decision, and write definitions with edge cases.
- Choose a granularity that matches how opinions appear in your text.
- Record the source, language, and intended use in a specification.
- Plan labeled evaluation data from the start.
Exercise
A team wants to detect customer posts that complain about delivery delays so a support agent can reply. Posts include questions such as "Where is my order?" and plain announcements such as "Order shipped." Propose a task, a label scheme, and a granularity, and explain one edge case that your definitions must settle.
Show answer
Task: polarity, with a negative class aimed at complaints. Label scheme: three-class (negative, neutral, positive), because questions and announcements are common and should not be forced into positive or negative. Granularity: document level, since posts are short. Edge case: "Where is my order?" has no explicit negative word but may signal a problem. The definitions must say whether a question about a late order counts as negative (complaint) or neutral (no opinion). Whichever rule is chosen should be written down with examples so annotators label it consistently.
Exercise
Using the SentimentTask class from this chapter, what happens when you call task.validate("mixed") on a task whose labels are negative, neutral, and positive? Why is this useful?
Show answer
It raises a ValueError with the message "Unknown label 'mixed'; expected one of ['negative', 'neutral', 'positive']". This is useful because an unexpected label in the data is caught immediately instead of silently creating an extra class that skews training and evaluation.