Sub topic 9
Using a pretrained transformer model
This chapter assumes you can run Python with pip-installed packages, know the basic supervised learning vocabulary (training data, test data, predictions), and have already built the TF-IDF and logistic regression baseline and the evaluation tools from the earlier chapters. The goal here is to run a pretrained transformer sentiment model, understand what it returns, and compare it honestly against the baseline.
What a pretrained sentiment model is
A transformer is a neural network that reads all the tokens of a text at once and builds a context-aware representation of each one. A pretrained transformer was first trained on a very large amount of unlabeled text to learn general language patterns. A sentiment model is that network with a small classification layer on top, further trained on texts labeled positive, negative, or neutral.
This differs from the TF-IDF baseline in a way that matters for sentiment. TF-IDF treats "not good" as two separate features, or as one bigram feature only if you asked for bigrams. A transformer sees the whole sentence, so "not" can change how "good" is represented. That helps with negation and with word-sense differences, and it is the main reason these models usually beat bag-of-words baselines on benchmark data.
You do not need to train anything to use one. Public models are published on the Hugging Face Hub, and the pipeline helper downloads the model and tokenizer and runs them for you.
Running a model with the pipeline API
The following example uses a model trained on social media text.
from transformers import pipeline
classifier = pipeline(
"sentiment-analysis",
model="cardiffnlp/twitter-roberta-base-sentiment-latest",
)
posts = [
"Just got my order and it is exactly what I wanted",
"Third outage this week. Unbelievable.",
]
for post, result in zip(posts, classifier(posts)):
print(post, "->", result["label"], round(result["score"], 3))The first run downloads several hundred megabytes of model files and caches them locally. You also need torch (or another supported backend) installed, for example with pip install transformers torch.
Each result is a dictionary with a label and a score. The score is the model's probability for the predicted label. Three details are easy to get wrong:
- The label names depend on the model. This model returns
positive,neutral, andnegative. Other models returnLABEL_0,LABEL_1,LABEL_2, orPOSITIVEandNEGATIVEonly. Read the model card, or checkclassifier.model.config.id2label, before mapping labels to your own scheme. - The number of classes is part of the model. A two-class model cannot output neutral. If your task has a neutral label, choose a three-class model or fine-tune one.
- The score is a probability that the model assigns, not a measure of how often it is right. Models are often overconfident, so a score of 0.99 does not mean 99% accuracy.
What happens inside the pipeline
The pipeline hides three steps. Knowing them helps when something goes wrong.
- Tokenization. The text is split into subword tokens, such as "unbeliev" and "able", and each is mapped to an integer ID. Special tokens mark the start and end of the sequence.
- Model forward pass. The transformer produces one vector for the sequence, and the classification layer turns it into one raw score (a logit) per class.
- Softmax. The logits are converted into probabilities that sum to 1. The label with the highest probability is returned.
Input length
Transformers have a maximum sequence length, typically 512 tokens for RoBERTa-style models. Tweets and most reviews fit. Long reviews do not. By default the pipeline does not always truncate for you, and an overly long input can raise an error. Pass truncation=True and, if you want to control the limit, max_length:
result = classifier(long_review, truncation=True, max_length=512)Truncation keeps only the start of the text. If a long review states its verdict at the end, the model never sees it. For long documents, consider splitting into chunks, scoring each, and aggregating, but check the result against labeled examples before trusting it.
Getting all class probabilities
By default the pipeline returns only the top label. For analysis you often want every class probability, for example to find uncertain cases. Use top_k=None:
from transformers import pipeline
classifier = pipeline(
"sentiment-analysis",
model="cardiffnlp/twitter-roberta-base-sentiment-latest",
)
outputs = classifier(["The update is fine, I guess."], top_k=None)
for item in outputs[0]:
print(item["label"], round(item["score"], 3))This returns a list of label and score pairs for each input. When the top two probabilities are close, the text is ambiguous or the model is unsure. Those cases are the best ones to send to a human reviewer.
Batching and speed
Calling the classifier once per post is slow. Pass a list, and set batch_size to process several texts at once:
results = classifier(posts, batch_size=32, truncation=True)On a CPU, a base-sized model handles tens of short texts per second. On a GPU it is much faster. To use a GPU, pass device=0 when creating the pipeline. A larger batch size uses more memory, and padding every text in a batch to the length of the longest one wastes work when lengths vary a lot. If you hit memory errors, lower batch_size first.
Choosing a model
The Hub has thousands of sentiment models. Compare them on these points before you pick one.
| Criterion | What to check | Why it matters |
|---|---|---|
| Training domain | Model card: tweets, product reviews, movie reviews, finance | A model trained on one domain often drops in accuracy on another |
| Label set | Two, three, or five classes | Must match your task definition from the first chapter |
| Language | English only or multilingual | An English model gives unreliable output on other languages |
| Size | Parameters and memory use | Larger models are slower and costlier for little gain on easy data |
| License | Model card license | Some licenses limit commercial use |
| Date | Training data period | Slang and topics change over time |
Check the training domain first. A model trained on movie reviews applied to customer support tweets is a domain shift, which a later chapter covers in detail.
Comparing against your baseline
A pretrained model is not automatically better for your data. Evaluate it the same way you evaluated the baseline: on the same held-out test set, with the same metrics.
from sklearn.metrics import classification_report, confusion_matrix
from transformers import pipeline
classifier = pipeline(
"sentiment-analysis",
model="cardiffnlp/twitter-roberta-base-sentiment-latest",
)
test_texts = [
"Love the quality",
"Disappointed, it broke quickly",
"It arrived on Tuesday",
"Best purchase this year",
"Not worth the price",
]
test_labels = ["positive", "negative", "neutral", "positive", "negative"]
outputs = classifier(test_texts, truncation=True)
pred = [o["label"].lower() for o in outputs]
labels = ["negative", "neutral", "positive"]
print(classification_report(test_labels, pred, labels=labels, zero_division=0))
print(confusion_matrix(test_labels, pred, labels=labels))Note the .lower() call. The label strings must match your gold labels exactly, or every prediction counts as an error. This five-item set only shows the mechanics. A real comparison needs hundreds or thousands of labeled examples that the model was not trained on.
Compare per-class results, not only overall accuracy. Pretrained models often do well on clear positive and negative texts and struggle on the neutral class, because neutral conventions differ between datasets. If your annotators called a factual complaint "neutral" and the model's training data called it "negative", the model will look wrong even though it is behaving consistently.
Common errors
- Label mismatch. Mapping
LABEL_0to the wrong class silently flips results. Verify with a few obvious examples such as "I love this" and "I hate this". - Using a two-class model for a three-class task. Neutral texts get forced into positive or negative.
- Skipping or over-applying normalization. Models trained on tweets have often seen URLs and mentions replaced with placeholders. The
<url>and@userstyle from the normalization chapter is common for this family, but check the model card. Do not lowercase or strip punctuation and emojis, because the model uses them. - Testing on training data. Some public models were trained on popular review datasets. If your test set comes from the same source, scores are inflated.
- Trusting confidence. High probability on a sarcastic sentence is still wrong.
- Ignoring truncation. Long reviews cut at 512 tokens may lose the verdict.
When to stay with this approach
Use a pretrained model as is when it scores acceptably on your labeled sample, your label scheme matches its labels, and latency and cost fit your budget. Consider fine-tuning when the model's domain differs from yours, when your labels differ from its labels, or when errors cluster in one class that matters to you. Fine-tuning is covered in a later chapter. A simpler baseline can still be the right choice when you need a fast, cheap, and explainable system, since logistic regression coefficients can be inspected directly and a transformer's decisions cannot.
Exercise
You run a three-class pretrained model on 500 labeled product reviews. Overall accuracy is 78%, but recall on the neutral class is 30%. Most neutral reviews are predicted as negative. Give two possible causes and one check for each.
Show answer
Cause 1: Annotation mismatch. Your annotators may label factual or mildly critical reviews as neutral, while the model's training data labeled them negative. Check by reading 20 to 30 misclassified neutral reviews and comparing your labeling guidelines with the model card's data description. Cause 2: Domain shift. The model may have been trained on tweets or movie reviews, where product-review phrasing such as "it works but the box was damaged" is rare. Check by evaluating the model on a small sample from its own training domain and comparing the neutral recall with the 30% you observed. If both causes hold, fine-tuning on your own labeled reviews is the next step.
Exercise
A colleague's script prints LABEL_2 for most outputs and reports 90% error against gold labels of positive, neutral, and negative. What is the likely problem, and how do you fix it without retraining?
Show answer
The model returns generic label names that the script does not map to the gold label strings, so nearly every prediction counts as wrong. Read classifier.model.config.id2label or the model card to see which class each LABEL_n means, build a dictionary that maps them to negative, neutral, and positive, apply it to the predictions, and confirm with a few obvious test sentences before re-running the evaluation.