Judge the Fine-Tuned Model on the Test Set

Once a classifier is trained, two questions remain: how well will it do on text it has never seen, and where does it go wrong? The first is answered by one score on a held-out test set. The second needs more than one number: a score per class, a table of which classes the model mixes up, and a look at the wrong answers themselves, so that you know whether to trust the model, fix the data or accept the errors.

The test set is opened once

A labelled dataset is usually split three ways, and each part has one job. The training set is what the model learns from. The validation set is what you score while you work: you compare epochs, learning rates or two versions of the data on it, and keep the best. The test set is kept closed until all of those decisions are made, and then scored once.

The reason is that every decision made by looking at a score fits the model a little to the data behind that score. After twenty comparisons on the validation set, the winner is partly the best model and partly the model that happened to suit those particular examples. Its validation score is therefore a little too optimistic. The test set took part in none of those choices, so its score is the honest estimate of how the model does on new text, such as the messages it will meet once it is in use.

  • Training set the model learns
  • Validation set scored to make choices
  • Test set scored once, at the end
  • Training set to Validation set
  • Validation set to Test set

This only works if the test score has no way back into the work. If you see a weak test result, change a setting and score the test set again, the test set has become a second validation set, and its number is no longer an honest estimate. Scikit-learn's guide on common pitfalls puts it in one rule: test data should never be used to make choices about the model. What the test result is good for is understanding: reading where the model fails tells you what to try in the next round, which you then judge on the validation set again.

True or false?

Picking the best epoch by its test score still gives an honest test result, because the model never trained on the test set.

False. The model did not learn from those examples, but your choice did. The chosen epoch is the one that suits the test examples best, so its test score is too optimistic.

A test score is usually a little lower than the best validation score, and that is expected.

True. The validation score belongs to the setting that won many comparisons on that data, so it carries some luck. The test score carries none of it.

Precision and recall: two questions about one class

Accuracy, the share of all examples labelled correctly, says how often the model is right overall. It does not say which classes it handles well. For that, each class is judged on its own, as if the task were a yes-or-no question: is this message about this class or not?

Take a small support classifier with three classes, refund, delivery and password, scored on 45 test messages. Look at refund alone. Twenty messages really are refund requests. The model answers refund 17 times. Sixteen messages are in both groups: real refund requests the model labelled correctly. A message that is a real refund request, or that the model answers refund, falls into one of three cases:

  • True positive: a real refund request answered refund (16).
  • False positive: a refund answer for a message of another class (1).
  • False negative: a real refund request given another label (4).
  • Really refund (20)
  • Answered refund (17)
  • 16 true positives
  • 4 false negatives
  • 1 false positive

Two questions come out of those counts. Precision starts from the model's answers: of the 17 times it said refund, how many were right? Recall starts from the real examples: of the 20 refund requests, how many did it find?

$$\text{precision} = \frac{TP}{TP + FP} = \frac{16}{16 + 1} \approx 0.94$$

Precision

$$\text{recall} = \frac{TP}{TP + FN} = \frac{16}{16 + 4} = 0.80$$

Recall

The two fail in different ways, and they matter to different people. Low precision for refund means the refund team receives messages that are not theirs. Low recall means refund requests get lost in other queues. A model can push one up by giving up the other: answering refund only when it is very sure raises precision and lowers recall, while answering refund for anything that mentions money does the opposite. That is why both are read, for every class.

True or false?

Precision for a class is the share of that class's real examples that the model finds.

False. That is recall. Precision is the share of the model's answers for the class that are right.

A class the model rarely predicts can have high precision and low recall.

True. If the model names the class only for its clearest cases, those few answers are mostly right (high precision) while many real examples go to other classes (low recall).

F1 per class, and the macro average

Two numbers per class are hard to compare across many classes, so they are often combined into one, the F1 score. It is the harmonic mean of precision and recall, a kind of average that leans towards the smaller of the two numbers. It runs from 0 to 1, and unlike a plain average it stays low when either side is low: a class with precision 1.0 and recall 0.2 gets an F1 of about 0.33, not 0.6. The formula can also be written straight from the counts:

$$F_1 = \frac{2 \cdot \text{precision} \cdot \text{recall}}{\text{precision} + \text{recall}} = \frac{2\,TP}{2\,TP + FP + FN}$$

F1

Here is the full report for the three-class example. Support is the number of real examples of each class in the test set. The small password class shows why the per-class rows matter: every one of its 3 answers is right, yet it finds only 3 of its 5 messages, and its F1 is the lowest of the three.

Report for 45 test messages
ClassPrecisionRecallF1Support
refund0.940.800.8620
delivery0.760.950.8420
password1.000.600.755
accuracy0.8445
macro average0.900.780.8245
weighted average0.870.840.8445

The macro average is the plain mean of the per-class values: each class counts once, whatever its size. The weighted average weights each class by its support, so large classes dominate it. Weighted recall always equals accuracy. In the example, accuracy and weighted F1 are both 0.84 because the two large classes go well, while the macro F1 of 0.82 is pulled down by the weak small class. When every class matters to someone, the macro average is the summary to watch, because a class that fails cannot hide behind the classes that do well.

When the test set has the same number of examples in every class, the weighted and the macro averages are equal, and macro recall equals accuracy. A balanced test set makes the summary numbers agree, but they can still hide one weak class, so the per-class rows are read anyway.

In Python, scikit-learn prints this report from two lists of class ids, the true ones and the predicted ones. By default the report has a row for every class that appears among the true or the predicted ids. Passing all class ids to labels also keeps a row for a class that appears in neither, and fixes the order of the rows to match target_names. A class the model never predicts gets precision 0, with a warning, because no answer for it exists to be right.

