Contents Language Models Code Course home

Chapter 15Text Classification and Evaluation

After this chapter you will be able to

  • fill the four-cell table and compute accuracy, precision, recall, specificity and F1F_1 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.

The oldest useful task

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-F1F_1, 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.

A baseline you already have

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.

Four outcomes

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.

Counting the four, worked

A spam filter reads 10001000 emails, of which 100100 are spam, and it flags 120120 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 TP=80TP = 80 FN=20FN = 20 100100
really not spam FP=40FP = 40 TN=860TN = 860 900900
total 120120 880880 10001000

Eighty spam emails were caught and twenty reached the inbox. Forty good emails were flagged, and 860860 were rightly left alone. Every email is in one cell only, so the four counts must add to 10001000, and a table that does not add up has a counting error in it.

Figure 15.1. The four outcomes of the spam filter. The shaded cells are the counts that precision uses in its numerator and recall uses in its numerator, so both share TP=80TP = 80. They differ in the denominator: precision divides by the column total 120120, recall by the row total 100100.

Ratios built from the four

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 TP+TNall\dfrac{TP + TN}{\text{all}} 80+8601000\dfrac{80 + 860}{1000} 0.94000.9400
error rate FP+FNall\dfrac{FP + FN}{\text{all}} 40+201000\dfrac{40 + 20}{1000} 0.06000.0600
recall, sensitivity, TPR TPTP+FN\dfrac{TP}{TP + FN} 80100\dfrac{80}{100} 0.80000.8000
miss rate, FNR FNTP+FN\dfrac{FN}{TP + FN} 20100\dfrac{20}{100} 0.20000.2000
specificity, TNR TNTN+FP\dfrac{TN}{TN + FP} 860900\dfrac{860}{900} 0.95560.9556
false positive rate, FPR FPTN+FP\dfrac{FP}{TN + FP} 40900\dfrac{40}{900} 0.04440.0444
precision, PPV TPTP+FP\dfrac{TP}{TP + FP} 80120\dfrac{80}{120} 0.66670.6667
negative predictive value TNTN+FN\dfrac{TN}{TN + FN} 860880\dfrac{860}{880} 0.97730.9773

They come in pairs that share a denominator. Recall and the miss rate both divide by the true spam, so they add to 11, 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, 120120 flagged and 880880 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, 97.797.7 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.

The filter that flags nothing

Return to accuracy, and try a filter that lets everything through. It has TP=0TP = 0, FP=0FP = 0, FN=100FN = 100 and TN=900TN = 900.

filter accuracy recall specificity precision
flags 120120 (above) 0.94000.9400 0.80000.8000 0.95560.9556 0.66670.6667
flags nothing 0.90000.9000 0.00000.0000 1.00001.0000 0/00/0, reported as 00

Ninety per cent accuracy, from a filter that has never caught a single spam message. Accuracy rewards the 900900 true negatives, and recall refuses to, so the two numbers tell opposite stories about the same filter. Its precision is 0/00/0 because it made no positive claims, and libraries report that as 00 and warn, the right response to a model that has said nothing.

One model, three thresholds

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 TPTP FPFP FNFN TNTN 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 11 while precision collapses, and predict it only when certain and precision rises while recall falls.

The same filter on a rarer class

Recall and the false positive rate describe the filter, 0.80000.8000 and 0.04440.0444, 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 TPTP FPFP precision
50%50\% 900 900 720 40 0.9474
10%10\% 100 900 80 40 0.6667
1%1\% 100 9900 80 440 0.1538

The filter is the same in every row. Precision falls from 0.94740.9474 to 0.15380.1538 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.

F1F_1 and its relatives

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:

F1=2PRP+R=2(0.6667)(0.8000)0.6667+0.8000=0.7273.(15.1)\begin{equation} F_1 \;=\; \frac{2PR}{P + R} \;=\; \frac{2\,(0.6667)(0.8000)}{0.6667 + 0.8000} \;=\; 0.7273 . \label{eq:f1} \quad\text{(15.1)} \end{equation}

