After this chapter you will be able to
fill the four-cell table and compute accuracy, precision, recall, specificity and from it;
explain why accuracy lies on imbalanced data, and how macro and micro averages answer;
read a confusion matrix and name its hardest class and most confused pair;
run an ablation and report a loop, not a number;
set a threshold, and say what calibration adds to ranking;
read a recurrent classifier’s score the same way as any other.
This chapter builds on Chapters 4 and 12, which supply the features and the recurrent classifier.
Part III has spent five chapters building models, four of them to predict the next word, moving from counting to a network, then a recurrence, then a gate, and one to translate with them. At no point did we say properly how you would know whether any of it worked in general. Perplexity was the answer for language models, and Section that section was careful to say that it measures surprise and not usefulness. Translation raised the same question and left it open. Neither answer is a discipline.
This chapter fixes that, and it does so on the simplest task in the field. Language modelling asks what comes next, whereas classification asks a smaller question and answers it far more reliably: given a document, which of a fixed set of labels applies?
Spam or not spam, positive or negative or neutral, news or fiction or government or learned. The label set is decided in advance and the model picks one.
This is the task that pays for itself, since it runs in every mail system, every support desk and every content moderation pipeline in production today. It is also where the empirical method of this field is easiest to see, so the chapter spends more time on evaluation than on models.
The chapter has a core and an extension. The core is Sections 15.3 to 15.6: the four outcomes, why accuracy lies, reading a confusion matrix and the experimental loop. It is everything needed to build a classifier, score it by macro-, ablate it and analyse its errors. Sections 15.7 and 15.8, on scores, curves and a recurrent classifier, sharpen the same measures. They can wait until the core works.
Everything needed for a strong classifier is already in Part II. Represent each document as a vector of term weights as Chapter 4 did, feed those vectors to a linear classifier, such as logistic regression or a linear support vector machine. Both learn one weight per feature, and both train on labelled documents.
That pipeline is thirty years old and it is still the right first move, since on many tasks it comes within a few points of a fine-tuned transformer at a thousandth of the cost. Two details decide most of its quality. The features come first, where unigrams are the default and adding bigrams captures short phrases such as not good, which unigrams cannot express at all. The weighting comes second, because raw counts let long documents shout while the tf-idf of Chapter 4 fixes both length and the dominance of common words.
A neural classifier replaces the hand-built vector with a learned one. The recurrent networks of Chapter 12 can read a document and hand their final state to a softmax, and Section 15.8 builds one once the evaluation is in place. The evaluation, however, is identical, and the evaluation is what most of this chapter is about.
Every measure in this chapter is a ratio of counts, and the counts come from one small table. Take the simplest classifier, which answers yes or no, and a test set in which every document truly belongs to one of two classes. One of them is the class being looked for, which is called the positive class, and the other is the negative class. The choice is a convenience, since a spam filter calls spam positive because spam is what it hunts. It must be fixed before any number is quoted, because swapping the classes swaps what several of the measures below mean. Each document then falls into one of four cells, according to what it is and what the classifier said.
| classifier says positive | classifier says negative | |
|---|---|---|
| truly positive | TP, true positive | FN, false negative |
| truly negative | FP, false positive | TN, true negative |
The name reads in two halves. The second word is the classifier’s answer, and the first says whether that answer was right. A false positive is therefore a document the classifier called positive and got wrong, and a true negative is a document it called negative and got right.
A spam filter reads emails, of which are spam, and it flags as spam. Counting what happened to each email gives the table below, where the margins record what was true and what was predicted.
| flagged as spam | passed | total | |
|---|---|---|---|
| really spam | |||
| really not spam | |||
| total |
Eighty spam emails were caught and twenty reached the inbox. Forty good emails were flagged, and were rightly left alone. Every email is in one cell only, so the four counts must add to , and a table that does not add up has a counting error in it.
Each measure puts some of the four counts on top and some on the bottom, and the useful habit is to ask which. Here are eight of them, worked on the filter above.
| measure | formula | here | value |
|---|---|---|---|
| accuracy | |||
| error rate | |||
| recall, sensitivity, TPR | |||
| miss rate, FNR | |||
| specificity, TNR | |||
| false positive rate, FPR | |||
| precision, PPV | |||
| negative predictive value |
They come in pairs that share a denominator. Recall and the miss rate both divide by the true spam, so they add to , and so do specificity and the false positive rate, which both divide by the genuine good email. Specificity is the share of good email correctly passed. These four describe how the classifier treats each class, and none of them changes if you give it twice as much of one kind of email to read.
Precision and the negative predictive value take their denominators from the predictions, flagged and passed, and they answer the question a reader of one verdict asks, which is how far to trust it. Of the emails flagged, two in three were spam, and of those passed, per cent were safe. Accuracy ignores the division entirely and counts all the right answers together.
A false positive is sometimes called a Type I error and a false negative a Type II error, names to recognise because papers use them, though FP and FN carry the same information without the memory test. The two errors rarely cost the same. A good email lost to the spam folder may matter more than a spam message reaching the inbox, or less, and the measure to quote follows from which.
Return to accuracy, and try a filter that lets everything through. It has , , and .
| filter | accuracy | recall | specificity | precision |
|---|---|---|---|---|
| flags (above) | ||||
| flags nothing | , reported as |
Ninety per cent accuracy, from a filter that has never caught a single spam message. Accuracy rewards the true negatives, and recall refuses to, so the two numbers tell opposite stories about the same filter. Its precision is because it made no positive claims, and libraries report that as and warn, the right response to a model that has said nothing.
Most classifiers produce a score, and the yes or no comes from a cut on it. Move the cut and the four counts move together. The same filter, run strictly, at the middle setting above, and loosely, gives this.
| cut | precision | recall | FPR | ||||
|---|---|---|---|---|---|---|---|
| strict | 60 | 6 | 40 | 894 | 0.9091 | 0.6000 | 0.0067 |
| middle | 80 | 40 | 20 | 860 | 0.6667 | 0.8000 | 0.0444 |
| loose | 95 | 135 | 5 | 765 | 0.4130 | 0.9500 | 0.1500 |
Recall and the false positive rate rise together as the cut loosens, because every extra email flagged is either a catch or a false alarm. Precision falls, since the extra emails are increasingly likely to be false alarms. No row is best in every column, and choosing one is a decision about costs that the model cannot make. Predict spam for everything and recall reaches while precision collapses, and predict it only when certain and precision rises while recall falls.
Recall and the false positive rate describe the filter, and , and they stay put when the mix of email changes. Precision does not, because it divides by everything flagged, and the false alarms scale with how much good email there is.
| spam share | spam | not spam | precision | ||
|---|---|---|---|---|---|
| 900 | 900 | 720 | 40 | 0.9474 | |
| 100 | 900 | 80 | 40 | 0.6667 | |
| 100 | 9900 | 80 | 440 | 0.1538 |
The filter is the same in every row. Precision falls from to only because the spam became rare, so a precision quoted without the class balance behind it says very little. This is the accuracy trap of the next section again, arriving through the other door.
Precision and recall pull against each other, so it is natural to want one number for the pair. The usual choice is their harmonic mean:
The harmonic mean is the point, because it is high only when both are high. An arithmetic mean would let a precision of hide a recall of , giving , while the harmonic mean gives and refuses to be flattered.
When one error is dearer than the other, weights recall times as much as precision, with . For the filter above , which sits closer to the recall of , as a score that cares about missed spam should.
Two summaries use all four cells, which never does. Balanced accuracy is the mean of recall and specificity, , and it is accuracy with the classes forced to count equally. The Matthews correlation coefficient treats the two label sequences as variables and correlates them:
It is for a perfect classifier, for one no better than chance and for one that is perfectly wrong, and it stays informative on imbalanced data where accuracy does not.
The obvious score is accuracy, the fraction of test documents labelled correctly, and it is the wrong default, as one example shows. Take a hundred test documents distributed unevenly.
| class | documents |
|---|---|
| news | 90 |
| fiction | 5 |
| government | 3 |
| learned | 2 |
Build a model that is a single line long and always answers news.
| class | precision | recall | |
|---|---|---|---|
| news | 0.9000 | 1.0000 | 0.9474 |
| fiction | 0.0000 | 0.0000 | 0.0000 |
| government | 0.0000 | 0.0000 | 0.0000 |
| learned | 0.0000 | 0.0000 | 0.0000 |
| accuracy | 0.9000 | ||
| macro- | 0.2368 | ||
Ninety per cent accuracy, from a model that cannot tell any two documents apart. Accuracy is blind to which classes are wrong, and what we want is a score where every class counts equally however rare it is.
With more than two classes there is no single positive, so ask the binary question once per class. Treat class as the positive class and every other class as the negative one, and the four counts of Section 15.3 follow. is documents predicted and truly , is predicted but truly something else, is truly but predicted something else, and is everything that is neither of those, which is every other document.
Precision and recall keep their meaning, and the harmonic mean of the previous section gives each class its own score:
None of the three uses , and for a rare class that is the intention. A class that makes up three per cent of the test set has the other ninety-seven per cent available as true negatives, and any measure that rewards them rewards the easy part of the job.
To get one number for the whole task, average the per-class scores across the label set.
Every class contributes one term whatever its size, so a classifier that ignores one class entirely scores for it and macro- drops by a full . Neglecting the rare class therefore costs you, and that is what Equation (15.3) is for, and why a leaderboard on an imbalanced task should use it.
Micro-averaging pools every decision first and computes one from the totals, so frequent classes dominate. One fact about it saves confusion later: on a single-label task micro- equals accuracy.
The reason is simple. When each document gets one label, every error is at once a false positive for the predicted class and a false negative for the true one. The pooled precision and the pooled recall are both the fraction correct and their harmonic mean is that same number. Micro- therefore tells you nothing accuracy did not, so report macro- or report the per-class table.
An evaluation score has one job, which is to put the better classifier first, and the averages above can be compared on that. Keep the hundred test documents of the accuracy trap, with news 90, fiction 5, government 3 and learned 2, and take three classifiers. A always answers news. B spreads its effort over the classes. C is tuned for the majority class. The first table counts how many documents of each class each one gets right.
| classifier | news | fiction | gov. | learned | accuracy |
| of 90 | of 5 | of 3 | of 2 | ||
| A always news | 90 | 0 | 0 | 0 | 0.9000 |
| B spreads its effort | 85 | 4 | 2 | 1 | 0.9200 |
| C chases the majority | 90 | 3 | 1 | 0 | 0.9400 |
By accuracy, which is also micro- here, C is the best of the three. Now score all three in every way the chapter has met, where acc. is accuracy and wtd is the weighted average of the per-class scores.
| acc. | news | fict. | gov. | learn. | wtd | macro- | |
|---|---|---|---|---|---|---|---|
| A | 0.9000 | 0.9474 | 0.0000 | 0.0000 | 0.0000 | 0.8526 | 0.2368 |
| B | 0.9200 | 0.9551 | 0.6667 | 0.6667 | 0.5000 | 0.9229 | 0.6971 |
| C | 0.9400 | 0.9677 | 0.7500 | 0.5000 | 0.0000 | 0.9235 | 0.5544 |
| ranks first | C | C | C | B | B | C | B |
Accuracy, the of the news class and the weighted , which averages the per-class scores with each class weighted by its size, all put C first, because the ninety news documents dominate each of them. C never finds a learned document and finds one government document in three, and neither failure moves those totals much. B finds something in every class. Macro- gives each class a quarter of the score and puts B first, the ranking the task wants. For a system that serves all four genres, the one that never finds a learned paper is the worse system.
A single carries a second bias, because it depends on which class is called positive. The same classifier C scores with news as the positive class and with learned, so a lone is meaningless until it says which class it belongs to. Macro- removes that choice by counting every class once.
It has a limit of its own, which the table shows. The learned class is two documents, so one more right or wrong would move for that class by a large step, and the macro average by a quarter of it. Give the counts beside a macro- so that the reader can see how much weight each term can bear.
One number cannot tell you what to fix, whereas a confusion matrix can. Rows are the true class and columns the prediction, so the diagonal is correct and every off-diagonal cell is an error.
| true predicted | news | fiction | govt. | learned | total |
|---|---|---|---|---|---|
| news | 9 | 0 | 2 | 1 | 12 |
| fiction | 0 | 11 | 0 | 1 | 12 |
| government | 3 | 0 | 7 | 2 | 12 |
| learned | 1 | 1 | 1 | 9 | 12 |
| predicted total | 13 | 12 | 10 | 13 | 48 |
The margins carry two totals for every class, and they are different quantities. The row total counts the documents that truly belong to it, and the column total counts the documents the classifier assigned to it. For news they are and , because twelve documents are news and the classifier called thirteen of them news, so the counts below take the row for one error and the column for the other.
Score it with Equation (15.2), taking one row per class. The first three counts are read straight off the matrix. For news, is the diagonal cell , is the rest of its column, , and is the rest of its row, . Check them against the margins: is the row total and is the column total. The true negatives are everything left over, so with documents in the test set .
| class | specificity | |||||||
|---|---|---|---|---|---|---|---|---|
| news | 9 | 4 | 3 | 32 | 0.6923 | 0.7500 | 0.7200 | 0.8889 |
| fiction | 11 | 1 | 1 | 35 | 0.9167 | 0.9167 | 0.9167 | 0.9722 |
| government | 7 | 3 | 5 | 33 | 0.7000 | 0.5833 | 0.6364 | 0.9167 |
| learned | 9 | 4 | 3 | 32 | 0.6923 | 0.7500 | 0.7200 | 0.8889 |
| accuracy | 0.7500 | |||||||
| macro- | 0.7483 | |||||||
Each row of counts adds to , the quickest check that no cell was misread. Specificity is , the share of the other genres that were correctly left alone.
The classes are balanced here at twelve each, so accuracy is not misleading, and it is still less useful because it says and stops. The per-class table says which genre is failing and how. Look at government, whose recall is because five of its twelve documents went elsewhere, and whose precision is because three documents from other genres were labelled government. Both directions are wrong at once, which is a different problem from being wrong in one direction only.
Both diagnoses are computed and not guessed. The hardest class is the one with the lowest per-class , which here is government at against , and . The most confused pair is the unordered pair with the most cross errors, found by adding the two off-diagonal cells that join them.
| pair | total | ||
|---|---|---|---|
| news / government | 2 | 3 | 5 |
| government / learned | 2 | 1 | 3 |
| news / learned | 1 | 1 | 2 |
| fiction / learned | 1 | 1 | 2 |
| news / fiction | 0 | 0 | 0 |
| fiction / government | 0 | 0 | 0 |
So the answer is news and government, with five errors between them. Both diagnoses are properties of the matrix, not opinions, and two people reading the same matrix must reach the same pair, which is what makes them gradeable.
One more thing the matrix shows that a score cannot is that the errors are directional. Government loses three documents to news and takes two back, and those are different mistakes with different causes.
A score is the end of an experiment, not the work. The work is a loop, and four rules give it its discipline.
Fix the split before you look. Train on train, tune on a held-out slice of train, and touch the test set once at the end, because every decision made while watching test scores is a decision that has quietly memorised the test set.
Ablate one factor at a time. An ablation changes one thing and records the validation score, and a log might read like this.
| configuration | validation macro- |
|---|---|
| unigrams, raw counts | 0.612 |
| unigrams, tf-idf | 0.681 |
| unigrams and bigrams, tf-idf | 0.724 |
| plus minimum document frequency 2 | 0.748 |
| plus lowercasing | 0.741 |
The last row went down, and reporting it is the point, because an ablation is a record of the runs you did, not of the runs that worked. Submit the best row. The winning configuration in your ablation must be the model you actually submit, and if it is not then your experiment log and your system have diverged, with one of them lying.
Read the errors themselves. Which class pairs blur, and what vocabulary do the misclassified documents share? A confusion matrix tells you where to look, and only the documents tell you why.
That loop, running from baseline to iteration to ablation to confusion matrix, is the empirical method of this whole field. It is the same loop for a linear classifier over tf-idf features and for a fine-tuned transformer, and only the middle step changes.
Everything so far scores a single decision. Precision, recall and all describe one cut through a ranking, and moving the cut moves all three. A model that outputs scores has not made that decision for you, so there is a second question underneath the first: how good is the ordering, before anyone picks a threshold?
Take ten documents, scored and ranked, with three belonging to the class of interest:
| score | label | TP | FP | precision | recall |
|---|---|---|---|---|---|
Each row is a threshold, and each threshold is its own four-cell table. Three of the ten documents are positive and seven are negative, so at every cut and , and the two rates of Section 15.3 follow. The table adds them for all ten cuts, including the four below that the previous one leaves out.
| score | TPR | FPR | ||||
|---|---|---|---|---|---|---|
| 1 | 0 | 2 | 7 | |||
| 2 | 0 | 1 | 7 | |||
| 2 | 1 | 1 | 6 | |||
| 3 | 1 | 0 | 6 | |||
| 3 | 2 | 0 | 5 | |||
| 3 | 3 | 0 | 4 | |||
| 3 | 4 | 0 | 3 | |||
| 3 | 5 | 0 | 2 | |||
| 3 | 6 | 0 | 1 | |||
| 3 | 7 | 0 | 0 |
ROC stands for receiver operating characteristic, a name from signal detection theory, where it described how well a receiver could tell a signal from noise. The ROC curve plots the true positive rate (TPR, which is recall) on the vertical axis against the false positive rate (FPR) on the horizontal one, with one point for every threshold. It starts at the origin, where nothing is flagged, and ends at , where everything is, and the ten rows above are its points.
A classifier whose scores carry no information stays on the diagonal , because flagging a fraction of the documents catches the same fraction of each class. A perfect one passes through the corner , catching every positive before it flags a single negative. The area under the curve, written AUC, is therefore for guessing and for perfect, and for these ten points it is by trapezoids. The same number comes from counting pairs. Each of the three positives is compared with each of the seven negatives and wins if it was scored higher. The positive scored beats all seven, the one scored beats all seven, and the one scored beats six, because the negative scored sits above it. This is wins in pairs, and , so ROC-AUC is the probability that a randomly chosen positive outranks a randomly chosen negative.
The precision-recall curve plots precision against recall for the same thresholds, and PR-AUC averages precision over the thresholds at which recall actually moves, which are the ranks where a positive appears. Here the precision at those three ranks is , and , so PR-AUC is , and on a balanced problem the two areas usually agree like this.
Make the class rare, the ordinary situation in text. Two positive documents among a hundred, ranked third and tenth by the same model:
| measure | value | reading |
|---|---|---|
| ROC-AUC | still excellent | |
| PR-AUC | barely better than guessing |
The ranking is the same ranking. ROC-AUC counts how many negatives sit below each positive, and ninety-eight negatives is a great deal of credit for very little work. PR-AUC asks what fraction of what you flagged was right, and at rank ten that is . The first number flatters the model and the second describes what a user would experience.
Under class imbalance, report PR-AUC as well. This is the accuracy trap from earlier in this chapter returning in a more sophisticated costume, because any measure dominated by the majority class will always look generous.
There is a last question that none of these metrics asks. A score of ought to mean the model is right about nine times in ten. Nothing in cross-entropy training guarantees that, and nothing in , ROC-AUC or PR-AUC would notice if it were false, because every one of them depends only on the order.
Group the predictions by confidence and compare what each bin promised against what it delivered:
| bin | mean score | correct | observed | gap | |
|---|---|---|---|---|---|
| to | |||||
| to | |||||
| to |
Weighting those gaps by bin size gives an expected calibration error of . The least confident bin is close to honest and the most confident is the worst, promising and delivering . This is the usual shape.
The ordering here may still be perfect, so every metric in this chapter so far would report a healthy model. Whenever a decision has a cost attached, and a threshold is chosen to balance that cost, the probability has to mean something and this is the table that says whether it does.
This section is for understanding an architecture, not for building the baseline classifier. A training set of documents is far too small to fit a recurrent network, and the linear baseline of the earlier section is the right tool there. What the section does is connect this chapter to Chapters 12, 13 and 14, and show that the evaluation of the previous sections does not care how the scores are made.
The linear baseline reads a document as a bag of words, so it has no idea that not good is two words in a particular order. The networks of Chapters 12 and 13 read in order. They carry a state that summarises everything seen so far, and the gates of the LSTM and the GRU keep that state alive across a long text. What they produce is a state for every word, whereas a classifier needs one decision for the whole document, so the architecture is the smallest bridge that turns the first into the second:
The cell is Equation (12.14), or the LSTM or the GRU of Chapter 13. The vector is whatever the head is shown of the sequence, and is a matrix with one row per class. The output layer is Equation (12.15) used once for the document where the language model used it at every step, and the loss is the same cross-entropy against a one-hot label, .
Take the sentence the dog ran and the weights of the unrolling example in Chapter 12, whose three states , and are already in a table there. Two classes, negative and positive, need a head with two rows, and the label of this document is positive:
The weights are chosen, not trained, so the predictions mean nothing, and the sentence is neutral anyway. What the example shows is how a number travels from the words to a loss. Give the head the last state and it computes the scores , which the softmax turns into probabilities.
| value | scores | (neg), (pos) | loss | |
|---|---|---|---|---|
| last state | 0.4174 | |||
| mean of states | 0.6433 | |||
| max of states | 0.8355 |
The loss is of the probability given to the true class, so for the first row. The three rows differ only in the choice of , which is the next question.
The last state is the usual choice, because was computed from every earlier state and in principle holds the whole document. It has one weakness, which is that everything has to survive the trip to the end. Mean pooling averages the states, so every word contributes directly and the document vector is hard to dominate by its final few words. Max pooling keeps, for every unit, the largest value it took anywhere in the text, which suits a unit that fires on a particular phrase wherever it occurs. A fourth choice is attention pooling, which weights the states by a learned query and sums them, the mechanism of Chapter 14 used to pool one sequence, not to align two.
Chapter 12 said that a bidirectional recurrent network cannot generate text, since its backward pass needs words not yet written. A classifier reads the whole document before it decides, so there is no such limit. Run one recurrence in each direction and join the final states, . The head then has inputs, so holds weights for classes where the one directional head held , and every word has seen both its left and its right context before the decision is made.
Backpropagation through time starts from one loss now, and the choice of decides where its error enters the unrolled network. Write for the error at the scores, as in Equation (12.2). With the last state, the head sends to step and nowhere else. Equation (12.7) therefore loses its first term at every earlier step, and each earlier error is carried back alone,
Mean pooling restores the first term at every step, scaled by , because each state contributes a share of :
On the example, the size of the error reaching each word is this.
| step | word | last state | mean pooling |
|---|---|---|---|
| 3 | ran | 0.5568 | 0.2580 |
| 2 | dog | 0.3139 | 0.4201 |
| 1 | the | 0.1644 | 0.4697 |
With the last state, the error at the first word is of what it is at the last, after only two steps back, and in a longer document it would shrink further, by the product of Section that section. Mean pooling gives the first word more than the last, because it receives its own share directly instead of an inheritance.
An LSTM or a GRU replaces the recurrent step and leaves the rest alone. Run the same sentence through the gates of Chapter 13, with for the LSTM, and give each final state to the same head.
| cell | (neg), (pos) | loss | |
|---|---|---|---|
| RNN | 0.4174 | ||
| LSTM | 0.7794 | ||
| GRU | 0.9626 |
The numbers differ because the three cells carry different weights, and nothing in the table says that one of them classifies better. What the cell changes is how much of the first word is still audible at the end of a long document, the distinction of Chapter 13. Classify only the last state of an -token document and the error at the first token has been multiplied times.
| tokens | plain RNN, factor | LSTM, forget gate |
|---|---|---|
| 10 | ||
| 50 | ||
| 200 |
A review of two hundred words is an ordinary document, and at that length the plain network has nothing left to learn its first sentence from while the gated one keeps about thirteen per cent of the signal.
Nothing in the evaluation depends on how the scores were produced. The head’s softmax output is a score for each class, so everything earlier in this chapter applies unchanged: the four outcomes, per-class precision and recall, the confusion matrix, macro- and the threshold sweep. The last of those deserves a warning, because a softmax is trained on cross-entropy, not for calibration, so its probabilities can be over-confident, and the calibration table above is how to check. The architecture is new, and the discipline of judging it is the same.
Run it.
code/worked_examples/classification.pyproduces every table in this chapter.--outcomescounts the four cells of the spam filter and prints every ratio built from them,--trapbuilds the ninety-per-cent-accuracy model that has learned nothing,--matrixscores the genre matrix class by class,--readderives the hardest class and the most confused pair,--averagesshows micro- landing on accuracy,--thresholdsweeps the ranking for ROC-AUC and PR-AUC,--calibrationchecks whether the scores mean anything,--rankscores three classifiers on one skewed test set and shows which score crowns which, and--recurrentsends one sentence through an RNN, an LSTM and a GRU into a classification head and follows the error back.
Part III began with counting words to predict the next one and it ends with a classifier and a confusion matrix, by way of a translator. Three things carry forward unchanged. The objective is still cross-entropy against a one-hot target, whether the target is the next word, the next word of a translation or a genre label. The evaluation discipline is now fixed, meaning held-out data, a stated metric, one factor at a time, and a matrix rather than a number. The representation is still a vector, still built from context.
Two limits remain, and they set the next part. Every word has had one vector, and Chapter 9 already showed why that fails for bank. Part IV opens by removing that constraint. And the recurrence still has to run one step at a time, so that a long text cannot be read in parallel. Attention has so far been a decoder looking at an encoder, globally and then locally, in Chapter 14. Chapter 17 lets a sequence look at itself, and the recurrence can then go.
Summary
A classifier is judged from a table of four counts, true and false positives and negatives, and every measure is a ratio of them. Accuracy lies on imbalanced data, because a model that always names the majority class scores highly. Precision, recall and per class are used instead, with macro averaging to give each class equal weight and micro averaging to pool decisions. On a single-label task micro- equals accuracy. A confusion matrix names the hardest class and the most confused pair. Evaluation is a loop of held-out data, one factor at a time, and a record of every run. When the threshold is yours to choose, ROC and PR curves rank differently on rare classes, and scores need calibration to be read as probabilities. A recurrent classifier is measured exactly like any other.
Key terms
confusion matrix. a table of counts of true class against predicted class.
precision. the share of predicted positives that are truly positive.
recall. the share of true positives that the classifier finds.
. the harmonic mean of precision and recall.
macro averaging. averaging a per-class score over classes, giving each equal weight.
micro averaging. pooling all decisions before computing one score.
calibration. agreement between a predicted probability and the observed frequency.
ablation. changing one factor at a time and recording the effect on a held-out score.
Jurafsky and Martin (2025) cover naive Bayes, logistic regression and
evaluation with more worked cases. Manning et al. (2009) treat
classification and evaluation from the information retrieval side, where
precision and recall were first made standard. Sokolova and Lapalme
(2009) survey the averaging choices and what each of them hides.
Everything in this chapter is one import away in
sklearn.metrics, whose classification_report
prints the per-class table and three different averages. Only one of
them would have caught the always-news model of Section 15.4.
15.1 Fill the table. A classifier is run on documents and produces , , and . Check that the cells add to , then compute accuracy, precision, recall, specificity, the false positive rate and , showing the fraction for each. Which two of them would not change if the test set held twice as many negative documents of the same kind?
15.2 Which error is dearer. For a screening system that flags documents for human review, say which of and is the costlier error and which of precision, recall and specificity you would therefore watch. Then repeat for a filter that automatically deletes what it flags. Explain why the answer changed.
15.3 Rarer and rarer. Keep the recall and false positive rate of the first exercise and apply the classifier to a corpus with per cent positive documents out of . Compute , and precision. Then find the share of positives at which precision falls to one half.
Build and measure
15.4 Build the trap. Construct a four-class test set of documents where a majority-class classifier scores above accuracy and below macro-. State the class distribution you used, and explain which property of Equation (15.3) makes the second number small.
15.5 Score the matrix by hand. Using the genre matrix in this chapter, compute , and for government and confirm , and . Then say in one sentence what the gap between its precision and its recall tells you.
15.6 Why the harmonic mean. A class has and . Compute the arithmetic mean and the harmonic mean. Which one would you rather report to someone deciding whether to deploy the system, and why?
15.7 Micro equals accuracy. Prove that for single-label classification the pooled and pooled are equal, and therefore that micro- equals accuracy. Where does the proof break if a document may carry two labels?
15.8 Find the pair. For the genre matrix, list all six unordered class pairs with their cross-error totals and confirm the winner. Then construct a matrix in which the hardest class is not a member of the most confused pair, and explain how that happens.
15.9 Run an ablation. On a corpus of your choice, build a tf-idf and linear-classifier baseline and record validation macro-. Then change one factor at a time: bigrams, minimum document frequency, sublinear term frequency. Report every run including the ones that hurt, and state which row you would submit.
15.10 Read the documents. Take the ten misclassified documents from your most confused pair. What vocabulary do they share? Propose one feature change that would help, predict its effect on macro- before running it, then run it and report the gap between your prediction and the result.
15.11 One ranking, two verdicts. The rare-class example scores ROC-AUC and PR-AUC on the same ordering. Move the second positive document from rank ten to rank four and recompute both. Which number moves more, and explain what that says about which one is measuring the thing a user cares about.
In practice
15.12 Where the threshold should sit. Using the ten-document table, suppose a false positive costs one unit and a false negative costs eight. Compute the total cost at every threshold and name the cheapest. Then say what would have to change for the cheapest threshold to be the one that maximises .
15.13 A model that ranks perfectly and lies. Construct scores for ten documents where the ordering is flawless, so ROC-AUC is exactly , and the expected calibration error is above . Explain why no metric in this chapter before the calibration table would report a problem.
15.14 Three averages, one honest.
Feed the ninety, five, three, two test set and the always-answer-news
predictions to sklearn.metrics.classification_report. It
reproduces this chapter’s table exactly,
macro-
of
included. Now read the row it adds, the weighted average, which reports
for a model that cannot tell any two documents apart. Say which of the
three averages you would put in a paper, which one a vendor would put in
a brochure, and what zero_division has to be set to before
any of them appear at all.
15.15 Read the library’s matrix.
Build the
labels and predictions of the spam filter in Section 15.3 and pass them to
sklearn.metrics.confusion_matrix. Its output is
[[860, 40], [20, 80]], with the true negatives in the top
left corner. Say which of the four cells sits where compared with this
chapter’s table, and what the labels argument changes if
you want spam first.
15.16 Pool by hand. Using the three states of the unrolling example in Chapter 12, compute the mean and the max of the states, then the scores and the softmax for each, and confirm the loss for mean pooling. Which pooling gives the true class the highest probability on this sentence, and why is that not evidence that it is the better choice?
15.17 Size the head. A genre classifier with four classes reads documents with a recurrent layer of units. How many weights and biases does the classification head hold for the last state, and how many when the layer is made bidirectional? Compare each with the number of parameters in .
15.18 How far back. A model classifies only the last state. For a per-step factor of , find the document length at which the error reaching the first token falls below of its starting size. Repeat for , and say what the difference means for the choice between a plain network and a gated one.
Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.
classification.pyAccuracy, F1 and a confusion matrix
The four outcomes (TP, FP, FN, TN) and every measure built from them, the accuracy trap, the confusion matrix, the threshold-free metrics underneath, which average to trust on skewed classes, and a recurrent network as a classifier.
runs in your browser Run itFrom Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.