Measure the Model Before You Train It
Before you train a classifier, you need to know how well it does already and what score would count as real progress. That takes three things: a way to score many labelled texts quickly, a number that summarises the result, and a simple point of comparison that any useful model has to beat. Fixing all three before training is what makes the score after training mean something.
Scoring texts in batches
A classifier can score one text at a time, but that is slow: each call to the model has its own overhead, and the processor spends most of its time waiting between small pieces of work. Scoring a batch, a group of texts sent through the model in one call, lets the same matrix operations work on many texts at once.
A batch is a tensor, and a tensor is rectangular: every row needs the same number of positions. Texts have different lengths, so the shorter ones are filled with a padding token until they match the longest, and the attention mask marks those filled positions as ones the model ignores. The question is how long to make the rows.
One option is to pad every text to one global length, such as the longest text in the whole dataset or the model's maximum input. Then a batch of short messages carries mostly padding, and the model still computes over every padded position. The better option is dynamic padding: pad each batch only to the longest text inside that batch. In the example below, the longest text in the whole set has 8 tokens, but the longest in this batch has 6.
- [CLS]
- card
- not
- working
- [SEP]
- [PAD]
- [PAD]
- [PAD]
- [CLS]
- where
- is
- my
- refund
- [SEP]
- [PAD]
- [PAD]
- [CLS]
- hi
- [SEP]
- [PAD]
- [PAD]
- [PAD]
- [PAD]
- [PAD]
- [CLS]
- card
- not
- working
- [SEP]
- [PAD]
- [CLS]
- where
- is
- my
- refund
- [SEP]
- [CLS]
- hi
- [SEP]
- [PAD]
- [PAD]
- [PAD]
Each batch now has its own width: a batch of short messages is narrow, a batch with one long message is wide. That is why padding waits until the batch is built, instead of happening once when the whole dataset is tokenized.
The object that builds a batch is a data collator: it takes a list of tokenized examples and turns them into one batch of tensors. In PyTorch it is the collate_fn of a DataLoader. PyTorch's default collate function only stacks the examples into tensors, which fails as soon as two of them differ in length. Transformers provides DataCollatorWithPadding for this job. You create it with the model's tokenizer, so it knows which padding token to use and on which side the model expects it, and by default it pads every batch to its own longest text.
import torch
from torch.utils.data import DataLoader
from transformers import DataCollatorWithPadding
# tokenizer, model and the tokenized dataset come from the same checkpoint
collator = DataCollatorWithPadding(tokenizer)
scoring_set = tokenized.select_columns(["input_ids", "attention_mask", "label"])
loader = DataLoader(scoring_set, batch_size=32, collate_fn=collator)
model.eval()
predictions, references = [], []
for batch in loader:
with torch.no_grad():
logits = model(**batch).logits
predictions.append(logits.argmax(dim=-1))
references.append(batch["labels"])
predictions = torch.cat(predictions)
references = torch.cat(references)A few details make this loop work:
- The text column is dropped with
select_columns, because a collator cannot turn strings into tensors. - The collator renames the
labelcolumn tolabels, the name the model's forward method takes. - The
DataLoaderis not shuffled (it does not shuffle unless you passshuffle=True), so the texts are scored in the dataset's order. model.eval()switches dropout off (during training, dropout switches off random parts of the network, so the same text could otherwise get different answers), andtorch.no_grad()skips the bookkeeping for gradients, which scoring does not need.- For each text, the predicted class is the one with the highest logit.
Padding changes the shape of a batch, not the answer for a text: the attention mask tells the model to ignore padded positions, so a text gets the same predicted class whichever batch it lands in.
True or false?
With dynamic padding, every batch of a scoring run has the same shape.
False. The number of texts per batch stays the same (except perhaps the last batch), but the length of each batch is the length of its own longest text, so it changes from batch to batch.
Padding a batch to its longest text instead of to the model's maximum length leaves the predicted classes unchanged.
True. The attention mask marks padded positions to be ignored, so only the amount of wasted computation changes, not what the model predicts.
Accuracy: the share of correct answers
Once you have a predicted class and a true label for every text, the simplest summary is accuracy: the number of texts the model labels correctly, divided by the number of texts scored. If a model gets 42 of 50 messages right, its accuracy is 0.84, or 84 percent.
With the predictions and the labels as tensors, this is one line: (predictions == references).float().mean(). The comparison gives a tensor of true and false values, and its mean is the share of true ones. Libraries compute the same fraction: scikit-learn's accuracy_score(y_true, y_pred) and the accuracy metric of Hugging Face's Evaluate library both return it.
Accuracy is easy to read, and that is also its weakness: it counts every example the same, so the largest classes decide most of it. Picture 100 messages, 80 about cards, 10 about refunds and 10 about transfers, and a model that answers "card" for every one of them. It is right 80 times, so its accuracy is 0.80, and yet it never recognises a single refund or transfer message.
- Overall accuracy 80%
- Card messages right 100%
- Refund messages right 0%
- Transfer messages right 0%
The single number hides how the correct answers are spread over the classes. So read accuracy together with the number of examples in each class: on a set where the classes are about the same size, a high accuracy has to come from every class, while on an uneven set it can come from the largest class alone. Splitting the score by class is the way to see where the errors are.
True or false?
A model with an accuracy of 0.90 must be right on most examples of every class.
False. If one class makes up 90 percent of the set, a model that always answers that class scores 0.90 while missing every other class.
On a set where every class has the same number of examples, a model that is right on only one class can score no more than 1/K, that class's share of the set.
True. With K equal classes, each class holds 1/K of the examples, so a model that is right only on one class scores at most 1/K.
The baseline a model has to beat
An accuracy of 0.30 sounds poor, and 0.80 sounds good, but neither means anything until you know what a model with no skill at all would score on the same set. That score is the baseline: the result of the simplest alternative that never reads the text. A model is only worth something if it clearly beats it.
Three simple rules give the usual baselines for a set with K classes:
- Guess uniformly: pick one of the K classes at random, each with the same chance. On average one guess in K is right, so the expected accuracy is \( 1/K \), whatever the class sizes.
- Always answer the largest class: give every text the label that is most common. Its accuracy is exactly that class's share of the set.
- Guess in proportion to the class shares: pick a class at random, class \( i \) with probability \( p_i \), its share of the set. A guess of class \( i \) is then right with probability \( p_i \), so the expected accuracy is \( \sum_i p_i^2 \), which lies between the other two.
| Rule | 4 classes, 25% each | 3 classes, 80/10/10% |
|---|---|---|
| Guess uniformly | 0.25 | 0.33 |
| Guess by class shares | 0.25 | 0.66 |
| Always the largest class | 0.25 | 0.80 |
On a balanced set all three rules give the same number, \( 1/K \). On an uneven set they spread apart, and the one that matters is the highest: answering the largest class every time. A model scoring 0.75 on the uneven set beats guessing by far, and is still worse than a rule that ignores the text completely. So state the baseline as a number for the exact set you score on, from that set's own class counts.
from collections import Counter
counts = Counter(references.tolist())
uniform_baseline = 1 / len(counts)
largest_class_baseline = max(counts.values()) / len(references)scikit-learn packages the same rules as DummyClassifier, a classifier that makes predictions ignoring the input, with strategies such as "most_frequent", "uniform" and "stratified".
A pretrained model with a newly added classification head is, before training, close to such a baseline. Its head has random weights, so its answers carry no knowledge of the classes. They are not drawn afresh like a coin toss, though: the same random weights give the same answer for the same text every time, and they may favour a few classes. Its accuracy therefore lands near chance without sitting exactly on \( 1/K \), and the only way to know it is to measure it.
"Clearly beat" also has a size. On 50 examples, one more correct answer moves accuracy by 0.02, so a gain of a point or two over the baseline on a small set can be luck. A trained model should be well above the highest baseline, not just above it.
True or false?
On any set with 10 classes, the lowest score worth beating is 0.10.
False. 0.10 is what uniform guessing gets. If the largest class holds 25 percent of the set, always answering it scores 0.25, and that is the number to beat.
An untrained classification head scored twice on the same texts, in eval mode, gives the same predictions both times.
True. Its weights are random but fixed once loaded, and with dropout off the model is a fixed function of its input, so the same text gets the same answer.
Measure first, the same way before and after
A score after training says how much training helped only if it is compared with a score before training that was measured in exactly the same way. Change anything between the two, and the difference mixes the effect of training with the effect of the change. A different set, a different metric or a different way of counting can move the number by itself.
So the measurement is fixed before any training starts:
- The data: the same labelled set, with the same rows. This is a validation set split off from the training data, so the model never trains on its rows. It is not the test set either, which stays unopened for the final result.
- The metric: the same definition of the score, here accuracy, computed by the same code.
- The baseline: computed from that set's class counts and written down next to the score.
- The run: a fixed random seed, the model in eval mode and the data in a fixed order, so scoring the same model twice prints the same number.
- Fixed set and metric
- Score before untrained head
- Training
- Score after same set, same code
- Compare with baseline
- Fixed set and metric to Score before
- Score before to Training
- Training to Score after
- Score after to Compare with baseline
Measuring first also catches problems while they are still cheap. If the untrained model scores far above every baseline, something is wrong: the labels may have leaked into the inputs, or the set may not be the one you meant to use. And if the scoring code has a bug, it is better to find it before hours of training than after.
True or false?
Scoring the model before training on a different validation split than after training is fine, as long as both splits are the same size.
False. Different rows can be easier or harder and can have different class shares, so the difference between the two scores would not be the effect of training alone.
The score before training is worth writing down even though it is expected to be poor.
True. It is the starting point of the comparison and a check that the data and the scoring code behave as expected.