The harmonic mean is the point, because it is high only when both are high. An arithmetic mean would let a precision of 1.01.0 hide a recall of 0.10.1, giving 0.550.55, while the harmonic mean gives 0.180.18 and refuses to be flattered.

When one error is dearer than the other, FβF_\beta weights recall β\beta times as much as precision, with Fβ=(1+β2)PR/(β2P+R)F_\beta = (1+\beta^2)PR \,/\, (\beta^2 P + R). For the filter above F2=5(0.6667)(0.8000)/(4(0.6667)+0.8000)=0.7692F_2 = 5(0.6667)(0.8000)/(4(0.6667) + 0.8000) = 0.7692, which sits closer to the recall of 0.800.80, as a score that cares about missed spam should.

Two summaries use all four cells, which F1F_1 never does. Balanced accuracy is the mean of recall and specificity, (0.8000+0.9556)/2=0.8778(0.8000 + 0.9556)/2 = 0.8778, 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:

MCC=TP⋅TN−FP⋅FN(TP+FP)(TP+FN)(TN+FP)(TN+FN)=80⋅860−40⋅20120⋅100⋅900⋅880=0.6975.\text{MCC} \;=\; \frac{TP \cdot TN - FP \cdot FN} {\sqrt{(TP{+}FP)(TP{+}FN)(TN{+}FP)(TN{+}FN)}} \;=\; \frac{80 \cdot 860 - 40 \cdot 20}{\sqrt{120 \cdot 100 \cdot 900 \cdot 880}} \;=\; 0.6975 .

It is 11 for a perfect classifier, 00 for one no better than chance and −1-1 for one that is perfectly wrong, and it stays informative on imbalanced data where accuracy does not.

A 2 by 2 spam filter table with accuracy, precision, recall and F1
Accuracy can look excellent while a classifier is useless. Precision and recall, built from the four outcomes, expose what it misses when one class is rare.

Why accuracy lies

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

One class against the rest

With more than two classes there is no single positive, so ask the binary question once per class. Treat class cc as the positive class and every other class as the negative one, and the four counts of Section 15.3 follow. TPcTP_c is documents predicted cc and truly cc, FPcFP_c is predicted cc but truly something else, FNcFN_c is truly cc but predicted something else, and TNcTN_c 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:

Pc=TPcTPc+FPc,Rc=TPcTPc+FNc,F1c=2PcRcPc+Rc.(15.2)\begin{equation} P_c = \frac{TP_c}{TP_c + FP_c}, \qquad R_c = \frac{TP_c}{TP_c + FN_c}, \qquad F1_c = \frac{2\,P_c R_c}{P_c + R_c}. \label{eq:prf} \quad\text{(15.2)} \end{equation}

None of the three uses TNcTN_c, 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.

Macro and micro

To get one number for the whole task, average the per-class scores across the label set.

macro-F1=1|C|∑c∈CF1c.(15.3)\begin{equation} \text{macro-}F_1 \;=\; \frac{1}{|C|} \sum_{c \in C} F1_c . \label{eq:macrof1} \quad\text{(15.3)} \end{equation}

Every class contributes one term whatever its size, so a classifier that ignores one class entirely scores F1c=0F1_c = 0 for it and macro-F1F_1 drops by a full 1/|C|1/|C|. 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 F1F_1 from the totals, so frequent classes dominate. One fact about it saves confusion later: on a single-label task micro-F1F_1 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-F1F_1 therefore tells you nothing accuracy did not, so report macro-F1F_1 or report the per-class table.

Which score picks the right classifier

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-F1F_1 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. F1F_1 news F1F_1 fict. F1F_1 gov. F1F_1 learn. wtd F1F_1 macro-F1F_1
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 F1F_1 of the news class and the weighted F1F_1, 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-F1F_1 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 F1F_1 carries a second bias, because it depends on which class is called positive. The same classifier C scores 0.96770.9677 with news as the positive class and 0.00000.0000 with learned, so a lone F1F_1 is meaningless until it says which class it belongs to. Macro-F1F_1 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 F1F_1 for that class by a large step, and the macro average by a quarter of it. Give the counts beside a macro-F1F_1 so that the reader can see how much weight each term can bear.

