6  Evaluating AI Systems

Week 6, 7 October

Last week, we classified NATO tweets with a language model but had no human labels to check its answers. We have now applied it to the 181 tweets in Week 4’s test set, where we do have hand-coded labels. The language model received instructions but no labeled examples.

It agrees with the human coder on 95 percent of those tweets. The Naive Bayes model, trained on 724 hand-coded tweets, reaches roughly 90 percent. On those figures alone, prompting a language model looks like an easier and better option. What else do we need to know before drawing that conclusion?

Both scores are accurate for this comparison. This session examines what they measure and which conclusions they support.

We focus on two issues. First, agreement with a coder and codebook is not automatically correspondence with the concept we want to measure. Second, labels that are 95 percent correct need not produce estimates that are 95 percent correct. Systematic labeling errors can bias the analysis that uses them.

6.1 Part I. What accuracy hides

6.1.1 The classifier, rebuilt

Part I reuses the Week 4 pipeline in a compressed form. Refer back to that handout for explanations of its individual steps.

install.packages(c("tm", "SnowballC", "caret", "e1071", "ggplot2", "pROC"))
library(tm)
library(SnowballC)
library(caret)
library(ggplot2)

url4 <- paste0("https://raw.githubusercontent.com/babakrezaee/",
               "AppliedAI-PoliSci/refs/heads/main/data/",
               "trump_immigration_2019.csv")

tweets <- read.csv(url4, stringsAsFactors = FALSE,
                   colClasses = c(id = "character"))
tweets$label <- factor(tweets$label, levels = c("other", "immigration"))

corpus <- VCorpus(VectorSource(tweets$text))

replace_with_space <- content_transformer(function(x, pattern) {
  gsub(pattern, " ", x)
})

clean <- tm_map(corpus, content_transformer(tolower))
clean <- tm_map(clean, replace_with_space, "http[s]?://\\S*")
clean <- tm_map(clean, replace_with_space, "@\\S+")
clean <- tm_map(clean, replace_with_space, "[^a-z ]")
clean <- tm_map(clean, removeWords, stopwords("english"))
clean <- tm_map(clean, stemDocument)
clean <- tm_map(clean, stripWhitespace)

dtm <- DocumentTermMatrix(clean)

train_id <- 1:floor(0.8 * nrow(tweets))

freq_words <- findFreqTerms(dtm[train_id, ], 5)

counts_train <- as.matrix(dtm[train_id, freq_words])
counts_test  <- as.matrix(dtm[-train_id, freq_words])

y_train <- tweets$label[train_id]
y_test  <- tweets$label[-train_id]

total_immigration <- colSums(counts_train[y_train == "immigration", ])
total_other       <- colSums(counts_train[y_train == "other", ])

p_immigration <- (total_immigration + 1) / sum(total_immigration + 1)
p_other       <- (total_other + 1) / sum(total_other + 1)

# The two scores, exactly as in Week 4
score_immigration <- as.vector(counts_test %*% log(p_immigration)) +
  log(mean(y_train == "immigration"))

score_other <- as.vector(counts_test %*% log(p_other)) +
  log(mean(y_train == "other"))

# Week 4 classified by asking which score was larger. The same comparison,
# written as a probability that the tweet is about immigration:
prob <- 1 / (1 + exp(-(score_immigration - score_other)))

nb_pred <- factor(ifelse(prob > 0.5, "immigration", "other"),
                  levels = c("other", "immigration"))

The following line adds the quantity we need for this part.

Week 4 compared score_immigration with score_other. These are sums of logarithms, and neither score is directly interpretable on its own. The new line converts their difference into \(P(\text{immigration} \mid \text{tweet})\), the classifier’s assigned probability. The logistic transformation preserves the ranking of tweets.

The default threshold is 0.5. Above it, the model predicts immigration. This is equivalent to choosing the class with the higher score. We will now examine what changes when we move that threshold.

6.1.2 Precision and recall, at last

Precision and recall describe different aspects of the same confusion matrix. Both depend on which class we designate as positive.

cm <- confusionMatrix(nb_pred, y_test, positive = "immigration")

cm$table
             Reference
Prediction    other immigration
  other          82           5
  immigration    12          82
round(cm$byClass[c("Precision", "Recall", "F1")], 3)
Precision    Recall        F1 
    0.872     0.943     0.906 

Using TP, FP, FN, and TN for its cells, with immigration as the positive class:

\[ \text{Recall} = \text{Sensitivity} = \frac{TP}{TP + FN} \qquad \text{Specificity} = \frac{TN}{TN + FP} \]

\[ \text{Precision} = \frac{TP}{TP + FP} \qquad F_1 = 2 \cdot \frac{\text{Recall} \times \text{Precision}}{\text{Recall} + \text{Precision}} \]

The denominators explain the difference. Recall, also called sensitivity or the true positive rate, divides by all genuine immigration tweets: what share did the model find? Precision, or positive predictive value, divides by all tweets the model flagged: what share were genuinely about immigration? A classifier can find most relevant cases while also producing many false alarms.