from sklearn.metrics import classification_report, f1_score

names = ["refund", "delivery", "password"]
# y_true and y_pred: lists of class ids, one per test example
print(classification_report(y_true, y_pred, labels=[0, 1, 2],
                            target_names=names, digits=3))

macro_f1 = f1_score(y_true, y_pred, average="macro")

With more than two classes, f1_score needs the average argument, because its default, "binary", is meant for yes-or-no tasks. average="macro" gives the macro average, and average=None returns one value per class. The report also has no micro average row for an ordinary multiclass task: that number would equal accuracy, which already has its own row.

True or false?

The macro F1 is the F1 computed from the macro precision and the macro recall.

False. Scikit-learn's macro F1 is the mean of the per-class F1 scores. In the example that is 0.82, while the F1 of 0.90 and 0.78 would be about 0.84.

A test set with high accuracy can still contain a class whose recall is poor.

True. Accuracy pools all examples, so a small class can fail without moving it much. The password row in the example has recall 0.60 under an accuracy of 0.84.

The confusion matrix: who is mistaken for whom

The report says that refund loses 4 messages, but not where they go. A confusion matrix shows it. It is a table with one row per true class and one column per predicted class; each cell counts the test examples of that row's class that received that column's label. Rows for the true class and columns for the predicted one is scikit-learn's convention. Some books and tools use the opposite, so check the axis labels before you read a matrix.

True class (rows) against predicted class (columns)
True \ PredictedrefunddeliverypasswordRow total
refund164020
delivery119020
password0235
Column total1725345

The diagonal, from top left to bottom right, holds the correct answers: 16, 19 and 3. Everything off it is a mistake, and its position says which one. The 4 in the first row means four refund requests were labelled delivery.

The two scores of the previous sections are both inside this table. A row total is the class's support, so a class's recall is its diagonal cell divided by its row total (refund: 16 / 20). A column total is how often the model gave that answer, so precision is the diagonal cell divided by the column total (delivery: 19 / 25). The column for delivery collects mistakes from both other classes, which is where its lower precision comes from.

A mix-up has a direction. Cell (refund, delivery) holds 4 and cell (delivery, refund) holds 1: the model often turns refund requests into delivery questions and rarely does the reverse. A pair with both cells high points to two classes that are hard to tell apart; a pair with one cell high points to a class the model leans towards. With many classes, the matrix becomes too large to scan. Then it helps to list only the largest off-diagonal cells: the pairs of true and predicted class that occur most often. They point to the same mistakes much faster.

from sklearn.metrics import confusion_matrix

# rows: true class, columns: predicted class, in the order of labels
matrix = confusion_matrix(y_true, y_pred, labels=[0, 1, 2])
print(matrix)

When the model is a Transformers classifier trained with the Trainer, trainer.predict(test_dataset) scores the test set. Its result holds the logits in predictions and the true class ids in label_ids. Taking the highest logit of each row, with predictions.predictions.argmax(axis=-1), gives the predicted ids, and those two lists of ids are what both functions above take. The metrics it returns have names that start with test_, where trainer.evaluate uses eval_.

True or false?

In a confusion matrix, cell (A, B) and cell (B, A) always hold the same count.

False. They are two different mistakes: A examples labelled B, and B examples labelled A. In the example they are 4 and 1.

With rows as true classes, dividing a diagonal cell by its column total gives that class's precision.

True. The column holds every time the model gave that answer, and the diagonal cell is the part of them that was right.

Reading the mistakes themselves

The matrix says which classes are confused, but not why. For that, you print the misclassified test messages, each with its true label and the predicted one, and read them, pair by pair. Wrong answers tend to fall into three kinds, and each calls for a different response.

Three wrong answers, three causes
MessageLabelPredictedWhat it is
My parcel never arrived, I want my money back.refunddeliveryOverlap: the message is about both
My order still has not come, where is it?passworddeliveryDoubtful label: the model's answer fits better than the label
Where is the refund you promised last week?refunddeliveryWeakness: the intent is clear, the model misses it
  • Classes that overlap in meaning. Some messages really belong to two classes, and a reader would hesitate too. Fine-grained label sets have many such pairs; the authors of the BANKING77 intent dataset note that some of its categories partially overlap and need fine-grained decisions. More training does not remove this kind of error. The fix lies in the classes: merge them, define them more sharply, or route both to the same team.
  • Doubtful labels. Sometimes the model's answer looks at least as good as the label, which means the label may be wrong or the guidelines unclear. Counting such a case as a model error makes the model look worse than it is; correcting the label, in the data the model learns from as well, is the real fix.
  • A real weakness of the model. The message is clear, the label is right, and the model still fails. Here the wording often shows the pattern: in the example, a question that starts with "where is" and mentions waiting, so it reads like a delivery question even though it asks about money. Such errors point to what more training examples should cover.

Only the last is a fault of the model, and the only one more training could remove. Without reading the messages, all three look the same in the matrix, as one count in one cell. Reading a few dozen of them turns a score into a description of where and why the model fails, which is what decides whether it is ready for use.

True or false?

Every off-diagonal count in a confusion matrix is a weakness of the model that more training would fix.

False. Some errors sit between classes that overlap in meaning, and some come from doubtful labels. Only reading the messages tells them apart from real weaknesses.

When the model's answer looks better than the label, the test score counts the model as wrong anyway.

True. The score compares predictions with labels as they are. A doubtful label lowers the score without the model being at fault, which is why such cases are read and, where needed, corrected.