Reading a confusion matrix

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 ∖\backslash 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 1212 and 1313, 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, TPTP is the diagonal cell 99, FPFP is the rest of its column, 0+3+1=40 + 3 + 1 = 4, and FNFN is the rest of its row, 0+2+1=30 + 2 + 1 = 3. Check them against the margins: TP+FN=12TP + FN = 12 is the row total and TP+FP=13TP + FP = 13 is the column total. The true negatives are everything left over, so with 4848 documents in the test set TN=48−9−4−3=32TN = 48 - 9 - 4 - 3 = 32.

class TPTP FPFP FNFN TNTN PP RR F1F_1 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-F1F_1 0.7483

Each row of counts adds to 4848, the quickest check that no cell was misread. Specificity is TNc/(TNc+FPc)TN_c / (TN_c + FP_c), 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 0.750.75 and stops. The per-class table says which genre is failing and how. Look at government, whose recall is 0.58330.5833 because five of its twelve documents went elsewhere, and whose precision is 0.70000.7000 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.

Two diagnoses the matrix hands you

Both diagnoses are computed and not guessed. The hardest class is the one with the lowest per-class F1F_1, which here is government at 0.63640.6364 against 0.72000.7200, 0.72000.7200 and 0.91670.9167. 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 i→ji \to j j→ij \to i 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.

The loop, not the number

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

When the threshold is yours to choose

Everything so far scores a single decision. Precision, recall and F1F_1 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
0.950.95 11 11 00 1.0001.000 0.3330.333
0.900.90 11 22 00 1.0001.000 0.6670.667
0.800.80 00 22 11 0.6670.667 0.6670.667
0.700.70 11 33 11 0.7500.750 1.0001.000
0.600.60 00 33 22 0.6000.600 1.0001.000
0.500.50 00 33 33 0.5000.500 1.0001.000

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 FN=3−TPFN = 3 - TP and TN=7−FPTN = 7 - FP, and the two rates of Section 15.3 follow. The table adds them for all ten cuts, including the four below 0.500.50 that the previous one leaves out.

score TPTP FPFP FNFN TNTN TPR FPR
0.950.95 1 0 2 7 0.3330.333 0.0000.000
0.900.90 2 0 1 7 0.6670.667 0.0000.000
0.800.80 2 1 1 6 0.6670.667 0.1430.143
0.700.70 3 1 0 6 1.0001.000 0.1430.143
0.600.60 3 2 0 5 1.0001.000 0.2860.286
0.500.50 3 3 0 4 1.0001.000 0.4290.429
0.400.40 3 4 0 3 1.0001.000 0.5710.571
0.300.30 3 5 0 2 1.0001.000 0.7140.714
0.200.20 3 6 0 1 1.0001.000 0.8570.857
0.100.10 3 7 0 0 1.0001.000 1.0001.000

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 (1,1)(1,1), where everything is, and the ten rows above are its points.

A classifier whose scores carry no information stays on the diagonal TPR=FPR\text{TPR} = \text{FPR}, because flagging a fraction of the documents catches the same fraction of each class. A perfect one passes through the corner (0,1)(0,1), catching every positive before it flags a single negative. The area under the curve, written AUC, is therefore 0.50.5 for guessing and 11 for perfect, and for these ten points it is 0.95240.9524 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 0.950.95 beats all seven, the one scored 0.900.90 beats all seven, and the one scored 0.700.70 beats six, because the negative scored 0.800.80 sits above it. This is 2020 wins in 2121 pairs, and 20/21=0.952420/21 = 0.9524, 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 1.0001.000, 1.0001.000 and 0.7500.750, so PR-AUC is 0.91670.9167, and on a balanced problem the two areas usually agree like this.

Figure 15.2. The ten documents of this section, one point per threshold. Left, the ROC curve, with the dashed diagonal for a classifier that guesses. Right, the precision-recall curve for the same ten thresholds.

Why the two disagree, and which to believe

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 0.94900.9490 still excellent
PR-AUC 0.26670.2667 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 2/10=0.202/10 = 0.20. 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.

Scores that are not probabilities