Specificity measures the share of genuine negatives correctly identified. It matters when avoiding errors on that class is important. \(F_1\) combines precision and recall through their harmonic mean, so a low value on either pulls the combined score down.

The mode argument tells caret which set of measures to report:

confusionMatrix(nb_pred, y_test, positive = "immigration",
                mode = "prec_recall")$byClass[c("Precision", "Recall", "F1")]
Precision    Recall        F1 
0.8723404 0.9425287 0.9060773 
confusionMatrix(nb_pred, y_test, positive = "immigration",
                mode = "sens_spec")$byClass[c("Sensitivity", "Specificity")]
Sensitivity Specificity 
  0.9425287   0.8723404 

Precision and recall also depend on the threshold used to turn scores into labels. We can see that by moving the cut point.

6.1.3 The threshold is a choice, not a finding

The 0.5 threshold is a convention. Changing it gives different classifications from the same fitted model. The appropriate cut point depends on the task, rather than being determined by the data alone.

cuts <- seq(0.1, 0.9, by = 0.1)

sweep_out <- data.frame()

for (cc in cuts) {
  pred_c <- factor(ifelse(prob > cc, "immigration", "other"),
                   levels = c("other", "immigration"))
  tp <- sum(pred_c == "immigration" & y_test == "immigration")
  fp <- sum(pred_c == "immigration" & y_test == "other")
  fn <- sum(pred_c == "other" & y_test == "immigration")
  tn <- sum(pred_c == "other" & y_test == "other")
  sweep_out <- rbind(sweep_out,
                     data.frame(threshold = cc,
                                flagged   = tp + fp,
                                precision = tp / (tp + fp),
                                recall    = tp / (tp + fn),
                                accuracy  = (tp + tn) / length(y_test)))
}

sweep_out$default <- sweep_out$threshold == 0.5

round(sweep_out[, 1:5], 3)
  threshold flagged precision recall accuracy
1       0.1     106     0.802  0.977    0.873
2       0.2     100     0.840  0.966    0.895
3       0.3      99     0.848  0.966    0.901
4       0.4      96     0.865  0.954    0.906
5       0.5      94     0.872  0.943    0.906
6       0.6      91     0.901  0.943    0.923
7       0.7      90     0.900  0.931    0.917
8       0.8      86     0.907  0.897    0.906
9       0.9      81     0.914  0.851    0.890

Each row summarizes a confusion matrix at a different threshold. At 0.1, the classifier finds nearly all immigration tweets but also flags many others. At 0.9, its flagged tweets are mostly correct, but it misses more genuine cases. The marked 0.5 row is the default, not necessarily the best choice for our purpose.

ggplot(sweep_out, aes(recall, precision)) +
  geom_path(colour = "steelblue", linewidth = 1) +
  geom_point(colour = "grey25", size = 1.9) +
  geom_text(aes(label = threshold), size = 3.1, colour = "grey25",
            hjust = -0.35, vjust = -0.5) +
  geom_point(data = sweep_out[sweep_out$default, ],
             colour = "maroon", size = 3.4) +
  geom_text(data = sweep_out[sweep_out$default, ],
            label = "default, p = 0.5", colour = "maroon",
            size = 3.3, hjust = 1.15, vjust = 1.8) +
  expand_limits(x = max(sweep_out$recall) + 0.04) +
  labs(x = "recall", y = "precision",
       title = "Every point is the same classifier, cut in a different place",
       subtitle = "Labels are the probability threshold for flagging a tweet")

The plot shows this trade-off. Each label marks a threshold and its precision and recall. The maroon point is the default; nearby points show what happens if we change it.

6.1.4 Why there is a trade-off at all

To understand the trade-off, look at how the two denominators behave as we lower the threshold.

One denominator stays fixed; the other changes with the classifier’s decisions.

Recall divides by the 87 genuine immigration tweets in the test set. Lowering the threshold catches more of them, so recall rises. Precision divides by the number flagged, which grows as we lower the threshold. The additional tweets have weaker scores and include more false positives, so precision falls in this example.

As a practical guide, precision emphasizes confidence in a flag; recall emphasizes finding the relevant cases.

Think about a spam filter. Letting a spam message into your inbox is usually a nuisance, while hiding a genuine job offer or exam result in junk may be costly. That makes precision important: when the filter labels a message as spam, we want it to be right, even if some spam gets through.

For a screening test for a serious disease, missing a case may be more costly than arranging an additional test after a false alarm. That favors recall, with further checks used to investigate flagged cases. The mathematics is the same, but the costs point toward a different threshold.

For our classifier, the appropriate balance depends on how we plan to use the labels. The default 0.5 does not settle that decision.

6.1.5 Try it yourself

Move the threshold and watch the four cells change. The display uses the same 181 test tweets as the table above. It follows caret’s layout: predictions down the side and reference labels across the top.

