Papa Programmer
Lesson 14 of 36

Fine-tune a classifier

10 min read

Optional

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.

python
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:

text
accuracy 83%
true access  : said access 3, said billing 0
true billing : said access 1, said billing 2

Each 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.

python
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.

  1. Model and tokeniser. AutoModelForSequenceClassification adds one output per label to the base model. num_labels=2 sets how many. Use the tokeniser from the same base.
  2. Prepare. Each message becomes token IDs. Truncation keeps long messages inside the model's limit.
  3. Metric. The model outputs a score per label, and argmax picks the highest. Accuracy is the share that match the true label.
  4. 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.
  5. 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.

  1. LabelsFix the label list and its numbers, and save the mapping with the model.
  2. BaselineScore a keyword or prompt baseline on held-out messages.
  3. TokeniseConvert text to IDs with the base model's tokeniser.
  4. TrainRun the Trainer for a few epochs, evaluating each epoch.
  5. ComparePrint the confusion matrix and read the wrong answers.
Train a classifier
Beat a baselineA tuned classifier must score above a simple keyword rule to earn its cost.
Keep the label mapThe model outputs numbers, so store the name for each number with it.
Read the errorsThe wrong answers show what the next round of data should cover.

Your reading position is saved

0%

0 of 36 complete

Contents

Learning tools