There is a last question that none of these metrics asks. A score of 0.90.9 ought to mean the model is right about nine times in ten. Nothing in cross-entropy training guarantees that, and nothing in F1F_1, 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 nn correct observed gap
0.60.6 to 0.70.7 0.650.65 4040 2626 0.6500.650 +0.000+0.000
0.70.7 to 0.90.9 0.800.80 3535 1717 0.4860.486 +0.314+0.314
0.90.9 to 1.01.0 0.950.95 2525 1010 0.4000.400 +0.550+0.550

Weighting those gaps by bin size gives an expected calibration error of 0.2470.247. The least confident bin is close to honest and the most confident is the worst, promising 0.950.95 and delivering 0.400.40. 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.

A recurrent classifier

This section is for understanding an architecture, not for building the baseline classifier. A training set of 112112 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:

ht=cell(xt,ht−1),r=pool(h1,…,hT),ŷ=softmax⁡(Wcr+bc).(15.4)\begin{equation} h_t = \text{cell}(x_t, h_{t-1}), \qquad r = \text{pool}(h_1, \dots, h_T), \qquad \hat{y} = \operatorname{softmax}(W_c\, r + b_c). \label{eq:rnnclassifier} \quad\text{(15.4)} \end{equation}

The cell is Equation (12.14), or the LSTM or the GRU of Chapter 13. The vector rr is whatever the head is shown of the sequence, and WcW_c 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, E=−∑kyklog⁡ŷkE = -\sum_k y_k \log\hat{y}_k.

One sentence, worked

Take the sentence the dog ran and the weights of the unrolling example in Chapter 12, whose three states h1h_1, h2h_2 and h3h_3 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:

Wc=(0.9−0.4−0.50.7),bc=(0,0).W_c = \begin{pmatrix} 0.9 & -0.4 \\ -0.5 & 0.7 \end{pmatrix}, \qquad b_c = (0, 0).

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 Wch3=(−0.3764,+0.2812)W_c h_3 = (-0.3764, +0.2812), which the softmax turns into probabilities.

rr value scores PP(neg), PP(pos) loss
last state (−0.3511,+0.1510)(-0.3511, +0.1510) (−0.3764,+0.2812)(-0.3764, +0.2812) (0.3413,0.6587)(0.3413, 0.6587) 0.4174
mean of states (+0.0193,+0.1176)(+0.0193, +0.1176) (−0.0297,+0.0727)(-0.0297, +0.0727) (0.4744,0.5256)(0.4744, 0.5256) 0.6433
max of states (+0.3885,+0.2518)(+0.3885, +0.2518) (+0.2489,−0.0180)(+0.2489, -0.0180) (0.5663,0.4337)(0.5663, 0.4337) 0.8355

The loss is −log-\log of the probability given to the true class, so −log⁡0.6587=0.4174-\log 0.6587 = 0.4174 for the first row. The three rows differ only in the choice of rr, which is the next question.

Which vector reaches the head

The last state is the usual choice, because hTh_T 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, r=[h→T;h⃖1]r = [\overrightarrow{h}_T \,;\, \overleftarrow{h}_1]. The head then has 2H2H inputs, so WcW_c holds 2HC2HC weights for CC classes where the one directional head held HCHC, and every word has seen both its left and its right context before the decision is made.

One loss, and where its error goes

Backpropagation through time starts from one loss now, and the choice of rr decides where its error enters the unrolled network. Write δout=ŷ−y\delta_{\text{out}} = \hat{y} - y for the error at the scores, as in Equation (12.2). With the last state, the head sends Wc⊤δoutW_c^{\top}\delta_{\text{out}} to step TT and nowhere else. Equation (12.7) therefore loses its first term at every earlier step, and each earlier error is carried back alone,

δhT=(Wc⊤δout)⊙(1−hT2),δhk=(U⊤δhk+1)⊙(1−hk2)(k<T).\delta_h^{T} = \big(W_c^{\top}\delta_{\text{out}}\big) \odot (1 - h_T^{2}), \qquad \delta_h^{k} = \big(U^{\top}\delta_h^{k+1}\big) \odot (1 - h_k^{2}) \quad (k < T).