At the far left, the classifier flags nearly everything and misses very few cases, but produces many false alarms. At the far right, it flags fewer tweets and misses more genuine immigration tweets. The dot stays on the curve because every point represents a threshold applied to the same scores.

Choose the threshold with the purpose in mind. When estimating a year’s immigration share, false positives inflate the count and precision matters. When retrieving documents for someone to read, recall may matter more because false positives mainly add reading time. Reporting accuracy without explaining the use leaves this choice unclear.

6.1.6 ROC and AUC, the same sweep in the standard form

A receiver operating characteristic, or ROC curve, plots sensitivity against one minus specificity. These are the true positive and false positive rates, traced as the threshold moves from one to zero.

library(pROC)

roc_nb <- roc(response = y_test, predictor = prob,
              levels = c("other", "immigration"), direction = "<")

auc(roc_nb)
Area under the curve: 0.9711
plot(roc_nb, col = "steelblue", lwd = 2,
     main = paste("Naive Bayes, AUC =", round(auc(roc_nb), 3)))

The diagonal represents a classifier with no useful ranking information. A curve nearer the top left performs better. AUC, the area under the ROC curve, summarizes this ranking performance.

Imagine drawing one immigration tweet and one other tweet at random. AUC is the probability that the classifier gives the immigration tweet a higher score. It measures ranking, not the proportion of labels correct, and is independent of the chosen threshold.

That makes AUC useful for comparing rankings, but insufficient for assessing a deployed threshold. A model can have high AUC and still perform poorly at the cut point we use. Report precision and recall at that cut point as well.

Note

The precision-recall curve above is another way to display threshold performance. With balanced classes, it often gives a similar impression to ROC. For rare positive outcomes, ROC can look favorable despite many false alarms because there are so many true negatives. Prefer the precision-recall curve for tasks such as Week 3’s war-onset prediction.

Note

Calibration is a separate property: do cases assigned seventy percent probability have the outcome about seventy percent of the time? It is important for early warning. We leave it for next week’s discussion of crisis management.

We now have precision, recall, and a way to examine thresholds. Working with our own classifier let us inspect how these quantities arise.

Next, we apply evaluation to a language model whose internal workings are unavailable to us.

6.2 Part II. Validating a language model

The NATO exercise could not establish accuracy because it lacked human labels. We now use Week 4’s hand-labeled tweets to evaluate the language model.

To keep the comparison clear, the classifier means our Naive Bayes model, trained on 724 tweets. The model, or language model, means the pretrained system instructed through a prompt without fitting to our data.

url6 <- paste0("https://raw.githubusercontent.com/babakrezaee/",
               "AppliedAI-PoliSci/refs/heads/main/data/",
               "llm_labels_w6.csv")

llm <- read.csv(url6, stringsAsFactors = FALSE,
                colClasses = c(id = "character"))

str(llm)
'data.frame':   181 obs. of  7 variables:
 $ id        : chr  "1124672389416144905" "1120715879640174592" "1106205023548133376" "1173803449202249728" ...
 $ date      : chr  "2019-05-04 21:49" "2019-04-23 23:47" "2019-03-14 22:46" "2019-09-17 11:38" ...
 $ text      : chr  "Very good call yesterday with President Putin of Russia. Tremendous potential for a good/great relationship wit"| __truncated__ "Great interview by Jared. Nice to have extraordinarily smart people serving our Country! https://t.co/d6Tgrn4Tzn" "A vote for today’s resolution by Republican Senators is a vote for Nancy Pelosi, Crime, and the Open Border Democrats!" "Beautiful evening in New Mexico with Great American Patriots! https://t.co/S8eDG3dAq0" ...
 $ human     : chr  "other" "other" "immigration" "other" ...
 $ llm_main  : chr  "other" "other" "immigration" "other" ...
 $ llm_reword: chr  "other" "other" "immigration" "other" ...
 $ llm_model2: chr  "other" "other" "immigration" "other" ...

6.2.1 What is in the file, and where it came from

The file contains four label columns for each tweet:

Column What produced it
human The Week 4 hand coding, one person working from a written codebook
llm_main A language model, given the prompt below, called prompt A
llm_reword The same model on the same tweets, given a differently worded prompt saying the same thing, called prompt B
llm_model2 A different model from the same provider, given prompt A again

Comparing llm_main with llm_reword changes the prompt while holding the model fixed. Comparing llm_main with llm_model2 changes the model while holding the prompt fixed. Exact model names and run dates are in data/llm_labels_w6_README.md; keep these details with any API-based measurement.

Both models come from the same provider and family. They differ in scale, including parameters and computation, though providers rarely disclose exact figures. Price and tier names give some practical indication; llm_model2 uses the more expensive model. Models from the same family do not provide fully independent judgments, which matters when interpreting agreement.

Both prompts are reasonable attempts to describe the same task.

Prompt A, which produced llm_main and llm_model2:

You are coding tweets for a political science project.

