Fine-tune a classifier
10 min read
The task
The task is the one from Define the task and what success means: label each support message as access or billing. This Lesson uses two labels to keep the example short. The same code works with more labels by changing the label count.
Each record has a message and an integer label. Keep the mapping from names to numbers with the model, because the model outputs a number and you need to turn it back into a name. Here access is 0 and billing is 1.
Baseline first
A baseline tells you what a few lines of code can do without any training. The program below classifies by keyword and scores itself on six held-out messages, then prints the counts you need for a confusion matrix.
from collections import Counter
validation = [
("Account access problem", "access"),
("I cannot sign in", "access"),
("Password reset email never arrives", "access"),
("Question about a bill", "billing"),
("Why was I charged twice?", "billing"),
("Update my card details", "billing"),
]
def keyword_baseline(text):
words = text.lower()
return "billing" if any(w in words for w in ["bill", "charge", "invoice"]) else "access"
pairs = [(truth, keyword_baseline(text)) for text, truth in validation]
counts = Counter(pairs)
accuracy = sum(t == g for t, g in pairs) / len(pairs)
print(f"accuracy {accuracy:.0%}")
for truth in ["access", "billing"]:
print(f"true {truth:8}: " + ", ".join(f"said {g} {counts[(truth, g)]}" for g in ["access", "billing"]))It prints:
accuracy 83%
true access : said access 3, said billing 0
true billing : said access 1, said billing 2Each row of the printout is one true label and how the baseline spread its answers. The rows show where the mistakes are: a card-update message with none of the keywords got the access label. A fine-tuned model has to do better than this, on the same six messages, to be worth its cost.
The training code
The program below fine-tunes DistilBERT, a small model with an added classification head, on four toy examples. It demonstrates the steps, and it is far too small to give a meaningful score. Install compatible versions of PyTorch, Transformers, Datasets and Accelerate first. The base model downloads on the first run.
import numpy as np
from datasets import Dataset
from transformers import (
AutoModelForSequenceClassification,
AutoTokenizer,
DataCollatorWithPadding,
Trainer,
TrainingArguments,
)
base = "distilbert/distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(base)
model = AutoModelForSequenceClassification.from_pretrained(base, num_labels=2)
def prepare(data):
dataset = Dataset.from_dict(data)
return dataset.map(lambda batch: tokenizer(batch["text"], truncation=True), batched=True)
train = prepare({
"text": ["Cannot sign in", "Login fails", "Explain my invoice", "Wrong charge"],
"label": [0, 0, 1, 1],
})
validation = prepare({
"text": ["Account access problem", "Question about a bill"],
"label": [0, 1],
})
def accuracy(result):
predictions = np.argmax(result.predictions, axis=-1)
return {"accuracy": float((predictions == result.label_ids).mean())}
trainer = Trainer(
model=model,
args=TrainingArguments(
output_dir="classifier-output",
num_train_epochs=1,
per_device_train_batch_size=2,
eval_strategy="epoch",
report_to="none",
),
train_dataset=train,
eval_dataset=validation,
processing_class=tokenizer,
data_collator=DataCollatorWithPadding(tokenizer),
compute_metrics=accuracy,
)
trainer.train()
print(trainer.evaluate()["eval_accuracy"])The score depends on the run, so this Lesson does not print one. Read the code in five parts.
- Model and tokeniser.
AutoModelForSequenceClassificationadds one output per label to the base model.num_labels=2sets how many. Use the tokeniser from the same base. - Prepare. Each message becomes token IDs. Truncation keeps long messages inside the model's limit.
- Metric. The model outputs a score per label, and
argmaxpicks the highest. Accuracy is the share that match the true label. - Arguments. The epoch count, batch size and evaluation schedule go in
TrainingArguments. The values here are for a demonstration. The Lessons on training controls explain how to choose them. - Trainer. It computes the loss, updates the weights, and evaluates on the Validation setA held-out set used during development to compare settings or choose a checkpoint. A separate test set is kept for a final assessment. at the end of each epoch. The collator pads each batch to its longest message.
For a complete guide, see the Hugging Face text classification guide.
Check the result honestly
Score the trained model on the same held-out messages as the baseline, and print the same table. Four checks matter:
- Beat the baseline. If the tuned model does not, the extra cost bought nothing.
- Read the errors. Print the messages it got wrong and look for a pattern.
- Per-label scores. Report precision and recall for each label when the mistakes have different costs, as Define the task and what success means showed.
- Use the test set once. Pick the settings with the validation set, then run the test set a single time at the end.
With six validation messages, one answer moves accuracy by 17 points. A real evaluation needs at least a few hundred examples, and more for rare labels.
- LabelsFix the label list and its numbers, and save the mapping with the model.
- BaselineScore a keyword or prompt baseline on held-out messages.
- TokeniseConvert text to IDs with the base model's tokeniser.
- TrainRun the Trainer for a few epochs, evaluating each epoch.
- ComparePrint the confusion matrix and read the wrong answers.
Why use macro-averaged measures?
One label has far fewer examples than the others.
Overall accuracy can look fine while a rare class fails.
What does a weak validation score with a strong training score suggest?
Training accuracy is 99% and validation accuracy is 70%.
The model has memorised the training set instead of learning a general pattern.
How do you check the classifier really works?
The training run finished with a good score.
Held-out data and error reading show what the training score hides.
Your reading position is saved
0 of 36 complete
Lesson complete
Fine-tune a classifier
Up next