Mean pooling restores the first term at every step, scaled by 1/T1/T, because each state contributes a 1/T1/T share of rr:

δhk=[1TWc⊤δout+U⊤δhk+1]⊙(1−hk2).\delta_h^{k} = \Big[\tfrac{1}{T} W_c^{\top}\delta_{\text{out}} + U^{\top}\delta_h^{k+1}\Big] \odot (1 - h_k^{2}).

On the example, the size ‖δhk‖\lVert\delta_h^{k}\rVert 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 0.300.30 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.

Swap the cell

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 bf=1b_f = 1 for the LSTM, and give each final state to the same head.

cell h3h_3 PP(neg), PP(pos) loss
RNN (−0.3511,+0.1510)(-0.3511, +0.1510) (0.3413,0.6587)(0.3413, 0.6587) 0.4174
LSTM (+0.0874,−0.0394)(+0.0874, -0.0394) (0.5413,0.4587)(0.5413, 0.4587) 0.7794
GRU (+0.1979,−0.1859)(+0.1979, -0.1859) (0.6181,0.3819)(0.6181, 0.3819) 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 nn-token document and the error at the first token has been multiplied n−1n - 1 times.

tokens plain RNN, factor 0.90.9 LSTM, forget gate 0.990.99
10 3.87×10−13.87 \times 10^{-1} 9.14×10−19.14 \times 10^{-1}
50 5.73×10−35.73 \times 10^{-3} 6.11×10−16.11 \times 10^{-1}
200 7.84×10−107.84 \times 10^{-10} 1.35×10−11.35 \times 10^{-1}

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.

Then measure it like any other classifier

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-F1F_1 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.py produces every table in this chapter. --outcomes counts the four cells of the spam filter and prints every ratio built from them, --trap builds the ninety-per-cent-accuracy model that has learned nothing, --matrix scores the genre matrix class by class, --read derives the hardest class and the most confused pair, --averages shows micro-F1F_1 landing on accuracy, --threshold sweeps the ranking for ROC-AUC and PR-AUC, --calibration checks whether the scores mean anything, --rank scores three classifiers on one skewed test set and shows which score crowns which, and --recurrent sends one sentence through an RNN, an LSTM and a GRU into a classification head and follows the error back.

Run it

What Part III leaves behind

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

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

Further reading.

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.

Practice problems

15.1 Fill the table. A classifier is run on 200200 documents and produces TP=45TP = 45, FP=5FP = 5, FN=15FN = 15 and TN=135TN = 135. Check that the cells add to 200200, then compute accuracy, precision, recall, specificity, the false positive rate and F1F_1, 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 FPFP and FNFN 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 22 per cent positive documents out of 50005000. Compute TPTP, FPFP 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 100100 documents where a majority-class classifier scores above 0.850.85 accuracy and below 0.300.30 macro-F1F_1. 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 TPTP, FPFP and FNFN for government and confirm P=0.7000P = 0.7000, R=0.5833R = 0.5833 and F1=0.6364F_1 = 0.6364. 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 P=0.95P = 0.95 and R=0.05R = 0.05. 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 FPFP and pooled FNFN are equal, and therefore that micro-F1F_1 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-F1F_1. 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-F1F_1 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 0.94900.9490 and PR-AUC 0.26670.2667 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 F1F_1.

15.13 A model that ranks perfectly and lies. Construct scores for ten documents where the ordering is flawless, so ROC-AUC is exactly 1.01.0, and the expected calibration error is above 0.30.3. 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-F1F_1 of 0.23680.2368 included. Now read the row it adds, the weighted average, which reports 0.85260.8526 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 10001000 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 WcrW_c r and the softmax for each, and confirm the loss 0.64330.6433 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 H=500H = 500 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 UU.

15.18 How far back. A model classifies only the last state. For a per-step factor of 0.950.95, find the document length at which the error reaching the first token falls below 10−310^{-3} of its starting size. Repeat for 0.990.99, and say what the difference means for the choice between a plain network and a gated one.

Code for this chapter

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 it

From Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.