Decide whether immigration is a main subject of the tweet. This includes the southern border, the border wall, illegal immigration, deportation, ICE, sanctuary cities, asylum, visas, and DACA.

If immigration is mentioned only in passing within a longer list of topics, code it as other.

Prompt B, which produced llm_reword:

Classify each tweet by topic.

Answer immigration if the tweet concerns immigration or border policy in any substantial way. Answer other for everything else.

Compare the instructions. Prompt A lists examples and explicitly addresses passing mentions. Prompt B leaves the meaning of “substantial” to the model. Neither is deliberately poor, but they give different amounts of guidance. Keep this distinction in mind when reading their disagreement rate.

The generation script is R/w6_generate_llm_labels.R. The README records provenance and limits on reproduction. Read both before the session so you know how these labels were produced.

6.2.2 Three label sources, one set of tweets

human <- factor(llm$human, levels = c("other", "immigration"))
llm_main <- factor(llm$llm_main, levels = c("other", "immigration"))

confusionMatrix(nb_pred, human, positive = "immigration")$table
             Reference
Prediction    other immigration
  other          82           5
  immigration    12          82
confusionMatrix(llm_main, human, positive = "immigration")$table
             Reference
Prediction    other immigration
  other          87           2
  immigration     7          85
round(rbind(
  naive_bayes = confusionMatrix(nb_pred, human,
                                positive = "immigration")$byClass[c("Precision", "Recall")],
  llm         = confusionMatrix(llm_main, human,
                                positive = "immigration")$byClass[c("Precision", "Recall")]
), 3)
            Precision Recall
naive_bayes     0.872  0.943
llm             0.924  0.977

The language model scores higher than our classifier without having received our labeled training examples. That result is worth examining and is consistent with the comparisons reported in the literature.

Recall is higher than precision: the model misses few immigration tweets but flags some labeled other. Read those cases to understand the difference.

wrong <- llm[llm$human != llm$llm_main, c("text", "human", "llm_main")]

nrow(wrong)
[1] 9
false_alarms <- wrong[wrong$human == "other", ]

for (i in 1:nrow(false_alarms)) {
  cat("-", substr(false_alarms$text[i], 1, 190), "\n\n")
}
- ....Kevin is strong on Securing the Border, #USMCA, protecting our #2A, and Loves our Vets and Military. Kevin is a true friend, and has my Complete and Total Endorsement! 

- MISSISSIPPI! There is a VERY important election for Governor on November 5th. I need you to get out and VOTE for our Great Republican nominee, @TateReeves. Tate is Strong on Crime, tough on  

- Senator Cindy Hyde-Smith is doing a GREAT JOB for the people of Mississippi and fully supports our #MAGA Agenda. Cindy is tough on Crime, Strong on the Border and Illegal Immigration.... 

- I will be signing our 738 Billion Dollar Defense Spending Bill today. It will include 12 weeks  Paid Parental Leave, gives our troops a raise, importantly creates the SPACE FORCE, SOUTHERN B 

- ..that this Administration has done. They don’t talk about the great economy, the big tax and regulation cuts, the rebuilding of the Military, “Choice” at our VA, our Vets, Judges and Suprem 

- Looking forward to being in the North Carolina tomorrow night. We’re having a BIG RALLY for a great guy, Dan Bishop. Strong on Crime, Borders, your Military and our Vets, we need Dan Bishop  

- I will be interviewed by Jeanine Pirro at 9:00 P.M. on @FoxNews. Watch @JesseBWatters before and @greggutfeld after. All terrific people. I am in the White House waiting for Cryin’ Chuck and 

Six of these seven errors are endorsements or lists of accomplishments. The border appears alongside issues such as crime, the Second Amendment, or veterans. The defense spending tweet lists “SOUTHERN BORDER WALL FUNDING” with parental leave, troop pay, the Space Force, and the smoking age.

The Week 4 codebook classifies passing mentions in lists as other. It also treats endorsement boilerplate that way when the border is one item rather than the main subject. One coder wrote these rules to resolve cases not covered by the original scheme.

The disagreements therefore concern how to apply those conventions, rather than simply whether the model recognizes immigration language. The model notices the mentions but does not consistently reproduce the coder’s distinction. Most errors occur where the codebook itself required a judgment call.

missed <- wrong[wrong$human == "immigration", ]

for (i in 1:nrow(missed)) {
  cat("-", substr(missed$text[i], 1, 190), "\n\n")
}
- So now the Obama appointed judge on the Census case (Are you a Citizen of the United States?) won’t let the Justice Department use the lawyers  that it wants to use. Could this be a first? 

- ....This will supersede USMCA. Likewise I am looking at an economic penalty for the 500 Billion Dollars in illegal DRUGS that are shipped and smuggled through Mexico and across our Southern  

The two missed tweets also involve boundaries of the scheme. One concerns the census citizenship question, which the codebook includes as immigration. The other concerns drugs crossing the southern border, which the scheme includes when tied to immigrants or the border. A reasonable coder could debate both decisions.

