Sentiment analysis is the use of natural language processing to work out how a writer feels about something. You can run it on one sentence or on millions of reviews, tickets and posts. The output is structured: a label such as positive, negative or neutral, a score, or a full breakdown of emotions. You can chart it, filter by it, alert on it or feed it to other systems.
This guide covers what sentiment analysis measures and how the main methods work, from word lists to transformers. It also covers where each method fails and how to choose one for a real project. If you already know the theory and want code, jump to sentiment analysis in Python.
Sentiment analysis, defined
Sentiment analysis, also called opinion mining, is a text classification task. A model reads a piece of text and predicts the attitude it expresses. Three things set it apart from general text classification:
- The target is subjective. Topic classification asks what a text is about. Sentiment asks how the author feels about it. Two reviews of the same phone can share a topic and have opposite sentiment.
- It is often graded, not binary. "Fine" and "absolutely brilliant" are both positive, but not equally positive. Most useful systems return a continuous score as well as a label.
- Meaning depends on context. "Unpredictable" is praise for a film plot and a complaint about a car's brakes. Negation, sarcasm and comparisons can reverse the meaning of otherwise positive words.
Polarity, emotion and aspect: three levels of detail
People say "sentiment analysis" for at least three different outputs. Knowing which one you need is the most important decision you will make.
| Level | Question it answers | Typical output |
|---|---|---|
| Polarity | Is this positive or negative, and how strongly? | positive / neutral / negative, or a score from -1 to 1 |
| Emotion | Which feelings are present? | scores for joy, anger, fear, gratitude, disappointment, … |
| Aspect | How does the writer feel about each thing mentioned? | battery: negative · screen: positive · price: neutral |
Polarity is the classic version and is enough for a headline metric such as "share of negative mentions this week". Emotion detection adds the why. A customer who is confused needs better documentation. One who is angry needs an escalation. One who is disappointed had expectations you failed to meet. All three look the same on a polarity chart. We cover this in depth in emotion detection vs sentiment analysis, and the list of 28 GoEmotions labels shows a widely used emotion taxonomy. Aspect-based sentiment splits the opinion by the features or entities a review mentions.
You can get to polarity from emotions, but not the other way round. If a model scores 28 emotions, a weighted sum of those scores gives a single valence number. This is how the Sentiment API computes its valence score from -1 to 1.
How sentiment analysis works
Most systems fall into one of three families. Older families have not disappeared, because each one trades accuracy against cost and simplicity differently.
1. Lexicon and rule-based methods
A lexicon is a dictionary of words with sentiment values: "excellent" +3, "terrible" −3, and so on. The system adds up the values of the words in a text. Rules then adjust the total for negation ("not good"), intensifiers ("very good"), capital letters and exclamation marks. VADER and TextBlob are the best-known examples.
Lexicons are fast, free, transparent and need no training data. They are also shallow. They miss sarcasm and domain-specific meaning ("sick" as praise), and they don't understand words outside their dictionary. Nearly all of them are English-only.
2. Classic machine learning
The next generation converted text into features, such as word counts or TF-IDF vectors. A classifier such as logistic regression, naive Bayes or a linear SVM was then trained on labelled examples. These models learn domain vocabulary from data and are cheap to run. But they treat text as a bag of words, so word order and long-range context are mostly lost. "Not bad at all" and "bad, not at all good" contain nearly the same words.
3. Transformer models
Modern sentiment analysis is dominated by pretrained transformers such as BERT, RoBERTa, XLM-R and their descendants. They are fine-tuned on labelled sentiment or emotion data. A transformer reads the whole sequence at once and builds a representation of each word in its context. That lets it handle negation, contrast ("the food was great but the service ruined it") and many idioms far better than earlier methods. Multilingual variants such as mBERT and XLM-R learn many languages in one model. A model fine-tuned on one language can often transfer reasonably well to others.
The cost is computation. Transformers run best on GPUs, and models typically cap input length at 512 tokens, so long documents must be split. Hosted APIs exist to take this work off your hands.
What about large language models?
You can ask a general-purpose LLM to "rate the sentiment of this review". It will often give a sensible answer and even explain it. For one-off analysis that is perfectly reasonable. At scale, purpose-built classifiers usually win on several counts:
- Cost: a small fine-tuned model is orders of magnitude cheaper per message.
- Latency: a classifier returns one forward pass, not a generated paragraph.
- Consistency: a classifier returns the same scores for the same input every time. LLM output can vary from run to run and depends on how the prompt is worded.
- Calibrated scores: a classifier gives you a probability for every label. An LLM gives you whatever number it decides to write.
A common hybrid: use a classifier on everything, then send only the interesting cases to an LLM for explanation or summarisation. Those are the most negative items, sudden spikes, or texts where the model is unsure.
How sentiment scores are calculated
Most tools return a polarity score: one number from -1 (very negative) through 0 (neutral) to +1 (very positive). The name changes from tool to tool (compound score, polarity, valence), but the calculation follows one of four patterns.
| Method | Score and range | How it is calculated |
|---|---|---|
| VADER | compound, -1 to 1 | Add up word valences (each -4 to +4), adjust for negation, intensifiers, caps and "!", then normalise: x / √(x² + 15) |
| TextBlob | polarity -1 to 1, subjectivity 0 to 1 | Average the lexicon values of the words found, with modifiers such as "very" and "not" |
| Transformer classifier | one probability per label, sum = 1 | Softmax over the labels (negative, neutral, positive). A single score is often P(positive) − P(negative) |
| Multi-label emotion model | one score per emotion, each 0 to 1 | Sigmoid per emotion, so several can be high at once. A weighted sum gives one valence score |
Worked example (lexicon). In VADER the word "great" has a valence of 3.1. For "The food was great" the raw sum is 3.1, so the compound score is 3.1 / √(3.1² + 15) ≈ 0.62. VADER calls a compound score of 0.05 or more positive and -0.05 or less negative. The VADER guide explains the compound score in more detail.
Worked example (emotions to valence). An emotion model reads "It works, but I expected more for the price" and returns disappointment 0.70 and approval 0.20, with the other emotions near zero. Each emotion has a polarity weight (disappointment -0.6, approval +0.6). The valence is the weighted sum: 0.70 × -0.6 + 0.20 × 0.6 = -0.30, so mildly negative. Because the emotion scores do not sum to 1, the sum is clamped to the range -1 to 1. This is how the Sentiment API returns its valence next to the 28 emotion scores.
Document, sentence and aspect granularity
Separately from what you measure, you must decide what unit to measure:
- Document level: one score per review, ticket or post. Simple, but a 400-word review that praises the product and condemns the delivery averages out to "neutral", which is wrong.
- Sentence level: split the text into sentences and score each one. This keeps mixed opinions visible. It also keeps inputs within the model's token limit.
- Aspect level: link each opinion to the thing it is about. This is the most actionable and the most expensive. A practical shortcut is to score sentences and tag them with keyword or topic rules, such as "battery", "shipping" or "price".
What teams use it for
- Product and app reviews: track satisfaction by release, find the features that cause complaints, and catch regressions before star ratings drop. See sentiment analysis of customer reviews.
- Customer support: send angry or distressed tickets to senior agents, flag churn risk, and measure whether replies improve the customer's mood over a conversation.
- Brand and social monitoring: detect spikes in negative emotion after a launch, an outage or a news story. See social media sentiment analysis.
- Surveys and NPS verbatims: turn thousands of free-text answers into themes and emotion distributions instead of reading a random hundred.
- Market and financial research: build sentiment features from news, forums and earnings-call transcripts. Usually this needs domain-specific models.
- Content moderation and wellbeing: surface posts with fear, grief or remorse for human review. Treat the model as a triage tool, never as the final decision-maker.
- Conversational AI: let chatbots and agents adapt their tone, or hand over to a human when frustration builds.
Why it's harder than it looks
Sarcasm and irony
"Great, another update that deletes my settings." Every sentiment word here is positive and the meaning is negative. Transformers trained on informal text catch a fair share of sarcasm. No model catches all of it, and people disagree about it too.
Negation and contrast
"Not bad", "hardly impressive" and "I wanted to love it" all flip or soften the surface meaning. Contrast words such as "but" and "although" usually mean the second clause matters more. Lexicon methods handle the simple cases with rules. Contextual models handle more of them.
Domain shift
A model trained on movie reviews has learned that "long" is slightly negative ("a long, dull film"). In laptop reviews, "long battery life" is clearly positive. Accuracy can drop sharply when your data looks different from the training data. That is the main reason to validate on your own labelled sample.
Multiple languages and code-switching
Real-world feeds mix languages, sometimes within one sentence, and include scripts and transliterations such as Arabic written in Latin letters. Translating everything into English loses nuance and adds cost. A natively multilingual model avoids the translation step. See multilingual sentiment analysis for the trade-offs.
Annotator disagreement
People don't agree perfectly on sentiment either, especially for fine-grained emotions. When labelled datasets are built, raters regularly assign different emotions to the same comment. A model can't be more consistent than its labels, so treat small score differences as noise.
Measuring accuracy properly
Vendor accuracy figures are measured on benchmark datasets that probably don't look like your data. To get a number you can trust:
- Sample a few hundred texts from your real data, stratified across sources, languages and time.
- Have two people label them independently. Measure how often they agree. That agreement rate is your realistic ceiling.
- Compare the model against the agreed labels. For imbalanced classes use per-class precision and recall and macro-F1, not plain accuracy. If 85% of your data is neutral, a model that always answers "neutral" scores 85% accuracy.
- For multi-label emotion output, choose a threshold per label on your sample. A 0.5 cut-off rarely suits rare emotions.
- Re-check every few months. Language, products and models all drift.
Public datasets are useful for comparing models before you label anything yourself. See sentiment analysis datasets for a curated list.
Choosing an approach
| If you need… | Consider |
|---|---|
| A quick English polarity score in a notebook, offline, free | A lexicon tool such as VADER or TextBlob |
| High accuracy in one domain, and you have labelled data and GPUs | Fine-tune your own transformer |
| Fine-grained emotions across several languages, without running infrastructure | A hosted emotion-detection API |
| Explanations or summaries of a small set of texts | A general-purpose LLM, ideally after a classifier has filtered the data |
| Enterprise procurement, existing cloud contract | Your cloud provider's NLP service (polarity, some aspect support) |
For a side-by-side look at specific libraries, cloud services and models, read sentiment analysis tools compared.
Getting started in ten minutes
The fastest way to see transformer-quality emotion detection on your own text is to send it to an API. With the Sentiment API, you POST the text, receive a job_id, and fetch the result. Each result contains all 28 emotion scores, the top emotion and a valence score:
// GET /api/jobs/:id → result (scores are illustrative)
{
"text": "The update fixed my sync issue, thank you so much!",
"predictions": [
{ "label": "gratitude", "score": 0.95 },
{ "label": "joy", "score": 0.31 },
{ "label": "relief", "score": 0.18 },
... 25 more labels, sorted by score
],
"top_emotion": "gratitude",
"top_score": 0.95,
"valence": 0.88
}Scores are independent sigmoid probabilities, so several emotions can be high at once, just as in real text. They don't add up to 1. There is no subscription. You send an API key and pay a fraction of a cent per message from prepaid credit. The API docs include copy-paste examples for curl, Python and JavaScript, and batch requests score up to 10,000 texts in a single call. Current per-message prices are on the pricing page.
Frequently asked questions
What is a polarity score in sentiment analysis?
A polarity score is a single number that says how positive or negative a text is. Most tools use a range from -1 (very negative) through 0 (neutral) to +1 (very positive). VADER calls it the compound score, TextBlob calls it polarity, and emotion APIs often call it valence.
How are sentiment scores calculated?
It depends on the method. Lexicon tools such as VADER add up the scores of known words, adjust for negation and intensifiers, and normalise the sum to the range -1 to 1. Transformer classifiers output a probability for each label (for example negative, neutral, positive), and a single score is often P(positive) minus P(negative). Emotion models score each emotion from 0 to 1 and combine them with weights into one valence number.
What is a sentiment analyzer?
A sentiment analyzer is a tool, library or API that takes text and returns its sentiment: a label such as positive, negative or neutral, a polarity score, and sometimes scores for individual emotions. Examples are the VADER and TextBlob Python libraries, cloud services such as AWS Comprehend, and emotion APIs such as the Sentiment API.
What is sentiment analysis in simple terms?
Sentiment analysis is the automatic detection of the attitude or feeling expressed in a piece of text. At its simplest it labels text as positive, negative or neutral; more detailed systems score specific emotions such as joy, anger, gratitude or disappointment.
Is sentiment analysis part of NLP or machine learning?
Both. Sentiment analysis is a classic natural language processing (NLP) task. Older systems used hand-built word lists (lexicons); most modern systems are machine-learning models, usually fine-tuned transformers such as BERT or RoBERTa, trained on labelled examples.
How accurate is sentiment analysis?
It depends heavily on the domain, the language and the label set. Binary positive/negative classification of clean English reviews can exceed 90% accuracy with modern transformers, while fine-grained emotion detection on short, informal or sarcastic text is much harder. Always measure on a labelled sample of your own data.
What is the difference between sentiment analysis and emotion detection?
Sentiment analysis usually measures polarity: is the text positive or negative, and how strongly. Emotion detection identifies which specific feelings are present — for example disappointment versus anger — which is more useful when you need to decide what action to take.
Can sentiment analysis handle languages other than English?
Yes, with the right model. Multilingual transformers such as mBERT and XLM-R can classify sentiment in many languages directly. Lexicon tools such as VADER and TextBlob are English-only, so non-English text requires either translation or a multilingual model.