Back to Tutorials
Machine Learning
Beginner

Sentiment Analysis: What the Model Sees, and Where It Breaks

Two real Hugging Face models read café reviews. Delete words to see what each answer rests on, then watch them fail, confidently, on sarcasm, slang and plain facts.

9 minInteractive: drag, click and try things as you read


Sentiment analysis labels a piece of text as positive or negative, sometimes neutral: thousands of reviews, support tickets or survey answers sorted in seconds. With Hugging Face, a ready-made model does it in three lines of Python. It works well on text like the text it learned from, and it fails with complete confidence on text that isn’t. A model’s confidence tells you how sure it is, not how right it is. Here two real models read a café’s reviews, and you’ll find out what they’re looking at and where they break.

Three lines of code#

Hugging Face’s pipeline wraps everything a model needs: splitting the text into tokens, running the model, and turning its output into a label and a score. Ask for pipeline("sentiment-analysis") without naming a model and you get its default: a small model called DistilBERT, fine-tuned (trained further) on SST-2, a dataset of sentences from movie reviews, each marked positive or negative. On SST-2 sentences it hasn’t seen, it’s right about 91% of the time.

We gave it 40 made-up café reviews, 20 happy and 20 not. It got 37 right, which is about what you’d hope for. The interesting part is how it gets there, and the three it got wrong.

What the model is looking at#

A model like this doesn’t explain itself, but you can ask it a simpler question: what happens if I delete this word? Score the sentence again without each word in turn, and the words whose removal changes the score most are the ones the answer depends on. This is called occlusion, and it’s the simplest of the tools for explaining a model’s decisions.

Try it
The sentences are made up; every score is real, from the two-label model (the pipeline’s default) run offline on the sentence and on each version with one word deleted. Green words pull towards positive, rose words towards negative; the stronger the colour, the bigger the effect.

In “The coffee was not bad at all”, two words light up: “not” and “bad”. Delete either and the answer flips to negative, because they only mean something positive as a pair. That’s reassuring: the model has learned that “not bad” is praise. Now pick “The flat white was silky and the barista remembered my name”: delete the word “and” and a 99.6% positive review becomes 99% negative. Nobody reads it that way. The model has learned patterns that usually work, and occlusion shows you where they’re strange.

Where it breaks#

The model can only answer what it was trained to answer. This one knows two labels, so every sentence gets one of them, even a sentence with no feeling in it at all.

Predict first

The two-label model reads “I ordered a flat white and a scone.” What does it say?

Try it
Twelve made-up sentences that are hard for different reasons, scored by two real models: the two-label model above, and a three-label RoBERTa model trained on about 124 million tweets. “Really” is our reading of each sentence. The cut-off is yours.

Both models handle negation (“not bad at all”, “I wouldn’t say the cake was good”), and both miss sarcasm: “Oh great, another forty-minute wait” reads as positive, because the words are positive and only the situation isn’t. The two-label model gets 7 of the 12 wrong and calls the plain facts and the question confidently negative or positive. The three-label model gets the neutral ones right, but it reads the slang “This espresso is sick” and “The brownies here are wicked” as complaints.

Now drag the cut-off. You might hope that treating low-confidence answers as “not sure” would catch the mistakes. For the two-label model it doesn’t: it’s at least 97% sure of all 12, so even at 95% it’s still wrong on 7 and unsure of none. Its 3 mistakes on the café reviews are just as confident. The three-label model spreads its bets more, so a cut-off around 70% turns most of its mistakes into “not sure”, at the price of being unsure about many reviews it had right.

Choosing a model#

  • Check the labels it can give. If your text includes questions, facts or mixed feelings, a model with only positive and negative will force them into one or the other.
  • Check what it learned from. Movie reviews, tweets and product reviews use language differently. The Hugging Face Hub has many sentiment models, and each model card says what it was trained on.
  • Test it on a hundred of your own examples, labelled by a person, before you trust it with a million. That’s how you find the sarcasm and the slang.
  • If nothing fits, train your own on a few hundred labelled examples from your own data.

In code#

Both models through the same pipeline, free and local (pip install transformers torch):

from transformers import pipeline

reviews = [
    "The coffee was not bad at all.",
    "I ordered a flat white and a scone.",
    "Oh great, another forty-minute wait. Just what I needed.",
]
models = {
    "two labels": "distilbert/distilbert-base-uncased-finetuned-sst-2-english",
    "three labels": "cardiffnlp/twitter-roberta-base-sentiment-latest",
}
for name, model in models.items():
    classifier = pipeline("sentiment-analysis", model=model)
    print(name)
    for review, result in zip(reviews, classifier(reviews)):
        print(f"  {result['label']:>8} {result['score']:.0%}  {review}")
# two labels
#   POSITIVE 100%  The coffee was not bad at all.
#   NEGATIVE 100%  I ordered a flat white and a scone.
#   POSITIVE 98%  Oh great, another forty-minute wait. Just what I needed.
# three labels
#   positive 93%  The coffee was not bad at all.
#    neutral 82%  I ordered a flat white and a scone.
#   positive 44%  Oh great, another forty-minute wait. Just what I needed.

What to remember

  • A sentiment pipeline is three lines of code; the model behind it decides which labels you get and which kinds of text it understands.
  • Deleting words one at a time (occlusion) shows what an answer depends on: sometimes sensible pairs like “not bad”, sometimes a stray “and”.
  • Confidence is not correctness: the movie-review model was at least 97% sure of every tricky sentence, including the 7 it got wrong.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.