The 95 percent figure therefore measures agreement with one coder’s conventions. The remaining five percent largely concerns contestable applications of those conventions, rather than a straightforward failure to understand the subject.

There is another difference between the systems. Our classifier supplies a probability, so we can move a threshold and draw a ROC curve. The language model supplies only a label, giving one point rather than a curve. Its precision-recall balance depends on the prompt and model. We can rewrite the prompt or request probabilities, but would need to validate those probabilities too. Our classifier performs worse here while giving us more direct control of its threshold.

6.2.3 Four ways to shake a measurement

So far, we have one run of one model under one prompt. Before relying on its 95 percent agreement, check how the result responds to changes that could occur in a research project.

We use four checks. First, verify factual claims against sources. Then vary the prompt, vary the model, and finally repeat an identical call. These examine different sources of error and instability.

6.2.4 Check one, the existence check: does the claim survive looking up?

When a model makes a factual claim, ask for a source and verify both that it exists and that it supports the claim.

The label file cannot test this kind of factual accuracy, so we will do it in the workshop. Fearon and Laitin’s 2003 article is a useful starting point because it was assigned in Week 3:

Ask the model what Fearon and Laitin found about the relationship between ethnic diversity and civil war onset, and then ask it for the page on which they report it. Open the article and look.

Repeat this with an article you know well, then one you have only heard of. The latter is especially useful because unfamiliarity makes a plausible answer harder to challenge.

Watch for invented references and for real sources misrepresented by the answer. A plausible author, journal, year, or page number is not enough. Correct and fabricated citations can be written with the same confidence.

Our 181 human labels gave us a way to check classifications. Factual claims need their own check. Fluency is visible in the response, but accuracy usually requires looking beyond it.

6.2.5 Check two, prompt stability: does the answer survive a reworded prompt?

The remaining checks concern measurement stability. Start with prompt wording, which researchers often adjust without treating it as a change to the instrument.

llm_reword <- factor(llm$llm_reword, levels = c("other", "immigration"))

table(as_written = llm_main, reworded = llm_reword)
             reworded
as_written    other immigration
  other          82           7
  immigration     0          92
round(mean(llm_main == llm_reword), 3)
[1] 0.961

The same model received two defensible prompts. Some tweets nevertheless receive different labels. Look at which tweets change, as well as how many.

moved <- llm[llm$llm_main != llm$llm_reword, ]

for (i in 1:nrow(moved)) {
  cat("-", substr(moved$text[i], 1, 170), "\n\n")
}
- ....energy independence, manufacturing resilience, illegal immigration coming down, the Wall going up, China confronted, the caliphate defeated, NAFTA renegotiated, our m 

- So now the Obama appointed judge on the Census case (Are you a Citizen of the United States?) won’t let the Justice Department use the lawyers  that it wants to use. Coul 

- ....This will supersede USMCA. Likewise I am looking at an economic penalty for the 500 Billion Dollars in illegal DRUGS that are shipped and smuggled through Mexico and  

- All necessary work has been completed to declare Mexican Cartels terrorist organizations. Statutorily we are ready to do so. However, at the request of a man who I like a 

- “Poll shows Dems losing interest in Impeachment inquiry all across the board. These Polls are actually devastating to the Democrats. But the writing was on the wall. He’s 

- It was a very bad week for the Democrats, with the GREAT economic numbers, The Virginia disaster and the State of the Union address. Now, with the terrible offers being m 

- The White House will be hosting a very big and very important Social Media Summit today. Would I have become President without Social Media? Yes (probably)! At its conclu 

The changing cases resemble the earlier errors: a list with “illegal immigration coming down,” the census citizenship question, the drug-smuggling tweet, and a poll quotation mentioning the wall in passing. These are also difficult cases for the codebook.

This pattern helps explain the instability: it occurs where human coding also required judgment. But those cases may be substantively important. A researcher using one prompt would miss that an eighth of the ambiguous cases could receive another label.

The model disagrees with the human coder on about five percent of tweets and with its reworded-prompt run on about four percent. Prompt sensitivity is therefore almost as large as the measured error rate. Report it alongside accuracy rather than assuming the wording makes little difference.

6.2.6 Check three, inter-model reliability: does a second model agree?

Now hold the prompt fixed and change the model. Consider how independent the two models are.

llm_model2 <- factor(llm$llm_model2, levels = c("other", "immigration"))

table(prompt_A_model_1 = llm_main, prompt_A_model_2 = llm_model2)
                prompt_A_model_2
prompt_A_model_1 other immigration
     other          83           6
     immigration     1          91
round(mean(llm_main == llm_model2), 3)
[1] 0.961

The second model comes from the same company and uses similar training methods and text. Shared assumptions about words such as “border” can produce agreement without providing independent confirmation.

We also ran prompt A through a model from a different company. In ellmer, this changes chat_openai() to chat_anthropic(), illustrating the convenience of a common interface.

