Sub topic 12
Fine-tuning a Transformer on Your Own Labeled Data
This chapter assumes basic Python, package installation with pip, and supervised learning. You should know the difference between training data, validation data, and test data. You should also understand that a pretrained transformer already contains language patterns learned from a large corpus.
What fine-tuning changes
A pretrained transformer can often classify text without seeing your data. Fine-tuning goes further: it updates the model's weights using labeled examples from your task.
For sentiment classification, each example contains text and a label such as negative, neutral, or positive. The transformer converts the text into contextual representations. A classification head then maps those representations to class scores. During training, the model compares its prediction with the known label and adjusts its weights.
Fine-tuning is worthwhile when your vocabulary, writing style, or label definitions differ from the model's original training data.
| Situation | Recommended action |
|---|---|
| Few examples and general language | Try a pretrained model first |
| Thousands of labeled examples from your domain | Fine-tune and compare against a baseline |
| Labels are inconsistent | Improve the labels before training |
Prepare a reliable dataset
Keep a separate test set until the end. Do not use test examples to choose hyperparameters or repeatedly inspect errors. If several posts come from the same author, product, or conversation, split by that group when possible. Otherwise, nearly identical text can appear in both training and test data.
Use integer IDs for labels:
0for negative1for neutral2for positive
Keep the mapping in your code and save it with the model. A prediction of 2 is meaningless if a later program forgets which class it represents.
A small dataset can demonstrate the workflow, but it cannot produce a trustworthy production model. Fine-tuning usually needs enough examples for every important language pattern and class.
Fine-tune with the Transformers library
Install the main packages:
pip install transformers datasets evaluate accelerate scikit-learn torchThe following example creates a small dataset, tokenizes it, fine-tunes DistilBERT, and evaluates the validation split. A real project should replace the sample sentences with reviewed data.
from datasets import Dataset, DatasetDict
from transformers import (
AutoTokenizer,
AutoModelForSequenceClassification,
DataCollatorWithPadding,
Trainer,
TrainingArguments,
)
import numpy as np
from sklearn.metrics import accuracy_score, f1_score
examples = {
"text": [
"The camera takes clear photos.",
"Delivery was fast and helpful.",
"The battery died after one day.",
"Support never answered my messages.",
"It is acceptable, but nothing special.",
"The package arrived on time.",
],
"label": [2, 2, 0, 0, 1, 1],
}
dataset = Dataset.from_dict(examples).train_test_split(
test_size=0.33, seed=42
)
data = DatasetDict({
"train": dataset["train"],
"validation": dataset["test"],
})
checkpoint = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
def tokenize(batch):
return tokenizer(batch["text"], truncation=True)
tokenized = data.map(tokenize, batched=True)
collator = DataCollatorWithPadding(tokenizer=tokenizer)
model = AutoModelForSequenceClassification.from_pretrained(
checkpoint,
num_labels=3,
id2label={0: "negative", 1: "neutral", 2: "positive"},
label2id={"negative": 0, "neutral": 1, "positive": 2},
)
def metrics(prediction):
predictions = np.argmax(prediction.predictions, axis=-1)
labels = prediction.label_ids
return {
"accuracy": accuracy_score(labels, predictions),
"macro_f1": f1_score(labels, predictions, average="macro"),
}
args = TrainingArguments(
output_dir="sentiment-model",
num_train_epochs=3,
per_device_train_batch_size=8,
per_device_eval_batch_size=8,
learning_rate=2e-5,
evaluation_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="macro_f1",
report_to="none",
)
trainer = Trainer(
model=model,
args=args,
train_dataset=tokenized["train"],
eval_dataset=tokenized["validation"],
tokenizer=tokenizer,
data_collator=collator,
compute_metrics=metrics,
)
trainer.train()
print(trainer.evaluate())learning_rate controls how much each update changes the pretrained weights. A rate that is too large can erase useful language knowledge. A rate that is too small may not adapt to your domain. Test several values on the validation set, then evaluate once on the untouched test set.
Check whether fine-tuning helped
Compare the fine-tuned model with a simple baseline, such as TF-IDF plus logistic regression, and with the original pretrained model. Use the same test examples and metrics for every approach.
Macro F1 gives every class equal importance. This matters when neutral examples greatly outnumber positive or negative examples. If one class is rare, inspect its recall and confusion-matrix row instead of relying on accuracy.
Fine-tuning cannot repair contradictory labels, missing classes, or a mismatch between training and production text. Review incorrect predictions by category: negation, sarcasm, slang, spelling, mixed sentiment, and domain-specific terms. If social posts are your target, include representative social posts during training and testing.
Exercise
Why should the test set remain untouched while choosing a learning rate and number of epochs?
Show answer
Using it for decisions makes the test result optimistic because the training process has indirectly adapted to those examples.