Sub topic 12
Fine-tuning a transformer on your own labeled data
This chapter shows how to adapt a pretrained transformer to your own sentiment labels, and how to decide whether that effort is worth it. It assumes you have read the earlier chapters on labeled data, evaluation metrics, class imbalance, and pretrained transformer models. You should also be comfortable with PyTorch-style training loops at the level of "a model, a loss, an optimizer". The code uses the Hugging Face transformers, datasets, and scikit-learn packages.
What fine-tuning changes
A pretrained model such as distilbert-base-uncased already knows a lot about language from large-scale training on unlabeled text. Fine-tuning continues training on your labeled examples. Two things are updated:
- A new classification head, a small linear layer on top of the encoder. It is initialized randomly and maps the encoder's summary vector to your label set.
- The encoder weights, usually all of them, with a small learning rate so the pretrained knowledge is adjusted and not overwritten.
The label scheme is yours. If your labels are negative, neutral, and positive, the head has three outputs, whatever the original model used.
When fine-tuning is worth it
Try the cheaper options first. A pretrained sentiment model used as-is is a baseline, and your TF-IDF plus logistic regression model is another. Fine-tune when one of these applies:
- Your label scheme differs from any public model (for example, "complaint", "praise", "question").
- The domain differs from the model's training data, and error analysis shows systematic misses on your vocabulary, slang, or product names.
- Your evaluation shows a gap that a stronger model could close, and you have enough labeled data to train and evaluate it.
As a rough guide, a few hundred labeled examples per class can beat a zero-shot model when the domain is unusual. Under about 100 total examples, the held-out set becomes too small to tell whether fine-tuning helped. In that case, improve the labels or use a lexicon or a pretrained model unchanged.
| Option | Labeled data needed | Compute | Typical use |
|---|---|---|---|
| Lexicon (VADER) | None | Negligible | Quick baseline |
| TF-IDF + logistic regression | Hundreds to thousands | CPU, seconds | Strong, cheap, easy to inspect |
| Pretrained sentiment model as-is | None | CPU or GPU inference | Same label scheme, similar domain |
| Fine-tuned transformer | Hundreds to thousands | GPU preferred | Custom labels or shifted domain |
The workflow
The test set is touched once, at the end. If you tune hyperparameters against it, its score becomes optimistic, the same mistake as evaluating on training data.
A complete fine-tuning script
The script below uses a tiny in-memory dataset so that it is self-contained. It is for learning the mechanics, not for real results. With 12 training examples the scores are noise. Replace the lists with your own data, split into three parts.
It was written for transformers 4.41 or later, where the argument is named eval_strategy. Older versions call it evaluation_strategy. Install the dependencies with pip install transformers datasets scikit-learn torch accelerate.
import numpy as np
from datasets import Dataset
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
from transformers import (
AutoModelForSequenceClassification,
AutoTokenizer,
DataCollatorWithPadding,
Trainer,
TrainingArguments,
)
labels = ["negative", "neutral", "positive"]
label2id = {name: i for i, name in enumerate(labels)}
id2label = {i: name for name, i in label2id.items()}
train_rows = [
("Great phone, battery lasts all day", "positive"),
("Absolutely love the camera", "positive"),
("Fast shipping and perfect fit", "positive"),
("Works as described", "neutral"),
("It arrived on Tuesday", "neutral"),
("Average sound, nothing special", "neutral"),
("Broke after two days", "negative"),
("Worst customer service ever", "negative"),
("Screen cracked, total waste of money", "negative"),
("Really happy with this purchase", "positive"),
("Box was opened, product is okay", "neutral"),
("Third outage this week, unacceptable", "negative"),
]
val_rows = [
("Love it", "positive"),
("It does the job", "neutral"),
("Stopped working, very disappointed", "negative"),
]
def to_dataset(rows):
return Dataset.from_dict({
"text": [text for text, _ in rows],
"label": [label2id[name] for _, name in rows],
})
model_name = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
def tokenize(batch):
return tokenizer(batch["text"], truncation=True, max_length=128)
train_ds = to_dataset(train_rows).map(tokenize, batched=True)
val_ds = to_dataset(val_rows).map(tokenize, batched=True)
model = AutoModelForSequenceClassification.from_pretrained(
model_name,
num_labels=len(labels),
id2label=id2label,
label2id=label2id,
)
def compute_metrics(eval_pred):
logits, y_true = eval_pred
y_pred = np.argmax(logits, axis=-1)
precision, recall, f1, _ = precision_recall_fscore_support(
y_true, y_pred, average="macro", zero_division=0
)
return {
"accuracy": accuracy_score(y_true, y_pred),
"macro_precision": precision,
"macro_recall": recall,
"macro_f1": f1,
}
args = TrainingArguments(
output_dir="sentiment-ft",
learning_rate=2e-5,
per_device_train_batch_size=8,
per_device_eval_batch_size=8,
num_train_epochs=4,
weight_decay=0.01,
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="macro_f1",
report_to="none",
seed=42,
)
trainer = Trainer(
model=model,
args=args,
train_dataset=train_ds,
eval_dataset=val_ds,
data_collator=DataCollatorWithPadding(tokenizer),
compute_metrics=compute_metrics,
)
trainer.train()
print(trainer.evaluate())
trainer.save_model("sentiment-ft/best")
tokenizer.save_pretrained("sentiment-ft/best")Several choices here matter.
- Dynamic padding.
DataCollatorWithPaddingpads each batch to its longest example. Padding everything to 128 tokens wastes compute on short social posts. - Macro F1 for model selection. Accuracy rewards ignoring a small class. Macro F1 averages per-class F1, so each class counts equally. Use it whenever classes are imbalanced.
id2labelandlabel2id. They are saved with the model, so a laterpipeline("sentiment-analysis", model="sentiment-ft/best")printspositiveand notLABEL_2.- A fixed seed. The classification head starts random, so results vary between runs. Report the spread over several seeds when comparing two settings.
To use the saved model:
from transformers import pipeline
clf = pipeline("sentiment-analysis", model="sentiment-ft/best")
print(clf("Third outage this week. Unbelievable."))Hyperparameters that usually matter
- Learning rate. Values between
1e-5and5e-5are standard. If validation loss spikes or the model predicts one class for everything, lower it. - Epochs. Two to four is typical. More epochs on a small dataset memorize it. Watch the validation metric, and keep the best checkpoint as the script does.
- Max length. Reviews can be long, while posts are short. Truncation silently drops the end of a long review, where the verdict often sits. Check how many of your examples exceed the limit.
- Batch size. Limited by GPU memory. If memory is short, lower it and consider
gradient_accumulation_steps.
Handling class imbalance during fine-tuning
The imbalance chapter covered resampling and metrics. A transformer adds one more option, a weighted loss that penalizes errors on rare classes more heavily. Subclass Trainer and override compute_loss:
import torch
from collections import Counter
from transformers import Trainer
def balanced_weights(label_ids, num_classes):
counts = Counter(label_ids)
total = len(label_ids)
return torch.tensor(
[total / (num_classes * counts[i]) for i in range(num_classes)],
dtype=torch.float,
)
class WeightedTrainer(Trainer):
def __init__(self, *args, class_weights=None, **kwargs):
super().__init__(*args, **kwargs)
self.class_weights = class_weights
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
labels = inputs.pop("labels")
outputs = model(**inputs)
weights = self.class_weights.to(outputs.logits.device)
loss = torch.nn.functional.cross_entropy(
outputs.logits, labels, weight=weights
)
return (loss, outputs) if return_outputs else loss
# Usage: pass class_weights=balanced_weights(train_ds["label"], 3)
# to WeightedTrainer(...) in place of Trainer(...), with the same other arguments.Weights equal to total / (num_classes * count) give a perfectly balanced class a weight of 1. Weighting trades precision on the rare class for recall, so re-check both after you apply it.
Common errors
- Data leakage. Near-duplicate posts, such as retweets or copied reviews, can land in both train and test sets. Deduplicate before splitting. When several reviews come from one author or product, split by author or product.
- Label quality caps the result. A model cannot reliably beat the agreement between your annotators. If two humans agree on only 75% of examples, 90% accuracy on those labels likely means leakage or an easy test set.
- Catastrophic forgetting. Too high a learning rate or too many epochs can erase useful pretrained behavior, such as handling negation. Sanity-check a few handwritten negation examples after training.
- A trained head with the wrong label count. Loading a three-label checkpoint into a two-label setup raises a size-mismatch error. Pass
ignore_mismatched_sizes=Trueto reinitialize the head. - Overconfident scores. Softmax probabilities from fine-tuned transformers are often too confident. Treat them as rankings and not as true probabilities, unless you calibrate them on validation data.
Checking for domain shift after fine-tuning
A model fine-tuned on product reviews can lose accuracy on social posts, and the reverse is also true. Keep a small separate set from each source you care about, and report metrics per source, not one blended number. If the social-post score is much lower, add labeled posts to the training data and repeat the loop in the diagram.
Exercise
You fine-tune a three-class model on 5,000 reviews where 80% are positive. It reaches 85% accuracy on a test set drawn from the same data, but you suspect it is weak on the negative class. Name two changes to how you train or evaluate it, and say why each helps.
Show answer
First, report per-class precision and recall, macro F1, and a confusion matrix. Select the best checkpoint with macro F1 instead of accuracy. A model that predicts "positive" for most inputs already scores about 80% accuracy, so accuracy hides the weak negative class. Second, address the imbalance during training, for example with a class-weighted loss as in WeightedTrainer, or by collecting more negative examples. This raises the cost of missing a negative review, which usually improves negative recall, though you must check that negative precision does not drop too far. The test and validation sets must keep the original class distribution.