url_c <- paste0("https://raw.githubusercontent.com/babakrezaee/",
                "AppliedAI-PoliSci/refs/heads/main/data/",
                "llm_claude_w6.csv")

claude <- read.csv(url_c, stringsAsFactors = FALSE,
                   colClasses = c(id = "character"))

llm_claude <- factor(claude$llm_claude, levels = c("other", "immigration"))

round(c(same_company  = mean(llm_main == llm_model2),
        other_company = mean(llm_main == llm_claude)), 3)
 same_company other_company 
        0.961         0.950 

We expected lower agreement across companies. It was lower by only two tweets out of 181, too small a difference here to support that expectation. Keep such results in the report even when they do not show the effect anticipated.

We can also inspect cases where all three models agree.

unanimous <- llm_main == llm_model2 & llm_main == llm_claude

sum(unanimous)
[1] 169
table(all_three_said = llm_main[unanimous], human = human[unanimous])
              human
all_three_said other immigration
   other          81           0
   immigration     3          85

The models agree on 169 of 181 tweets. Of those 169, 166 match the human label. Unanimous agreement still leaves three disagreements with the coder.

Model agreement alone would not identify those cases. Comparing the answers with someone who had read and coded the tweets did.

6.2.7 Check four, intra-model reliability: does the same model agree with itself?

Finally, repeat the same prompt on the same model. This tests whether identical requests give the same labels, without changing either instrument or instruction.

Across two runs on these 181 tweets, the model changed its label on 8 cases. Accuracy against the hand labels moved from 95.0 to 93.9 percent. Even with the same request and model, the score depended on the run.

Five of those eight also changed under prompt rewording. Across rewording, model changes, and repeated calls, 12 of 181 tweets changed at least once. About 93 percent were stable; the rest were sensitive to the request or run. They were largely the borderline cases requiring codebook tie-break rules. The checks repeatedly brought us back to the same ambiguities.

6.2.8 Why that happens, and why we could not switch it off

Week 5 showed probabilities over possible next tokens followed by a selection step. Temperature controls how that selection uses the probabilities.

At zero temperature, selection takes the most likely token. Higher settings allow less likely tokens to be sampled and can produce more varied answers. Researchers have therefore commonly used zero temperature when seeking repeatable measurements and reported the setting with their methods.

That option is unavailable for the model in this exercise.

This is a reasoning model, which generates intermediate steps before the final answer. That process is trained and configured for a particular sampling setup, and the provider restricts changes to the setting. We cannot assume that lowering it would preserve the model’s intended performance.

We requested zero temperature for all 181 tweets, and every call was refused: the API allowed only the default. A request for 0.5 was also refused. Although the R package exposes the parameter, this model does not let us set it.

This limits our control over repeatability. The provider determines which settings are available, and we cannot evaluate all its reasons from outside. We can measure and report variation across runs, as above, but cannot remove it through the usual temperature setting here.

6.2.9 Agreement is not accuracy

We have calculated several agreement rates. They address reliability, which needs to be distinguished from accuracy.

Agreement across prompts, models, providers, or repeated runs tells us how reproducible the measurement is under those conditions. It does not establish that the result is right. Models may agree because they share training material or assumptions, including shared errors. Our three-model comparison illustrates this possibility.

In this exercise, human labels provide the accuracy benchmark. The reliability checks add useful information but do not replace that comparison.

Human labels also need scrutiny. One coder applied one codebook, including four rules developed for difficult cases. Another coder might disagree. State the result precisely: the model agrees 95 percent of the time with one person’s application of a coding scheme to 181 tweets. Lowe and Benoit (Lowe and Benoit 2013) discuss what is required when human judgment serves as the benchmark.

Part III asks whether that coding scheme measures our intended concept and whether the evaluation was properly separated from model development.

6.3 Part III. Why a good score can be the wrong number

6.3.1 What the score is a score of

Construct validity concerns whether an instrument measures the concept it claims to measure, rather than a related concept or something easier to count. This is familiar territory for political scientists.

Our score measures agreement with the codebook. Whether it also measures immigration content depends on the scheme’s definition. Labeling a ten-item list with “Border” seventh as other is contestable. Changing that rule changes the labels and measured accuracy, even though the tweets and model are unchanged.

Consider four questions about our evaluation.

Does the measure cover the concept, or only part of it? We include the census citizenship question but exclude an endorsement saying “strong on the border.” If the research question concerns political displays of toughness on immigration, that exclusion may omit important content.

Does it agree with an established measure of the same thing? The Comparative Agendas Project and Manifesto Project use political-text coding schemes developed over years with multiple coders. We could compare our single-coder scheme with those approaches, but have not done so.

Does the measure behave as the concept should? Immigration’s measured share falls after the first half of 2019, consistent with the shift from the shutdown to impeachment. That is useful supporting evidence. An unexpected pattern would require investigation, regardless of label agreement.

What follows from using it? If this became a monitoring system, politicians might adapt their language to its rules. Our endorsement cases already show how the border can appear without being the main subject. Deployment could affect the behavior the instrument is meant to measure.

An agreement rate alone does not answer these questions. It tells us about consistency with labels, leaving their substantive adequacy to be examined.

6.3.2 When the test was not really a test

An apparently strong score may also reflect information from the test set entering model development.

Think of an exam. If students see the questions during preparation, their scores may be high and the marking perfectly correct, but those scores no longer measure performance on unseen questions.

Leakage occurs when test-set information reaches the model or development process before evaluation. It can happen through routine preparation decisions, without deliberate cheating.

We can demonstrate one route by changing how we select the vocabulary.

Compare the training-only selection in Part I with selection using all tweets.

# What Part I did: look only at the 724 training tweets, and keep every word
# used at least 5 times among them.
length(freq_words)
[1] 651
# The careless version: look at all 905 tweets, including the 181 that are
# about to be used as the test set.
freq_leaky <- findFreqTerms(dtm, 5)

length(freq_leaky)
[1] 749

dtm contains all 905 tweets; dtm[train_id, ] contains the 724 training rows. Passing the full matrix to findFreqTerms() instead of the training subset lets test documents influence vocabulary selection.

The resulting vocabulary contains around a hundred extra words. setdiff() identifies them by returning words in the first set but not the second.

head(setdiff(freq_leaky, freq_words), 20)
 [1] "account"     "addit"       "address"     "amaz"        "appoint"    
 [6] "apprentic"   "assist"      "associ"      "benefit"     "biden"      
[11] "bishop"      "black"       "bless"       "brought"     "captur"     
[16] "center"      "condit"      "congression" "consider"    "convers"    

These terms reached the frequency threshold only when we included the test tweets. They therefore enter the model because of the documents on which it will be evaluated, rather than training evidence alone.

A second route concerns threshold selection. Part I gave us the opportunity to make this mistake.

We calculated precision, recall, and accuracy at nine test-set thresholds. Inspecting that table is useful. Selecting a threshold from it and reporting the same test score as an independent evaluation is a different matter.

# The row of the sweep where accuracy happens to be highest.
# which.max() returns the position of the largest value in a vector.
best <- sweep_out[which.max(sweep_out$accuracy), ]

# sweep_out$default is the TRUE/FALSE column marking the 0.5 row, so this
# compares the accuracy at the default against the best available anywhere.
round(c(at_the_default = sweep_out$accuracy[sweep_out$default],
        best_on_test   = best$accuracy), 3)
at_the_default   best_on_test 
         0.906          0.923 
best$threshold
[1] 0.6

The best threshold in this test set differs from 0.5 and classifies a few more tweets correctly. The code and arithmetic are correct.

But the threshold was selected using the test answers. Its score describes a choice optimized for these 181 tweets, not an independent estimate of performance on new ones. We cannot assume that threshold will remain best or that score will repeat in another sample.

No error message identifies this problem. Leakage can look like improved performance, so we need to check how decisions were made rather than relying on warnings from the software.

6.3.3 The version you cannot check

We can address these examples by selecting vocabulary from dtm[train_id, ] and choosing the threshold separately from final evaluation data.

Contamination raises a related problem for pretrained models: our test documents may already have appeared in their training data. With an undisclosed commercial corpus, we cannot establish that they were excluded.

This is plausible for our corpus. Presidential tweets have been quoted in news coverage, analyzed in academic work, and archived in at least three public GitHub repositories, including our source. The model may have encountered both the tweets and commentary explaining them before our request.

We cannot check that possibility from outside the company. Report it as a limitation when interpreting the 95 percent score, rather than treating the result as certainly out of sample.

It also limits the comparison with Naive Bayes. Our classifier was trained on 724 tweets, while the language model may have encountered these documents and commentary during pretraining. The table compares their outputs, but does not give them equal prior information.

6.3.4 What a benchmark number means

Benchmark scores dominate many published evaluations. Three recurring problems are useful to recognize, including versions of issues we have examined here.

Benchmarks saturate as systems improve and are selected against them. Near the ceiling, small score differences may reflect noise more than meaningful performance differences. Replacing the benchmark with a harder one helps, but scores from different tests are not directly comparable over time.

Benchmarks can be gamed through ordinary optimization. Selecting the best test-set threshold would produce a favorable number without a coding error. When rankings affect funding or procurement, repeated selection against a benchmark can similarly make it less informative about broader performance.

Language models also increasingly judge other models’ outputs, reducing the cost of human evaluation. Shared training patterns and assumptions can make that agreement weak evidence of quality. Our smaller comparison illustrates the concern: three models agreed on 169 tweets, but three of those labels differed from the human benchmark.

When a vendor, procurement document, or paper reports 94 percent accuracy, ask which benchmark was used, who constructed it, when it was measured, and whose labels defined success. These are substantive and institutional questions as well as technical ones.

6.4 Part IV. When the measurement feeds a regression

Labels are often an intermediate step in research. They become variables used in an analysis, so labeling errors can affect the substantive estimate.

For these 181 tweets, we can ask how much larger the immigration share was in the first half of 2019 than in the second. The first half included the wall-funding shutdown and national emergency declaration; impeachment became more prominent later.

Split the tweets by half-year and calculate the share difference using each set of labels. The hand labels give roughly 36 percentage points, the model labels roughly 30, and the reworded prompt roughly 27. Despite 95 percent agreement, the model labels understate this substantive difference by between a sixth and a quarter.

The model over-flags in both halves. When genuine immigration tweets are scarce in the second half, false positives form a larger share of the immigration total and inflate that estimate more. This narrows the estimated gap between the halves, pulling it toward zero.

This systematic error does not disappear simply by labeling a larger corpus. More observations can produce a more precise biased estimate, and ordinary output or standard errors need not reveal it. Egami and colleagues (Egami et al. 2023) demonstrate downstream bias with labels of 80 to 90 percent accuracy. Our example shows attenuation even at 95 percent agreement.

6.4.1 What to do about it

Their statistical correction goes beyond this course. But the practice needed to support correction does not: preserve a hand-coded validation sample, as required for Type B projects.

Hand-code a random sample before inspecting the model’s labels. Report agreement and describe the disagreements, including any systematic direction of error. Present the substantive estimate with information about its labels’ quality. This lets readers assess a limitation they would otherwise be unable to see.

Finally, consider whether an independent researcher has the access needed to perform these checks.

6.5 The politics of who may audit

We could evaluate this exercise because we had the corpus, labels, code, and outputs. Researchers auditing deployed systems may have much less access.

Undisclosed training data prevent contamination checks. Inaccessible weights leave researchers querying a system from outside, sometimes under terms that restrict systematic probing. A model may change between measurement and publication. Meanwhile, the organization with the fullest access also has an interest in the evaluation’s outcome.

Audit access therefore raises legal and institutional questions. Proposals for safe harbor would protect good-faith independent evaluation from liability. Outside queries alone may not provide everything a rigorous audit needs; arranging fuller access requires rules about who may inspect what.

We have asked who defines similarity, selects thresholds, writes codebooks, and owns classifiers. Now ask: who is allowed to check? The organization being evaluated often controls access. What arrangements would make independent scrutiny possible?

6.6 Reading

Grimmer, J., and Stewart, B. M. 2013. “Text as Data: The Promise and Pitfalls of Automatic Content Analysis Methods for Political Texts.” Political Analysis 21(3): 267–297. (Grimmer and Stewart 2013)

Return to the article’s argument that validation is essential and requires more than selecting a metric. Compare its recommendations with what we did in Part II. Which did our procedure satisfy?

Lowe, W., and Benoit, K. 2013. “Validating Estimates of Latent Traits from Textual Data Using Human Judgment as a Benchmark.” Political Analysis 21(3): 298–313. (Lowe and Benoit 2013)

This article appeared immediately after Grimmer and Stewart in the same issue. It examines human judgment as a benchmark, as we used it in Part II. Focus on how variability in that judgment should be modeled rather than assumed away.

Egami, N., Hinck, M., Stewart, B. M., and Wei, H. 2023. “Using Imperfect Surrogates for Downstream Inference: Design-Based Supervised Learning for Social Science Applications of Large Language Models.” Advances in Neural Information Processing Systems 36. (Egami et al. 2023)

This is the source for Part IV. The estimator is beyond our scope, but read the opening demonstration of how imperfect labels affect inference. It is particularly relevant if your project uses model-generated labels.

6.7 Before the workshop

Run the full handout before the workshop. It makes no API calls, so you need no key or credit. The only new package is pROC.

Read data/llm_labels_w6_README.md, especially the limits on exact reproduction. You will need that information for Assignment 3.

Bring a factual question from your own area of interest that you can check. We will use it for the existence-check exercise.

6.8 Questions for the session

Prepare an answer to at least two questions.

  1. The language model beat a classifier trained on 724 hand-labeled examples, having seen none. Give the strongest argument you can that Week 4 was nonetheless worth doing, and then give the strongest argument against yourself.

  2. Two prompts, each of which a competent researcher might have written first, label about four percent of the corpus differently. What should a journal require an author to report about this, and what would it cost the author to comply?

  3. Part II insisted that agreement between two models is not evidence of accuracy. Construct a case in which two independent models agree closely and are both substantially wrong, and say what you would need in order to detect it.

  4. Our accuracy figure measures agreement with one coder’s application of one codebook. Suppose a second coder had labeled the same tweets and agreed with the first on 90 percent of them. What is the most the model’s 95 percent can now mean?

  5. The attenuation in Part IV went in a predictable direction once the mechanism was understood. Describe a research question where the same kind of error would bias an estimate upward instead, and explain why.

  6. You are advising a ministry considering a system that its vendor reports as 94 percent accurate. List, in order, the questions you would ask before the contract is signed, and mark which of them the vendor is likely to refuse to answer.