Skip to content

Annotators as instruments: Dawid–Skene, GLAD and MACE

When several people (or models) label the same items, estimate each item's true label and each annotator's error rates together, and check that the annotators really labeled independently.

Advanced ~13 min9 steps

What runs in CodeSplash

You will be able to

  • Explain how an annotator model weighs labels by each annotator's estimated error rates
  • Choose between Dawid–Skene, GLAD and MACE
  • Spot copied or shared labels that make a consensus overconfident

Read first

01

From agreement to answers

In the app

Kappa and alpha say how much raters agree. When you need the labels themselves — training data for a model, a coded survey, a judged benchmark — you want the most likely true label for each item, and you want to trust the careful annotators more than the careless ones.

An annotator modelAnnotator modelA model that estimates each item's true label and each annotator's error rates together from labels given by several people. does both at once. It treats each item's true label as unknown, gives every annotator their own error rates, and fits the two together by EM: start from the majority vote, estimate each annotator's error rates from the current guesses, update the guesses using those rates, and repeat.

02

A first fit

In the app

Here 6 annotators gave 534 labels to 120 items, three to six labels per item. Dawid–Skene's consensus matches the plain majority vote on 96.7% of items. Where they differ, the more reliable annotators outvoted the others. Mean confidence in the consensus is 0.97.

Annotator model (Dawid–Skene)Recorded · Python and R agreeRecorded 2026-11-21 · 27 values compared
R

Dawid–Skene model, 6 annotators, 120 items, 534 labels; log-likelihood = −442.12

Mean confidence
0.9664
Matches majority vote
96.7%
Log-likelihood
−442.12

Plots

Annotators: estimated accuracy and agreement with the consensusHow do categories compare on one value — and across up to three groups?
View data
AnnotatorMeasureShare
a1Estimated accuracy0.8573
a2Estimated accuracy0.7767
a3Estimated accuracy0.7940
a4Estimated accuracy0.6725
a5Estimated accuracy0.6052
a6Estimated accuracy0.9204
a1Agrees with consensus0.8539
a2Agrees with consensus0.7865
a3Agrees with consensus0.7978
a4Agrees with consensus0.6782
a5Agrees with consensus0.6087
a6Agrees with consensus0.9318
How each annotator labels each true classHow does each annotator label items of each true class?
View data
AnnotatorLabel givenTrue classProbability
a1positivepositive0.8910
a1neutralpositive0.1087
a1negativepositive0.0003
a1positiveneutral0.0840
a1neutralneutral0.8765
a1negativeneutral0.0395
a1positivenegative0.0878
a1neutralnegative0.1366
a1negativenegative0.7756
a2positivepositive0.7611
a2neutralpositive0.1565
a2negativepositive0.0824
a2positiveneutral0.0359
a2neutralneutral0.9121
a2negativeneutral0.0520
a2positivenegative0.0444
a2neutralnegative0.3278
a2negativenegative0.6278
a3positivepositive0.7618
a3neutralpositive0.2379
a3negativepositive0.0003
a3positiveneutral0.0457
a3neutralneutral0.8714
a3negativeneutral0.0828
a3positivenegative0.0005
a3neutralnegative0.2348
a3negativenegative0.7648
a4positivepositive0.7483
a4neutralpositive0.1310
a4negativepositive0.1207
a4positiveneutral0.1612
a4neutralneutral0.6077
a4negativeneutral0.2312
a4positivenegative0.2346
a4neutralnegative0.1354
a4negativenegative0.6301
a5positivepositive0.5783
a5neutralpositive0.1561
a5negativepositive0.2656
a5positiveneutral0.1912
a5neutralneutral0.6513
a5negativeneutral0.1575
a5positivenegative0.2384
a5neutralnegative0.1737
a5negativenegative0.5879
a6positivepositive0.8840
a6neutralpositive0.1148
a6negativepositive0.0013
a6positiveneutral0.0554
a6neutralneutral0.9442
a6negativeneutral0.0004
a6positivenegative0.0535
a6neutralnegative0.0005
a6negativenegative0.9460
Confidence in each item's consensus labelHow is one numeric variable distributed?
View data
Confidence
0.8079
1.0000
0.9999
1.0000
1.0000
0.9994
0.9992
0.9879
0.9830
0.9999
0.9920
0.9978
1.0000
1.0000
0.9755
0.9996
0.9901
0.9986
0.9999
0.9611
0.9616
0.9992
0.9891
0.9629
0.9602
0.8953
0.9960
0.9938
0.9966
1.0000
0.9912
1.0000
0.9998
0.9998
0.9999
0.9986
0.9963
0.9999
1.0000
0.9997
0.9995
0.9999
0.9996
0.9993
0.9767
0.9998
1.0000
0.9967
1.0000
1.0000
0.9994
0.9390
0.5766
0.9995
1.0000
0.9956
0.9966
0.9985
0.4666
0.9995

First 60 of 120 rows.

Assumptions

  • Annotators overlap — 100% of items have two or more labels.
  • Every class has items — Every class has at least 5 expected items.
  • Convergence — EM converged after 107 iterations.
  • Annotators label independently — No pair agrees more than 15 points above what independent labeling would give.

Annotators

AnnotatorLabelsEstimated accuracyAgrees with consensus
a18985.7%85.4%
a28977.7%78.7%
a38979.4%79.8%
a48767.2%67.8%
a59260.5%60.9%
a68892.0%93.2%

Labels

LabelEstimated shareItems (consensus)Items (majority vote)
positive45.6%5659
neutral29.8%3536
negative24.6%2925

Least certain items

ItemConsensusConfidenceMajority voteLabels
t059positive46.7%positive3
t119negative52.1%neutral4
t053neutral57.7%neutral4
t098positive70.6%positive4
t120neutral71.5%neutral4
t090positive71.7%positive4
t064positive76.0%positive4
t067neutral79.6%neutral3
t001positive80.8%positive4
t062neutral81.4%neutral3
t026positive89.5%positive3
t071positive93.0%positive3
t052positive93.9%positive3
t102neutral94.3%neutral6
t094neutral94.7%neutral5
t111negative95.3%negative3
t088neutral95.4%neutral6
t025positive96.0%positive4
t020positive96.1%positive5
t021positive96.2%positive4
t024neutral96.3%neutral3
t070negative96.5%positive5
t087neutral97.0%neutral3
t015negative97.6%negative3
t045positive97.7%positive3

Pairs that agree more than independent labeling would

AnnotatorWithShared itemsObserved agreementExpected if independentExcess
a1a66780.6%74.2%0.0636
a4a66567.7%62.6%0.0509
a2a36163.9%61.8%0.0215
a4a56949.3%47.8%0.0149
a3a46660.6%59.3%0.0128
a2a57052.9%51.9%0.0100
a1a26668.2%67.6%0.0058
a1a46761.2%61.5%−0.0029
a5a66855.9%57.0%−0.0111
a1a36768.7%70.2%−0.0156
  • EM from the majority vote; smoothing 0.01. Estimated accuracy is the expected share of an annotator's labels that match the true class. A low value is a statistical pattern, not a judgment of the person.
The exact R script · R R version 4.5.1 (2025-06-13)
# Annotator models (Dawid–Skene, GLAD, MACE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method agreement.dawid_skene 1.0.0 · spec 2155a83122af0e77
# Dataset: annotations_sim (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/annotations_sim.parquet", col_select = c("item", "annotator", "label")))
n_input <- nrow(df)
df[["item"]] <- factor(df[["item"]], levels = c("t001", "t002", "t003", "t004", "t005", "t006", "t007", "t008", "t009", "t010", "t011", "t012", "t013", "t014", "t015", "t016", "t017", "t018", "t019", "t020", "t021", "t022", "t023", "t024", "t025", "t026", "t027", "t028", "t029", "t030", "t031", "t032", "t033", "t034", "t035", "t036", "t037", "t038", "t039", "t040", "t041", "t042", "t043", "t044", "t045", "t046", "t047", "t048", "t049", "t050", "t051", "t052", "t053", "t054", "t055", "t056", "t057", "t058", "t059", "t060", "t061", "t062", "t063", "t064", "t065", "t066", "t067", "t068", "t069", "t070", "t071", "t072", "t073", "t074", "t075", "t076", "t077", "t078", "t079", "t080", "t081", "t082", "t083", "t084", "t085", "t086", "t087", "t088", "t089", "t090", "t091", "t092", "t093", "t094", "t095", "t096", "t097", "t098", "t099", "t100", "t101", "t102", "t103", "t104", "t105", "t106", "t107", "t108", "t109", "t110", "t111", "t112", "t113", "t114", "t115", "t116", "t117", "t118", "t119", "t120"))  # stored level order
df[["annotator"]] <- factor(df[["annotator"]], levels = c("a1", "a2", "a3", "a4", "a5", "a6"))  # stored level order
df[["label"]] <- factor(df[["label"]], levels = c("positive", "neutral", "negative"))  # stored level order
df <- df[stats::complete.cases(df[c("item", "annotator", "label")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("item", "annotator", "label"))  # infinite values stop the run (registry/errors.yaml)

# %% Codes (one row per label: item, annotator, label)
item_col <- "item"
annot_col <- "annotator"
label_col <- "label"
items <- levels(df[[item_col]])
annots <- levels(df[[annot_col]])
labels <- levels(df[[label_col]])
n <- length(items)
m <- length(annots)
k <- length(labels)
model <- "dawid_skene"
if (n < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = item_col, min = 2, k = n)
if (m < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = annot_col, min = 2, k = m)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = label_col, min = 2, k = k)
if (model == "glad" && k != 2) cs_error("CS_E_GROUP_COUNT", column = label_col, expected = 2, k = k)
item <- as.integer(df[[item_col]])
annot <- as.integer(df[[annot_col]])
label <- as.integer(df[[label_col]])
if (!any(tabulate(item, n) >= 2)) cs_error("CS_E_UNDEFINED", what = "Annotator error rates", reason = "every item has a single label; the models learn from items that two or more annotators labeled")

# %% Fit
smoothing <- 0.01
restarts <- as.integer(0)
seed <- as.integer(1)
fit <- cs_annotator_model(item, annot, label, n, m, k, model = model, smoothing = smoothing, restarts = restarts, seed = seed)
summ <- cs_annotator_summary(fit, item, annot, label, n, m, k, smoothing = smoothing)
mv <- cs_annotator_majority_vote(item, label, n, k)
T <- fit$T
consensus <- summ$consensus
confidence <- summ$confidence
model_label <- c(dawid_skene = "Dawid–Skene", glad = "GLAD", mace = "MACE")[[model]]
per_item <- tabulate(item, n)
pairs <- summ$pairs
if (length(pairs)) {
  pm <- do.call(rbind, pairs)
  pm <- pm[order(-pm[, 6], pm[, 1], pm[, 2]), , drop = FALSE]
} else pm <- matrix(numeric(0), 0, 6)
max_excess <- if (nrow(pm)) pm[1, 6] else NA_real_

values <- list(
  n_items = n, n_annotators = m, n_labels = length(item), k = k,
  loglik = fit$loglik, iterations = fit$iterations, converged = if (fit$converged) 1 else 0,
  mean_confidence = mean(confidence), share_uncertain = mean(confidence < 0.8),
  agree_majority = mean(consensus == mv), max_pair_excess = max_excess,
  model_label = model_label
)
share <- colMeans(T)
for (c0 in seq_len(k)) values[[sprintf("share[%s]", labels[c0])]] <- share[c0]
ann_rows <- list()
for (j in seq_len(m)) {
  a <- annots[j]
  values[[sprintf("accuracy[%s]", a)]] <- summ$accuracy[j]
  values[[sprintf("agreement[%s]", a)]] <- summ$agreement[j]
  row <- list(annotator = a, labels = as.integer(summ$n_labels[j]), accuracy = summ$accuracy[j], agreement = summ$agreement[j])
  if (model == "glad") values[[sprintf("ability[%s]", a)]] <- row$ability <- fit$par$ability[j]
  if (model == "mace") values[[sprintf("competence[%s]", a)]] <- row$competence <- fit$par$competence[j]
  ann_rows[[j]] <- row
}

# %% Assumptions
shared <- vapply(seq_len(m), function(j) any(item[annot != j] %in% unique(item[annot == j])), logical(1))
multi <- mean(per_item >= 2)
alone <- annots[!shared]
support <- colSums(T)
thin <- labels[support < 5]
flagged <- if (nrow(pm)) pm[pm[, 3] >= 20 & pm[, 6] > 0.15, , drop = FALSE] else pm
pct0 <- function(x) sprintf("%.0f%%", 100 * x)
assumptions <- list(
  list(key = "overlap", label = "Annotators overlap", status = if (length(alone) || multi < 0.5) "warn" else "pass",
       detail = paste0(if (length(alone)) sprintf("No shared items for: %s — their error rates rest on the model alone. ", paste(alone, collapse = ", ")) else "",
                       sprintf("%s of items have two or more labels.", pct0(multi)))),
  list(key = "class_support", label = "Every class has items", status = if (length(thin)) "warn" else "pass",
       detail = if (length(thin)) sprintf("Fewer than 5 expected items in: %s.", paste(thin, collapse = ", ")) else "Every class has at least 5 expected items."),
  list(key = "convergence", label = "Convergence", status = if (fit$converged) "pass" else "warn",
       detail = sprintf("EM %s after %d iterations.", if (fit$converged) "converged" else "stopped before converging", fit$iterations)),
  list(key = "conditional_independence", label = "Annotators label independently",
       status = if (nrow(flagged)) "warn" else if (nrow(pm)) "pass" else "info",
       detail = if (nrow(flagged)) sprintf("%s and %s agree on %s of %d shared items; independent labeling would give %s. Copied or shared labels make the consensus overconfident.",
                                          annots[flagged[1, 1]], annots[flagged[1, 2]], pct0(flagged[1, 4]), as.integer(flagged[1, 3]), pct0(flagged[1, 5]))
                else if (nrow(pm)) "No pair agrees more than 15 points above what independent labeling would give." else "Too few shared items to compare pairs of annotators.")
)
if (!fit$converged) warnings <- c(warnings, cs_warning("CS_W_NO_CONVERGENCE", what = model_label))

# %% Tables
ord <- order(confidence, seq_len(n))[seq_len(min(25, n))]
item_rows <- lapply(ord, function(i) list(item = items[i], consensus = labels[consensus[i]], confidence = confidence[i],
                                          majority = labels[mv[i]], labels = per_item[i]))
class_rows <- lapply(seq_len(k), function(c0) list(label = labels[c0], share = share[c0], consensus = sum(consensus == c0),
                                                   majority = sum(mv == c0)))
pair_rows <- lapply(seq_len(min(10, nrow(pm))), function(r) list(a = annots[pm[r, 1]], b = annots[pm[r, 2]], shared = as.integer(pm[r, 3]),
                                                                 observed = pm[r, 4], expected = pm[r, 5], excess = pm[r, 6]))
ann_cols <- list(list(key = "annotator", label = "Annotator", type = "string"), list(key = "labels", label = "Labels", type = "integer"),
                 list(key = "accuracy", label = "Estimated accuracy", type = "percent"),
                 list(key = "agreement", label = "Agrees with consensus", type = "percent"))
if (model == "glad") ann_cols[[length(ann_cols) + 1]] <- list(key = "ability", label = "Ability (α)", type = "number")
if (model == "mace") ann_cols[[length(ann_cols) + 1]] <- list(key = "competence", label = "Competence (θ)", type = "percent")
tables <- list(
  list(key = "annotators", title = "Annotators", columns = ann_cols, rows = ann_rows),
  list(key = "classes", title = "Labels", columns = list(
    list(key = "label", label = "Label", type = "string"), list(key = "share", label = "Estimated share", type = "percent"),
    list(key = "consensus", label = "Items (consensus)", type = "integer"), list(key = "majority", label = "Items (majority vote)", type = "integer")
  ), rows = class_rows),
  list(key = "uncertain", title = "Least certain items", columns = list(
    list(key = "item", label = "Item", type = "string"), list(key = "consensus", label = "Consensus", type = "string"),
    list(key = "confidence", label = "Confidence", type = "percent"), list(key = "majority", label = "Majority vote", type = "string"),
    list(key = "labels", label = "Labels", type = "integer")
  ), rows = item_rows)
)
if (length(pair_rows)) tables[[length(tables) + 1]] <- list(key = "pairs", title = "Pairs that agree more than independent labeling would", columns = list(
  list(key = "a", label = "Annotator", type = "string"), list(key = "b", label = "With", type = "string"),
  list(key = "shared", label = "Shared items", type = "integer"), list(key = "observed", label = "Observed agreement", type = "percent"),
  list(key = "expected", label = "Expected if independent", type = "percent"), list(key = "excess", label = "Excess", type = "number")
), rows = pair_rows)

# %% Charts
charts <- list(cs_chart("annotators", "cleveland-dot", "Annotators: estimated accuracy and agreement with the consensus", list(
  category = cs_col("Annotator", c(annots, annots), "categorical", levels = annots),
  value = cs_col("Share", c(summ$accuracy, summ$agreement), "numeric"),
  group = cs_col("Measure", rep(c("Estimated accuracy", "Agrees with consensus"), each = m), "categorical",
                 levels = c("Estimated accuracy", "Agrees with consensus"))
), controls = list(top = min(30, max(3, m)), sort = "value")))
if (model %in% c("dawid_skene", "mace")) {
  if (model == "dawid_skene") {
    cm <- fit$par$theta
  } else {
    cm <- array(0, dim = c(m, k, k))
    for (c0 in seq_len(k)) {
      cm[, c0, ] <- (1 - fit$par$competence) * fit$par$spam
      cm[, c0, c0] <- cm[, c0, c0] + fit$par$competence
    }
  }
  grid <- expand.grid(l = seq_len(k), c = seq_len(k), j = seq_len(m))
  charts[[length(charts) + 1]] <- cs_chart("confusion", "annotator-confusion", "How each annotator labels each true class", list(
    annotator = cs_col("Annotator", annots[grid$j], "categorical", levels = annots),
    truth = cs_col("True class", labels[grid$c], "categorical", levels = labels),
    given = cs_col("Label given", labels[grid$l], "categorical", levels = labels),
    value = cs_col("Probability", cm[cbind(grid$j, grid$c, grid$l)], "numeric")
  ))
}
charts[[length(charts) + 1]] <- cs_chart("confidence", "histogram", "Confidence in each item's consensus label", list(
  x = cs_col("Confidence", confidence, "numeric")
), controls = list(scale = "count", kde = FALSE))

# %% Result
cs_publish(list(
  method = "agreement.dawid_skene",
  methodVersion = "1.0.0",
  title = sprintf("Annotator model (%s)", model_label),
  engine = cs_engine_info("stats", "codesplashr"),
  n = length(item),
  summary = sprintf("%s for %d labels from %d annotators on %d items: the consensus matches the majority vote on %s of items, with mean confidence %.2f.",
                    model_label, length(item), m, n, pct0(values$agree_majority), values$mean_confidence),
  apa = sprintf("%s model, %d annotators, %d items, %d labels; log-likelihood = %s", model_label, m, n, length(item), cs_fmt_num(fit$loglik, 2)),
  statistics = list(list(key = "mean_confidence", label = "Mean confidence", value = values$mean_confidence),
                    list(key = "agree_majority", label = "Matches majority vote", value = values$agree_majority, format = "percent"),
                    list(key = "loglik", label = "Log-likelihood", value = values$loglik)),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("EM from the majority vote%s; smoothing %s. Estimated accuracy is the expected share of an annotator's labels that match the true class. A low value is a statistical pattern, not a judgment of the person.",
                       if (restarts > 0) sprintf(" plus %d random restarts", restarts) else "", format(smoothing))),
  charts = charts,
  values = values
))
Python

Dawid–Skene model, 6 annotators, 120 items, 534 labels; log-likelihood = −442.12

Mean confidence
0.9664
Matches majority vote
96.7%
Log-likelihood
−442.12

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Annotators overlap — 100% of items have two or more labels.
  • Every class has items — Every class has at least 5 expected items.
  • Convergence — EM converged after 107 iterations.
  • Annotators label independently — No pair agrees more than 15 points above what independent labeling would give.

Annotators

AnnotatorLabelsEstimated accuracyAgrees with consensus
a18985.7%85.4%
a28977.7%78.7%
a38979.4%79.8%
a48767.2%67.8%
a59260.5%60.9%
a68892.0%93.2%

Labels

LabelEstimated shareItems (consensus)Items (majority vote)
positive45.6%5659
neutral29.8%3536
negative24.6%2925

Least certain items

ItemConsensusConfidenceMajority voteLabels
t059positive46.7%positive3
t119negative52.1%neutral4
t053neutral57.7%neutral4
t098positive70.6%positive4
t120neutral71.5%neutral4
t090positive71.7%positive4
t064positive76.0%positive4
t067neutral79.6%neutral3
t001positive80.8%positive4
t062neutral81.4%neutral3
t026positive89.5%positive3
t071positive93.0%positive3
t052positive93.9%positive3
t102neutral94.3%neutral6
t094neutral94.7%neutral5
t111negative95.3%negative3
t088neutral95.4%neutral6
t025positive96.0%positive4
t020positive96.1%positive5
t021positive96.2%positive4
t024neutral96.3%neutral3
t070negative96.5%positive5
t087neutral97.0%neutral3
t015negative97.6%negative3
t045positive97.7%positive3

Pairs that agree more than independent labeling would

AnnotatorWithShared itemsObserved agreementExpected if independentExcess
a1a66780.6%74.2%0.0636
a4a66567.7%62.6%0.0509
a2a36163.9%61.8%0.0215
a4a56949.3%47.8%0.0149
a3a46660.6%59.3%0.0128
a2a57052.9%51.9%0.0100
a1a26668.2%67.6%0.0058
a1a46761.2%61.5%−0.0029
a5a66855.9%57.0%−0.0111
a1a36768.7%70.2%−0.0156
  • EM from the majority vote; smoothing 0.01. Estimated accuracy is the expected share of an annotator's labels that match the true class. A low value is a statistical pattern, not a judgment of the person.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Annotator models (Dawid–Skene, GLAD, MACE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method agreement.dawid_skene 1.0.0 · spec 2155a83122af0e77
# Dataset: annotations_sim (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.stats import annotators as an  # Dawid–Skene, GLAD, MACE (twin of R's cs_annotator_model)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/annotations_sim.parquet", columns=["item", "annotator", "label"])
n_input = len(df)
df["item"] = pd.Categorical(df["item"], categories=["t001", "t002", "t003", "t004", "t005", "t006", "t007", "t008", "t009", "t010", "t011", "t012", "t013", "t014", "t015", "t016", "t017", "t018", "t019", "t020", "t021", "t022", "t023", "t024", "t025", "t026", "t027", "t028", "t029", "t030", "t031", "t032", "t033", "t034", "t035", "t036", "t037", "t038", "t039", "t040", "t041", "t042", "t043", "t044", "t045", "t046", "t047", "t048", "t049", "t050", "t051", "t052", "t053", "t054", "t055", "t056", "t057", "t058", "t059", "t060", "t061", "t062", "t063", "t064", "t065", "t066", "t067", "t068", "t069", "t070", "t071", "t072", "t073", "t074", "t075", "t076", "t077", "t078", "t079", "t080", "t081", "t082", "t083", "t084", "t085", "t086", "t087", "t088", "t089", "t090", "t091", "t092", "t093", "t094", "t095", "t096", "t097", "t098", "t099", "t100", "t101", "t102", "t103", "t104", "t105", "t106", "t107", "t108", "t109", "t110", "t111", "t112", "t113", "t114", "t115", "t116", "t117", "t118", "t119", "t120"])  # stored level order
df["annotator"] = pd.Categorical(df["annotator"], categories=["a1", "a2", "a3", "a4", "a5", "a6"])  # stored level order
df["label"] = pd.Categorical(df["label"], categories=["positive", "neutral", "negative"])  # stored level order
df = df.dropna(subset=["item", "annotator", "label"])  # listwise deletion over the analysis columns
df["item"] = df["item"].cat.remove_unused_categories()
df["annotator"] = df["annotator"].cat.remove_unused_categories()
df["label"] = df["label"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["item", "annotator", "label"])  # infinite values stop the run (registry/errors.yaml)

# %% Codes (one row per label: item, annotator, label)
item_col, annot_col, label_col = "item", "annotator", "label"
items = [str(x) for x in df[item_col].cat.categories]
annots = [str(x) for x in df[annot_col].cat.categories]
labels = [str(x) for x in df[label_col].cat.categories]
n, m, k = len(items), len(annots), len(labels)
model = "dawid_skene"
if n < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=item_col, min=2, k=n)
if m < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=annot_col, min=2, k=m)
if k < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=label_col, min=2, k=k)
if model == "glad" and k != 2:
    cs.cs_error("CS_E_GROUP_COUNT", column=label_col, expected=2, k=k)
item = df[item_col].cat.codes.to_numpy(dtype=np.int64)
annot = df[annot_col].cat.codes.to_numpy(dtype=np.int64)
label = df[label_col].cat.codes.to_numpy(dtype=np.int64)
if not np.any(np.bincount(item, minlength=n) >= 2):
    cs.cs_error("CS_E_UNDEFINED", what="Annotator error rates", reason="every item has a single label; the models learn from items that two or more annotators labeled")

# %% Fit
smoothing = 0.01
restarts = int(0)
seed = int(1)
fit = an.annotator_model(item, annot, label, n, m, k, model=model, smoothing=smoothing, restarts=restarts, seed=seed)
summ = an.annotator_summary(fit, item, annot, label, n, m, k, smoothing=smoothing)
mv = an.majority_vote(item, label, n, k)
T = fit["T"]
consensus, confidence = summ["consensus"], summ["confidence"]
model_label = {"dawid_skene": "Dawid–Skene", "glad": "GLAD", "mace": "MACE"}[model]
per_item = np.bincount(item, minlength=n)
pairs = sorted(summ["pairs"], key=lambda r: (-r[5], r[0], r[1]))
max_excess = pairs[0][5] if pairs else None

values = {
    "n_items": float(n), "n_annotators": float(m), "n_labels": float(len(item)), "k": float(k),
    "loglik": float(fit["loglik"]), "iterations": float(fit["iterations"]), "converged": 1.0 if fit["converged"] else 0.0,
    "mean_confidence": float(np.mean(confidence)), "share_uncertain": float(np.mean(confidence < 0.8)),
    "agree_majority": float(np.mean(consensus == mv)), "max_pair_excess": None if max_excess is None else float(max_excess),
    "model_label": model_label,
}
share = T.mean(axis=0)
for c, lab in enumerate(labels):
    values[f"share[{lab}]"] = float(share[c])
ann_rows = []
for j, a in enumerate(annots):
    values[f"accuracy[{a}]"] = float(summ["accuracy"][j])
    values[f"agreement[{a}]"] = float(summ["agreement"][j])
    row = {"annotator": a, "labels": int(summ["n_labels"][j]), "accuracy": float(summ["accuracy"][j]),
           "agreement": float(summ["agreement"][j])}
    if model == "glad":
        values[f"ability[{a}]"] = row["ability"] = float(fit["par"]["ability"][j])
    if model == "mace":
        values[f"competence[{a}]"] = row["competence"] = float(fit["par"]["competence"][j])
    ann_rows.append(row)

# %% Assumptions
shared = np.zeros(m, dtype=bool)
for j in range(m):
    its = np.unique(item[annot == j])
    shared[j] = bool(np.any(np.isin(item[annot != j], its)))
multi = float(np.mean(per_item >= 2))
alone = [annots[j] for j in range(m) if not shared[j]]
support = T.sum(axis=0)
thin = [labels[c] for c in range(k) if support[c] < 5]
flagged = [p for p in pairs if p[2] >= 20 and p[5] > 0.15]
assumptions = [
    {"key": "overlap", "label": "Annotators overlap", "status": "warn" if (alone or multi < 0.5) else "pass",
     "detail": (f"No shared items for: {', '.join(alone)} — their error rates rest on the model alone. " if alone else "")
     + f"{multi:.0%} of items have two or more labels."},
    {"key": "class_support", "label": "Every class has items", "status": "warn" if thin else "pass",
     "detail": f"Fewer than 5 expected items in: {', '.join(thin)}." if thin else "Every class has at least 5 expected items."},
    {"key": "convergence", "label": "Convergence", "status": "pass" if fit["converged"] else "warn",
     "detail": f"EM {'converged' if fit['converged'] else 'stopped before converging'} after {fit['iterations']} iterations."},
    {"key": "conditional_independence", "label": "Annotators label independently",
     "status": "warn" if flagged else ("pass" if pairs else "info"),
     "detail": (f"{annots[flagged[0][0]]} and {annots[flagged[0][1]]} agree on {flagged[0][3]:.0%} of {flagged[0][2]} shared items; independent labeling would give {flagged[0][4]:.0%}. Copied or shared labels make the consensus overconfident."
                if flagged else ("No pair agrees more than 15 points above what independent labeling would give." if pairs else "Too few shared items to compare pairs of annotators."))},
]
if not fit["converged"]:
    warnings.append(cs.cs_warning("CS_W_NO_CONVERGENCE", what=model_label))

# %% Tables
order = np.lexsort((np.arange(n), confidence))[:25]
item_rows = [{"item": items[i], "consensus": labels[consensus[i]], "confidence": float(confidence[i]),
              "majority": labels[mv[i]], "labels": int(per_item[i])} for i in order]
class_rows = [{"label": labels[c], "share": float(share[c]), "consensus": int(np.sum(consensus == c)),
               "majority": int(np.sum(mv == c))} for c in range(k)]
pair_rows = [{"a": annots[p[0]], "b": annots[p[1]], "shared": int(p[2]), "observed": float(p[3]), "expected": float(p[4]),
              "excess": float(p[5])} for p in pairs[:10]]
ann_cols = [{"key": "annotator", "label": "Annotator", "type": "string"}, {"key": "labels", "label": "Labels", "type": "integer"},
            {"key": "accuracy", "label": "Estimated accuracy", "type": "percent"},
            {"key": "agreement", "label": "Agrees with consensus", "type": "percent"}]
if model == "glad":
    ann_cols.append({"key": "ability", "label": "Ability (α)", "type": "number"})
if model == "mace":
    ann_cols.append({"key": "competence", "label": "Competence (θ)", "type": "percent"})
tables = [
    {"key": "annotators", "title": "Annotators", "columns": ann_cols, "rows": ann_rows},
    {"key": "classes", "title": "Labels", "columns": [
        {"key": "label", "label": "Label", "type": "string"}, {"key": "share", "label": "Estimated share", "type": "percent"},
        {"key": "consensus", "label": "Items (consensus)", "type": "integer"}, {"key": "majority", "label": "Items (majority vote)", "type": "integer"},
    ], "rows": class_rows},
    {"key": "uncertain", "title": "Least certain items", "columns": [
        {"key": "item", "label": "Item", "type": "string"}, {"key": "consensus", "label": "Consensus", "type": "string"},
        {"key": "confidence", "label": "Confidence", "type": "percent"}, {"key": "majority", "label": "Majority vote", "type": "string"},
        {"key": "labels", "label": "Labels", "type": "integer"},
    ], "rows": item_rows},
]
if pair_rows:
    tables.append({"key": "pairs", "title": "Pairs that agree more than independent labeling would", "columns": [
        {"key": "a", "label": "Annotator", "type": "string"}, {"key": "b", "label": "With", "type": "string"},
        {"key": "shared", "label": "Shared items", "type": "integer"}, {"key": "observed", "label": "Observed agreement", "type": "percent"},
        {"key": "expected", "label": "Expected if independent", "type": "percent"}, {"key": "excess", "label": "Excess", "type": "number"},
    ], "rows": pair_rows})

# %% Charts
charts = [cs.chart("annotators", "cleveland-dot", "Annotators: estimated accuracy and agreement with the consensus", {
    "category": cs.col("Annotator", annots + annots, "categorical", levels=annots),
    "value": cs.col("Share", [float(x) for x in summ["accuracy"]] + [float(x) for x in summ["agreement"]], "numeric"),
    "group": cs.col("Measure", ["Estimated accuracy"] * m + ["Agrees with consensus"] * m, "categorical",
                    levels=["Estimated accuracy", "Agrees with consensus"]),
}, controls={"top": min(30, max(3, m)), "sort": "value"})]
if model in ("dawid_skene", "mace"):
    if model == "dawid_skene":
        cm = fit["par"]["theta"]
    else:
        th, sp = fit["par"]["competence"], fit["par"]["spam"]
        cm = (1.0 - th)[:, None, None] * np.repeat(sp[:, None, :], k, axis=1)
        cm[:, np.arange(k), np.arange(k)] += th[:, None]
    charts.append(cs.chart("confusion", "annotator-confusion", "How each annotator labels each true class", {
        "annotator": cs.col("Annotator", [a for a in annots for _ in range(k * k)], "categorical", levels=annots),
        "truth": cs.col("True class", [labels[c] for _ in annots for c in range(k) for _ in range(k)], "categorical", levels=labels),
        "given": cs.col("Label given", [labels[l] for _ in annots for _ in range(k) for l in range(k)], "categorical", levels=labels),
        "value": cs.col("Probability", [float(cm[j, c, l]) for j in range(m) for c in range(k) for l in range(k)], "numeric"),
    }))
charts.append(cs.chart("confidence", "histogram", "Confidence in each item's consensus label", {
    "x": cs.col("Confidence", [float(x) for x in confidence], "numeric"),
}, controls={"scale": "count", "kde": False}))

# %% Result
cs.publish({
    "method": "agreement.dawid_skene",
    "methodVersion": "1.0.0",
    "title": f"Annotator model ({model_label})",
    "engine": cs.engine_info("numpy", "codesplash"),
    "n": int(len(item)),
    "summary": f"{model_label} for {len(item)} labels from {m} annotators on {n} items: the consensus matches the majority vote on {values['agree_majority']:.0%} of items, with mean confidence {values['mean_confidence']:.2f}.",
    "apa": f"{model_label} model, {m} annotators, {n} items, {len(item)} labels; log-likelihood = {cs.fmt_num(fit['loglik'], 2)}",
    "statistics": [{"key": "mean_confidence", "label": "Mean confidence", "value": values["mean_confidence"]},
                   {"key": "agree_majority", "label": "Matches majority vote", "value": values["agree_majority"], "format": "percent"},
                   {"key": "loglik", "label": "Log-likelihood", "value": values["loglik"]}],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"EM from the majority vote{f' plus {restarts} random restarts' if restarts else ''}; smoothing {smoothing:g}. Estimated accuracy is the expected share of an annotator's labels that match the true class. A low value is a statistical pattern, not a judgment of the person."],
    "charts": charts,
    "values": values,
})
03

Reading an annotator's confusion matrix

In the app

Dawid–Skene learns a full confusion matrix for each annotator: given the true class, how often do they give each label? The panels show one matrix per annotator; the outlined diagonal is how often they give the true class.

Annotator a1's estimated accuracy is 85.7%, and a5's is 60.5%. That's the expected share of their labels that match the true class. A low number is a pattern in the data — hard items, an unclear guideline, a different reading of a category — not a verdict on the person.

04

Three models, three error stories

Predict

Predict first

Items are yes/no relevance judgments, and some items are genuinely ambiguous. You don't want an annotator blamed for getting the ambiguous ones wrong. Which model describes that best?

Dawid–SkeneGLADMACE
Reveal

GLAD. It gives every item a clarity and every annotator an ability, and the chance of a right label grows with their product, so mistakes on unclear items count less. GLAD handles two categories only. Here annotator a1's ability is 1.30 and a5's is 0.52.

05

Which model when

In the app
  • Dawid–Skene: a full confusion matrix per annotator. Best when annotators label many items, and it can learn that someone systematically mixes up two classes.
  • GLAD: ability × item clarity, two labels. Best when item difficulty varies a lot.
  • MACE: each annotator's label either reflects the item (with their competence) or comes from their own habitual pattern. Robust when some annotators click without looking. a1's competence is 77.4%.
Annotator model (MACE)Recorded · Python and R agreeRecorded 2026-11-21 · 33 values compared
R

MACE model, 6 annotators, 120 items, 534 labels; log-likelihood = −454.00

Mean confidence
0.9608
Matches majority vote
95.0%
Log-likelihood
−454.00

Plots

Annotators: estimated accuracy and agreement with the consensusHow do categories compare on one value — and across up to three groups?
View data
AnnotatorMeasureShare
a1Estimated accuracy0.8544
a2Estimated accuracy0.7721
a3Estimated accuracy0.7976
a4Estimated accuracy0.6730
a5Estimated accuracy0.5984
a6Estimated accuracy0.9187
a1Agrees with consensus0.8652
a2Agrees with consensus0.7753
a3Agrees with consensus0.7978
a4Agrees with consensus0.6667
a5Agrees with consensus0.5978
a6Agrees with consensus0.9432
How each annotator labels each true classHow does each annotator label items of each true class?
View data
AnnotatorLabel givenTrue classProbability
a1positivepositive0.8695
a1neutralpositive0.1161
a1negativepositive0.0144
a1positiveneutral0.0957
a1neutralneutral0.8899
a1negativeneutral0.0144
a1positivenegative0.0957
a1neutralnegative0.1161
a1negativenegative0.7882
a2positivepositive0.7070
a2neutralpositive0.2305
a2negativepositive0.0625
a2positiveneutral0.0456
a2neutralneutral0.8919
a2negativeneutral0.0625
a2positivenegative0.0456
a2neutralnegative0.2305
a2negativenegative0.7239
a3positivepositive0.7443
a3neutralpositive0.2269
a3negativepositive0.0288
a3positiveneutral0.0268
a3neutralneutral0.9444
a3negativeneutral0.0288
a3positivenegative0.0268
a3neutralnegative0.2269
a3negativenegative0.7464
a4positivepositive0.7096
a4neutralpositive0.1290
a4negativepositive0.1614
a4positiveneutral0.2079
a4neutralneutral0.6307
a4negativeneutral0.1614
a4positivenegative0.2079
a4neutralnegative0.1290
a4negativenegative0.6631
a5positivepositive0.6070
a5neutralpositive0.1781
a5negativepositive0.2149
a5positiveneutral0.2064
a5neutralneutral0.5787
a5negativeneutral0.2149
a5positivenegative0.2064
a5neutralnegative0.1781
a5negativenegative0.6155
a6positivepositive0.9276
a6neutralpositive0.0722
a6negativepositive0.0002
a6positiveneutral0.0530
a6neutralneutral0.9468
a6negativeneutral0.0002
a6positivenegative0.0530
a6neutralnegative0.0722
a6negativenegative0.8748
Confidence in each item's consensus labelHow is one numeric variable distributed?
View data
Confidence
0.8148
1.0000
0.9999
1.0000
0.9957
0.9984
0.7806
0.9889
0.9685
0.9999
0.9750
0.9952
1.0000
0.9997
0.9438
0.9986
0.9445
0.9968
1.0000
0.9259
0.9493
0.9997
0.9926
0.9632
0.8947
0.8194
0.9949
0.9873
0.9829
1.0000
0.9638
1.0000
0.9997
0.9998
0.9997
0.9982
0.9682
0.9999
1.0000
0.9987
0.9994
0.9999
0.9995
0.9995
0.9089
0.9998
1.0000
0.9951
1.0000
1.0000
0.9999
0.8573
0.5119
0.9984
1.0000
0.9958
0.9954
0.9921
0.5497
0.9619

First 60 of 120 rows.

Assumptions

  • Annotators overlap — 100% of items have two or more labels.
  • Every class has items — Every class has at least 5 expected items.
  • Convergence — EM converged after 59 iterations.
  • Annotators label independently — No pair agrees more than 15 points above what independent labeling would give.

Annotators

AnnotatorLabelsEstimated accuracyAgrees with consensusCompetence (θ)
a18985.4%86.5%77.4%
a28977.2%77.5%66.1%
a38979.8%79.8%71.8%
a48767.3%66.7%50.2%
a59259.8%59.8%40.1%
a68891.9%94.3%87.5%

Labels

LabelEstimated shareItems (consensus)Items (majority vote)
positive45.0%5659
neutral29.8%3536
negative25.1%2925

Least certain items

ItemConsensusConfidenceMajority voteLabels
t053positive51.2%neutral4
t059neutral55.0%positive3
t098positive61.0%positive4
t119negative64.8%neutral4
t120neutral71.4%neutral4
t090positive72.1%positive4
t064positive75.0%positive4
t067neutral75.9%neutral3
t007neutral78.1%neutral6
t001positive81.5%positive4
t026positive81.9%positive3
t052positive85.7%positive3
t062neutral88.5%neutral3
t025positive89.5%positive4
t045positive90.9%positive3
t081neutral92.2%neutral6
t020positive92.6%positive5
t071positive94.4%positive3
t015negative94.4%negative3
t017positive94.5%positive4
t021positive94.9%positive4
t060positive96.2%positive5
t024neutral96.3%neutral3
t031positive96.4%positive6
t037neutral96.8%neutral5

Pairs that agree more than independent labeling would

AnnotatorWithShared itemsObserved agreementExpected if independentExcess
a4a66567.7%62.5%0.0516
a3a46660.6%57.2%0.0342
a2a57052.9%49.9%0.0299
a1a26668.2%66.2%0.0200
a1a66780.6%78.8%0.0183
a4a56949.3%47.5%0.0176
a5a66855.9%54.4%0.0150
a1a36768.7%67.2%0.0143
a1a46761.2%61.3%−0.0011
a2a36163.9%64.1%−0.0017
  • EM from the majority vote; smoothing 0.01. Estimated accuracy is the expected share of an annotator's labels that match the true class. A low value is a statistical pattern, not a judgment of the person.
The exact R script · R R version 4.5.1 (2025-06-13)
# Annotator models (Dawid–Skene, GLAD, MACE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method agreement.dawid_skene 1.0.0 · spec a43d18d5110b9afc
# Dataset: annotations_sim (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/annotations_sim.parquet", col_select = c("item", "annotator", "label")))
n_input <- nrow(df)
df[["item"]] <- factor(df[["item"]], levels = c("t001", "t002", "t003", "t004", "t005", "t006", "t007", "t008", "t009", "t010", "t011", "t012", "t013", "t014", "t015", "t016", "t017", "t018", "t019", "t020", "t021", "t022", "t023", "t024", "t025", "t026", "t027", "t028", "t029", "t030", "t031", "t032", "t033", "t034", "t035", "t036", "t037", "t038", "t039", "t040", "t041", "t042", "t043", "t044", "t045", "t046", "t047", "t048", "t049", "t050", "t051", "t052", "t053", "t054", "t055", "t056", "t057", "t058", "t059", "t060", "t061", "t062", "t063", "t064", "t065", "t066", "t067", "t068", "t069", "t070", "t071", "t072", "t073", "t074", "t075", "t076", "t077", "t078", "t079", "t080", "t081", "t082", "t083", "t084", "t085", "t086", "t087", "t088", "t089", "t090", "t091", "t092", "t093", "t094", "t095", "t096", "t097", "t098", "t099", "t100", "t101", "t102", "t103", "t104", "t105", "t106", "t107", "t108", "t109", "t110", "t111", "t112", "t113", "t114", "t115", "t116", "t117", "t118", "t119", "t120"))  # stored level order
df[["annotator"]] <- factor(df[["annotator"]], levels = c("a1", "a2", "a3", "a4", "a5", "a6"))  # stored level order
df[["label"]] <- factor(df[["label"]], levels = c("positive", "neutral", "negative"))  # stored level order
df <- df[stats::complete.cases(df[c("item", "annotator", "label")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("item", "annotator", "label"))  # infinite values stop the run (registry/errors.yaml)

# %% Codes (one row per label: item, annotator, label)
item_col <- "item"
annot_col <- "annotator"
label_col <- "label"
items <- levels(df[[item_col]])
annots <- levels(df[[annot_col]])
labels <- levels(df[[label_col]])
n <- length(items)
m <- length(annots)
k <- length(labels)
model <- "mace"
if (n < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = item_col, min = 2, k = n)
if (m < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = annot_col, min = 2, k = m)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = label_col, min = 2, k = k)
if (model == "glad" && k != 2) cs_error("CS_E_GROUP_COUNT", column = label_col, expected = 2, k = k)
item <- as.integer(df[[item_col]])
annot <- as.integer(df[[annot_col]])
label <- as.integer(df[[label_col]])
if (!any(tabulate(item, n) >= 2)) cs_error("CS_E_UNDEFINED", what = "Annotator error rates", reason = "every item has a single label; the models learn from items that two or more annotators labeled")

# %% Fit
smoothing <- 0.01
restarts <- as.integer(0)
seed <- as.integer(1)
fit <- cs_annotator_model(item, annot, label, n, m, k, model = model, smoothing = smoothing, restarts = restarts, seed = seed)
summ <- cs_annotator_summary(fit, item, annot, label, n, m, k, smoothing = smoothing)
mv <- cs_annotator_majority_vote(item, label, n, k)
T <- fit$T
consensus <- summ$consensus
confidence <- summ$confidence
model_label <- c(dawid_skene = "Dawid–Skene", glad = "GLAD", mace = "MACE")[[model]]
per_item <- tabulate(item, n)
pairs <- summ$pairs
if (length(pairs)) {
  pm <- do.call(rbind, pairs)
  pm <- pm[order(-pm[, 6], pm[, 1], pm[, 2]), , drop = FALSE]
} else pm <- matrix(numeric(0), 0, 6)
max_excess <- if (nrow(pm)) pm[1, 6] else NA_real_

values <- list(
  n_items = n, n_annotators = m, n_labels = length(item), k = k,
  loglik = fit$loglik, iterations = fit$iterations, converged = if (fit$converged) 1 else 0,
  mean_confidence = mean(confidence), share_uncertain = mean(confidence < 0.8),
  agree_majority = mean(consensus == mv), max_pair_excess = max_excess,
  model_label = model_label
)
share <- colMeans(T)
for (c0 in seq_len(k)) values[[sprintf("share[%s]", labels[c0])]] <- share[c0]
ann_rows <- list()
for (j in seq_len(m)) {
  a <- annots[j]
  values[[sprintf("accuracy[%s]", a)]] <- summ$accuracy[j]
  values[[sprintf("agreement[%s]", a)]] <- summ$agreement[j]
  row <- list(annotator = a, labels = as.integer(summ$n_labels[j]), accuracy = summ$accuracy[j], agreement = summ$agreement[j])
  if (model == "glad") values[[sprintf("ability[%s]", a)]] <- row$ability <- fit$par$ability[j]
  if (model == "mace") values[[sprintf("competence[%s]", a)]] <- row$competence <- fit$par$competence[j]
  ann_rows[[j]] <- row
}

# %% Assumptions
shared <- vapply(seq_len(m), function(j) any(item[annot != j] %in% unique(item[annot == j])), logical(1))
multi <- mean(per_item >= 2)
alone <- annots[!shared]
support <- colSums(T)
thin <- labels[support < 5]
flagged <- if (nrow(pm)) pm[pm[, 3] >= 20 & pm[, 6] > 0.15, , drop = FALSE] else pm
pct0 <- function(x) sprintf("%.0f%%", 100 * x)
assumptions <- list(
  list(key = "overlap", label = "Annotators overlap", status = if (length(alone) || multi < 0.5) "warn" else "pass",
       detail = paste0(if (length(alone)) sprintf("No shared items for: %s — their error rates rest on the model alone. ", paste(alone, collapse = ", ")) else "",
                       sprintf("%s of items have two or more labels.", pct0(multi)))),
  list(key = "class_support", label = "Every class has items", status = if (length(thin)) "warn" else "pass",
       detail = if (length(thin)) sprintf("Fewer than 5 expected items in: %s.", paste(thin, collapse = ", ")) else "Every class has at least 5 expected items."),
  list(key = "convergence", label = "Convergence", status = if (fit$converged) "pass" else "warn",
       detail = sprintf("EM %s after %d iterations.", if (fit$converged) "converged" else "stopped before converging", fit$iterations)),
  list(key = "conditional_independence", label = "Annotators label independently",
       status = if (nrow(flagged)) "warn" else if (nrow(pm)) "pass" else "info",
       detail = if (nrow(flagged)) sprintf("%s and %s agree on %s of %d shared items; independent labeling would give %s. Copied or shared labels make the consensus overconfident.",
                                          annots[flagged[1, 1]], annots[flagged[1, 2]], pct0(flagged[1, 4]), as.integer(flagged[1, 3]), pct0(flagged[1, 5]))
                else if (nrow(pm)) "No pair agrees more than 15 points above what independent labeling would give." else "Too few shared items to compare pairs of annotators.")
)
if (!fit$converged) warnings <- c(warnings, cs_warning("CS_W_NO_CONVERGENCE", what = model_label))

# %% Tables
ord <- order(confidence, seq_len(n))[seq_len(min(25, n))]
item_rows <- lapply(ord, function(i) list(item = items[i], consensus = labels[consensus[i]], confidence = confidence[i],
                                          majority = labels[mv[i]], labels = per_item[i]))
class_rows <- lapply(seq_len(k), function(c0) list(label = labels[c0], share = share[c0], consensus = sum(consensus == c0),
                                                   majority = sum(mv == c0)))
pair_rows <- lapply(seq_len(min(10, nrow(pm))), function(r) list(a = annots[pm[r, 1]], b = annots[pm[r, 2]], shared = as.integer(pm[r, 3]),
                                                                 observed = pm[r, 4], expected = pm[r, 5], excess = pm[r, 6]))
ann_cols <- list(list(key = "annotator", label = "Annotator", type = "string"), list(key = "labels", label = "Labels", type = "integer"),
                 list(key = "accuracy", label = "Estimated accuracy", type = "percent"),
                 list(key = "agreement", label = "Agrees with consensus", type = "percent"))
if (model == "glad") ann_cols[[length(ann_cols) + 1]] <- list(key = "ability", label = "Ability (α)", type = "number")
if (model == "mace") ann_cols[[length(ann_cols) + 1]] <- list(key = "competence", label = "Competence (θ)", type = "percent")
tables <- list(
  list(key = "annotators", title = "Annotators", columns = ann_cols, rows = ann_rows),
  list(key = "classes", title = "Labels", columns = list(
    list(key = "label", label = "Label", type = "string"), list(key = "share", label = "Estimated share", type = "percent"),
    list(key = "consensus", label = "Items (consensus)", type = "integer"), list(key = "majority", label = "Items (majority vote)", type = "integer")
  ), rows = class_rows),
  list(key = "uncertain", title = "Least certain items", columns = list(
    list(key = "item", label = "Item", type = "string"), list(key = "consensus", label = "Consensus", type = "string"),
    list(key = "confidence", label = "Confidence", type = "percent"), list(key = "majority", label = "Majority vote", type = "string"),
    list(key = "labels", label = "Labels", type = "integer")
  ), rows = item_rows)
)
if (length(pair_rows)) tables[[length(tables) + 1]] <- list(key = "pairs", title = "Pairs that agree more than independent labeling would", columns = list(
  list(key = "a", label = "Annotator", type = "string"), list(key = "b", label = "With", type = "string"),
  list(key = "shared", label = "Shared items", type = "integer"), list(key = "observed", label = "Observed agreement", type = "percent"),
  list(key = "expected", label = "Expected if independent", type = "percent"), list(key = "excess", label = "Excess", type = "number")
), rows = pair_rows)

# %% Charts
charts <- list(cs_chart("annotators", "cleveland-dot", "Annotators: estimated accuracy and agreement with the consensus", list(
  category = cs_col("Annotator", c(annots, annots), "categorical", levels = annots),
  value = cs_col("Share", c(summ$accuracy, summ$agreement), "numeric"),
  group = cs_col("Measure", rep(c("Estimated accuracy", "Agrees with consensus"), each = m), "categorical",
                 levels = c("Estimated accuracy", "Agrees with consensus"))
), controls = list(top = min(30, max(3, m)), sort = "value")))
if (model %in% c("dawid_skene", "mace")) {
  if (model == "dawid_skene") {
    cm <- fit$par$theta
  } else {
    cm <- array(0, dim = c(m, k, k))
    for (c0 in seq_len(k)) {
      cm[, c0, ] <- (1 - fit$par$competence) * fit$par$spam
      cm[, c0, c0] <- cm[, c0, c0] + fit$par$competence
    }
  }
  grid <- expand.grid(l = seq_len(k), c = seq_len(k), j = seq_len(m))
  charts[[length(charts) + 1]] <- cs_chart("confusion", "annotator-confusion", "How each annotator labels each true class", list(
    annotator = cs_col("Annotator", annots[grid$j], "categorical", levels = annots),
    truth = cs_col("True class", labels[grid$c], "categorical", levels = labels),
    given = cs_col("Label given", labels[grid$l], "categorical", levels = labels),
    value = cs_col("Probability", cm[cbind(grid$j, grid$c, grid$l)], "numeric")
  ))
}
charts[[length(charts) + 1]] <- cs_chart("confidence", "histogram", "Confidence in each item's consensus label", list(
  x = cs_col("Confidence", confidence, "numeric")
), controls = list(scale = "count", kde = FALSE))

# %% Result
cs_publish(list(
  method = "agreement.dawid_skene",
  methodVersion = "1.0.0",
  title = sprintf("Annotator model (%s)", model_label),
  engine = cs_engine_info("stats", "codesplashr"),
  n = length(item),
  summary = sprintf("%s for %d labels from %d annotators on %d items: the consensus matches the majority vote on %s of items, with mean confidence %.2f.",
                    model_label, length(item), m, n, pct0(values$agree_majority), values$mean_confidence),
  apa = sprintf("%s model, %d annotators, %d items, %d labels; log-likelihood = %s", model_label, m, n, length(item), cs_fmt_num(fit$loglik, 2)),
  statistics = list(list(key = "mean_confidence", label = "Mean confidence", value = values$mean_confidence),
                    list(key = "agree_majority", label = "Matches majority vote", value = values$agree_majority, format = "percent"),
                    list(key = "loglik", label = "Log-likelihood", value = values$loglik)),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("EM from the majority vote%s; smoothing %s. Estimated accuracy is the expected share of an annotator's labels that match the true class. A low value is a statistical pattern, not a judgment of the person.",
                       if (restarts > 0) sprintf(" plus %d random restarts", restarts) else "", format(smoothing))),
  charts = charts,
  values = values
))
Python

MACE model, 6 annotators, 120 items, 534 labels; log-likelihood = −454.00

Mean confidence
0.9608
Matches majority vote
95.0%
Log-likelihood
−454.00

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Annotators overlap — 100% of items have two or more labels.
  • Every class has items — Every class has at least 5 expected items.
  • Convergence — EM converged after 59 iterations.
  • Annotators label independently — No pair agrees more than 15 points above what independent labeling would give.

Annotators

AnnotatorLabelsEstimated accuracyAgrees with consensusCompetence (θ)
a18985.4%86.5%77.4%
a28977.2%77.5%66.1%
a38979.8%79.8%71.8%
a48767.3%66.7%50.2%
a59259.8%59.8%40.1%
a68891.9%94.3%87.5%

Labels

LabelEstimated shareItems (consensus)Items (majority vote)
positive45.0%5659
neutral29.8%3536
negative25.1%2925

Least certain items

ItemConsensusConfidenceMajority voteLabels
t053positive51.2%neutral4
t059neutral55.0%positive3
t098positive61.0%positive4
t119negative64.8%neutral4
t120neutral71.4%neutral4
t090positive72.1%positive4
t064positive75.0%positive4
t067neutral75.9%neutral3
t007neutral78.1%neutral6
t001positive81.5%positive4
t026positive81.9%positive3
t052positive85.7%positive3
t062neutral88.5%neutral3
t025positive89.5%positive4
t045positive90.9%positive3
t081neutral92.2%neutral6
t020positive92.6%positive5
t071positive94.4%positive3
t015negative94.4%negative3
t017positive94.5%positive4
t021positive94.9%positive4
t060positive96.2%positive5
t024neutral96.3%neutral3
t031positive96.4%positive6
t037neutral96.8%neutral5

Pairs that agree more than independent labeling would

AnnotatorWithShared itemsObserved agreementExpected if independentExcess
a4a66567.7%62.5%0.0516
a3a46660.6%57.2%0.0342
a2a57052.9%49.9%0.0299
a1a26668.2%66.2%0.0200
a1a66780.6%78.8%0.0183
a4a56949.3%47.5%0.0176
a5a66855.9%54.4%0.0150
a1a36768.7%67.2%0.0143
a1a46761.2%61.3%−0.0011
a2a36163.9%64.1%−0.0017
  • EM from the majority vote; smoothing 0.01. Estimated accuracy is the expected share of an annotator's labels that match the true class. A low value is a statistical pattern, not a judgment of the person.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Annotator models (Dawid–Skene, GLAD, MACE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method agreement.dawid_skene 1.0.0 · spec a43d18d5110b9afc
# Dataset: annotations_sim (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.stats import annotators as an  # Dawid–Skene, GLAD, MACE (twin of R's cs_annotator_model)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/annotations_sim.parquet", columns=["item", "annotator", "label"])
n_input = len(df)
df["item"] = pd.Categorical(df["item"], categories=["t001", "t002", "t003", "t004", "t005", "t006", "t007", "t008", "t009", "t010", "t011", "t012", "t013", "t014", "t015", "t016", "t017", "t018", "t019", "t020", "t021", "t022", "t023", "t024", "t025", "t026", "t027", "t028", "t029", "t030", "t031", "t032", "t033", "t034", "t035", "t036", "t037", "t038", "t039", "t040", "t041", "t042", "t043", "t044", "t045", "t046", "t047", "t048", "t049", "t050", "t051", "t052", "t053", "t054", "t055", "t056", "t057", "t058", "t059", "t060", "t061", "t062", "t063", "t064", "t065", "t066", "t067", "t068", "t069", "t070", "t071", "t072", "t073", "t074", "t075", "t076", "t077", "t078", "t079", "t080", "t081", "t082", "t083", "t084", "t085", "t086", "t087", "t088", "t089", "t090", "t091", "t092", "t093", "t094", "t095", "t096", "t097", "t098", "t099", "t100", "t101", "t102", "t103", "t104", "t105", "t106", "t107", "t108", "t109", "t110", "t111", "t112", "t113", "t114", "t115", "t116", "t117", "t118", "t119", "t120"])  # stored level order
df["annotator"] = pd.Categorical(df["annotator"], categories=["a1", "a2", "a3", "a4", "a5", "a6"])  # stored level order
df["label"] = pd.Categorical(df["label"], categories=["positive", "neutral", "negative"])  # stored level order
df = df.dropna(subset=["item", "annotator", "label"])  # listwise deletion over the analysis columns
df["item"] = df["item"].cat.remove_unused_categories()
df["annotator"] = df["annotator"].cat.remove_unused_categories()
df["label"] = df["label"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["item", "annotator", "label"])  # infinite values stop the run (registry/errors.yaml)

# %% Codes (one row per label: item, annotator, label)
item_col, annot_col, label_col = "item", "annotator", "label"
items = [str(x) for x in df[item_col].cat.categories]
annots = [str(x) for x in df[annot_col].cat.categories]
labels = [str(x) for x in df[label_col].cat.categories]
n, m, k = len(items), len(annots), len(labels)
model = "mace"
if n < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=item_col, min=2, k=n)
if m < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=annot_col, min=2, k=m)
if k < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=label_col, min=2, k=k)
if model == "glad" and k != 2:
    cs.cs_error("CS_E_GROUP_COUNT", column=label_col, expected=2, k=k)
item = df[item_col].cat.codes.to_numpy(dtype=np.int64)
annot = df[annot_col].cat.codes.to_numpy(dtype=np.int64)
label = df[label_col].cat.codes.to_numpy(dtype=np.int64)
if not np.any(np.bincount(item, minlength=n) >= 2):
    cs.cs_error("CS_E_UNDEFINED", what="Annotator error rates", reason="every item has a single label; the models learn from items that two or more annotators labeled")

# %% Fit
smoothing = 0.01
restarts = int(0)
seed = int(1)
fit = an.annotator_model(item, annot, label, n, m, k, model=model, smoothing=smoothing, restarts=restarts, seed=seed)
summ = an.annotator_summary(fit, item, annot, label, n, m, k, smoothing=smoothing)
mv = an.majority_vote(item, label, n, k)
T = fit["T"]
consensus, confidence = summ["consensus"], summ["confidence"]
model_label = {"dawid_skene": "Dawid–Skene", "glad": "GLAD", "mace": "MACE"}[model]
per_item = np.bincount(item, minlength=n)
pairs = sorted(summ["pairs"], key=lambda r: (-r[5], r[0], r[1]))
max_excess = pairs[0][5] if pairs else None

values = {
    "n_items": float(n), "n_annotators": float(m), "n_labels": float(len(item)), "k": float(k),
    "loglik": float(fit["loglik"]), "iterations": float(fit["iterations"]), "converged": 1.0 if fit["converged"] else 0.0,
    "mean_confidence": float(np.mean(confidence)), "share_uncertain": float(np.mean(confidence < 0.8)),
    "agree_majority": float(np.mean(consensus == mv)), "max_pair_excess": None if max_excess is None else float(max_excess),
    "model_label": model_label,
}
share = T.mean(axis=0)
for c, lab in enumerate(labels):
    values[f"share[{lab}]"] = float(share[c])
ann_rows = []
for j, a in enumerate(annots):
    values[f"accuracy[{a}]"] = float(summ["accuracy"][j])
    values[f"agreement[{a}]"] = float(summ["agreement"][j])
    row = {"annotator": a, "labels": int(summ["n_labels"][j]), "accuracy": float(summ["accuracy"][j]),
           "agreement": float(summ["agreement"][j])}
    if model == "glad":
        values[f"ability[{a}]"] = row["ability"] = float(fit["par"]["ability"][j])
    if model == "mace":
        values[f"competence[{a}]"] = row["competence"] = float(fit["par"]["competence"][j])
    ann_rows.append(row)

# %% Assumptions
shared = np.zeros(m, dtype=bool)
for j in range(m):
    its = np.unique(item[annot == j])
    shared[j] = bool(np.any(np.isin(item[annot != j], its)))
multi = float(np.mean(per_item >= 2))
alone = [annots[j] for j in range(m) if not shared[j]]
support = T.sum(axis=0)
thin = [labels[c] for c in range(k) if support[c] < 5]
flagged = [p for p in pairs if p[2] >= 20 and p[5] > 0.15]
assumptions = [
    {"key": "overlap", "label": "Annotators overlap", "status": "warn" if (alone or multi < 0.5) else "pass",
     "detail": (f"No shared items for: {', '.join(alone)} — their error rates rest on the model alone. " if alone else "")
     + f"{multi:.0%} of items have two or more labels."},
    {"key": "class_support", "label": "Every class has items", "status": "warn" if thin else "pass",
     "detail": f"Fewer than 5 expected items in: {', '.join(thin)}." if thin else "Every class has at least 5 expected items."},
    {"key": "convergence", "label": "Convergence", "status": "pass" if fit["converged"] else "warn",
     "detail": f"EM {'converged' if fit['converged'] else 'stopped before converging'} after {fit['iterations']} iterations."},
    {"key": "conditional_independence", "label": "Annotators label independently",
     "status": "warn" if flagged else ("pass" if pairs else "info"),
     "detail": (f"{annots[flagged[0][0]]} and {annots[flagged[0][1]]} agree on {flagged[0][3]:.0%} of {flagged[0][2]} shared items; independent labeling would give {flagged[0][4]:.0%}. Copied or shared labels make the consensus overconfident."
                if flagged else ("No pair agrees more than 15 points above what independent labeling would give." if pairs else "Too few shared items to compare pairs of annotators."))},
]
if not fit["converged"]:
    warnings.append(cs.cs_warning("CS_W_NO_CONVERGENCE", what=model_label))

# %% Tables
order = np.lexsort((np.arange(n), confidence))[:25]
item_rows = [{"item": items[i], "consensus": labels[consensus[i]], "confidence": float(confidence[i]),
              "majority": labels[mv[i]], "labels": int(per_item[i])} for i in order]
class_rows = [{"label": labels[c], "share": float(share[c]), "consensus": int(np.sum(consensus == c)),
               "majority": int(np.sum(mv == c))} for c in range(k)]
pair_rows = [{"a": annots[p[0]], "b": annots[p[1]], "shared": int(p[2]), "observed": float(p[3]), "expected": float(p[4]),
              "excess": float(p[5])} for p in pairs[:10]]
ann_cols = [{"key": "annotator", "label": "Annotator", "type": "string"}, {"key": "labels", "label": "Labels", "type": "integer"},
            {"key": "accuracy", "label": "Estimated accuracy", "type": "percent"},
            {"key": "agreement", "label": "Agrees with consensus", "type": "percent"}]
if model == "glad":
    ann_cols.append({"key": "ability", "label": "Ability (α)", "type": "number"})
if model == "mace":
    ann_cols.append({"key": "competence", "label": "Competence (θ)", "type": "percent"})
tables = [
    {"key": "annotators", "title": "Annotators", "columns": ann_cols, "rows": ann_rows},
    {"key": "classes", "title": "Labels", "columns": [
        {"key": "label", "label": "Label", "type": "string"}, {"key": "share", "label": "Estimated share", "type": "percent"},
        {"key": "consensus", "label": "Items (consensus)", "type": "integer"}, {"key": "majority", "label": "Items (majority vote)", "type": "integer"},
    ], "rows": class_rows},
    {"key": "uncertain", "title": "Least certain items", "columns": [
        {"key": "item", "label": "Item", "type": "string"}, {"key": "consensus", "label": "Consensus", "type": "string"},
        {"key": "confidence", "label": "Confidence", "type": "percent"}, {"key": "majority", "label": "Majority vote", "type": "string"},
        {"key": "labels", "label": "Labels", "type": "integer"},
    ], "rows": item_rows},
]
if pair_rows:
    tables.append({"key": "pairs", "title": "Pairs that agree more than independent labeling would", "columns": [
        {"key": "a", "label": "Annotator", "type": "string"}, {"key": "b", "label": "With", "type": "string"},
        {"key": "shared", "label": "Shared items", "type": "integer"}, {"key": "observed", "label": "Observed agreement", "type": "percent"},
        {"key": "expected", "label": "Expected if independent", "type": "percent"}, {"key": "excess", "label": "Excess", "type": "number"},
    ], "rows": pair_rows})

# %% Charts
charts = [cs.chart("annotators", "cleveland-dot", "Annotators: estimated accuracy and agreement with the consensus", {
    "category": cs.col("Annotator", annots + annots, "categorical", levels=annots),
    "value": cs.col("Share", [float(x) for x in summ["accuracy"]] + [float(x) for x in summ["agreement"]], "numeric"),
    "group": cs.col("Measure", ["Estimated accuracy"] * m + ["Agrees with consensus"] * m, "categorical",
                    levels=["Estimated accuracy", "Agrees with consensus"]),
}, controls={"top": min(30, max(3, m)), "sort": "value"})]
if model in ("dawid_skene", "mace"):
    if model == "dawid_skene":
        cm = fit["par"]["theta"]
    else:
        th, sp = fit["par"]["competence"], fit["par"]["spam"]
        cm = (1.0 - th)[:, None, None] * np.repeat(sp[:, None, :], k, axis=1)
        cm[:, np.arange(k), np.arange(k)] += th[:, None]
    charts.append(cs.chart("confusion", "annotator-confusion", "How each annotator labels each true class", {
        "annotator": cs.col("Annotator", [a for a in annots for _ in range(k * k)], "categorical", levels=annots),
        "truth": cs.col("True class", [labels[c] for _ in annots for c in range(k) for _ in range(k)], "categorical", levels=labels),
        "given": cs.col("Label given", [labels[l] for _ in annots for _ in range(k) for l in range(k)], "categorical", levels=labels),
        "value": cs.col("Probability", [float(cm[j, c, l]) for j in range(m) for c in range(k) for l in range(k)], "numeric"),
    }))
charts.append(cs.chart("confidence", "histogram", "Confidence in each item's consensus label", {
    "x": cs.col("Confidence", [float(x) for x in confidence], "numeric"),
}, controls={"scale": "count", "kde": False}))

# %% Result
cs.publish({
    "method": "agreement.dawid_skene",
    "methodVersion": "1.0.0",
    "title": f"Annotator model ({model_label})",
    "engine": cs.engine_info("numpy", "codesplash"),
    "n": int(len(item)),
    "summary": f"{model_label} for {len(item)} labels from {m} annotators on {n} items: the consensus matches the majority vote on {values['agree_majority']:.0%} of items, with mean confidence {values['mean_confidence']:.2f}.",
    "apa": f"{model_label} model, {m} annotators, {n} items, {len(item)} labels; log-likelihood = {cs.fmt_num(fit['loglik'], 2)}",
    "statistics": [{"key": "mean_confidence", "label": "Mean confidence", "value": values["mean_confidence"]},
                   {"key": "agree_majority", "label": "Matches majority vote", "value": values["agree_majority"], "format": "percent"},
                   {"key": "loglik", "label": "Log-likelihood", "value": values["loglik"]}],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"EM from the majority vote{f' plus {restarts} random restarts' if restarts else ''}; smoothing {smoothing:g}. Estimated accuracy is the expected share of an annotator's labels that match the true class. A low value is a statistical pattern, not a judgment of the person."],
    "charts": charts,
    "values": values,
})
06

The assumption that bites: independent annotators

In the app

Every one of these models assumes annotators make their errors independently, given the true class. If one annotator copies another, or two AI judges come from the same model family, their agreement looks like strong evidence and the model trusts them both.

In this version of the data, annotator a6 copies a1 on most of the items they share. Mean confidence rises to 0.99, and a1 and a6 now look almost perfect. The consensus is more confident, not more correct: against the simulated true labels it gets worse.

07

Checking for copied labels

In the app

The copied-annotator check refits the model without each annotator and asks how often each pair would agree if they labeled independently. Here a1 and a6 agree more often than that by 0.31 (as a share of their shared items), far more than the check allows, so the independence row warns.

Annotator model (Dawid–Skene)Recorded · Python and R agreeRecorded 2026-11-21 · 27 values compared
R

Dawid–Skene model, 6 annotators, 120 items, 534 labels; log-likelihood = −428.04

Mean confidence
0.9876
Matches majority vote
92.5%
Log-likelihood
−428.04

Plots

Annotators: estimated accuracy and agreement with the consensusHow do categories compare on one value — and across up to three groups?
View data
AnnotatorMeasureShare
a1Estimated accuracy0.9999
a2Estimated accuracy0.6866
a3Estimated accuracy0.7152
a4Estimated accuracy0.6249
a5Estimated accuracy0.5328
a6Estimated accuracy0.9925
a1Agrees with consensus1
a2Agrees with consensus0.6966
a3Agrees with consensus0.7303
a4Agrees with consensus0.6207
a5Agrees with consensus0.5435
a6Agrees with consensus0.9886
How each annotator labels each true classHow does each annotator label items of each true class?
View data
AnnotatorLabel givenTrue classProbability
a1positivepositive0.9994
a1neutralpositive0.0003
a1negativepositive0.0003
a1positiveneutral0.0004
a1neutralneutral0.9993
a1negativeneutral0.0003
a1positivenegative0.0005
a1neutralnegative0.0008
a1negativenegative0.9986
a2positivepositive0.6800
a2neutralpositive0.2397
a2negativepositive0.0803
a2positiveneutral0.1169
a2neutralneutral0.7747
a2negativeneutral0.1084
a2positivenegative0.0458
a2neutralnegative0.3744
a2negativenegative0.5798
a3positivepositive0.6987
a3neutralpositive0.2738
a3negativepositive0.0275
a3positiveneutral0.1254
a3neutralneutral0.7238
a3negativeneutral0.1509
a3positivenegative0.0005
a3neutralnegative0.2644
a3negativenegative0.7351
a4positivepositive0.7006
a4neutralpositive0.1632
a4negativepositive0.1361
a4positiveneutral0.2309
a4neutralneutral0.5194
a4negativeneutral0.2497
a4positivenegative0.2012
a4neutralnegative0.1514
a4negativenegative0.6475
a5positivepositive0.5270
a5neutralpositive0.2244
a5negativepositive0.2486
a5positiveneutral0.2487
a5neutralneutral0.5161
a5negativeneutral0.2352
a5positivenegative0.2377
a5neutralnegative0.1823
a5negativenegative0.5801
a6positivepositive0.9825
a6neutralpositive0.0172
a6negativepositive0.0003
a6positiveneutral0.0009
a6neutralneutral0.9988
a6negativeneutral0.0004
a6positivenegative0.0006
a6neutralnegative0.0005
a6negativenegative0.9989
Confidence in each item's consensus labelHow is one numeric variable distributed?
View data
Confidence
0.9984
1.0000
1.0000
1.0000
1.0000
0.9898
1.0000
0.9960
1.0000
1.0000
1.0000
1.0000
1.0000
1.0000
0.7837
0.9929
0.9999
1.0000
1.0000
0.9995
0.9998
0.9995
0.9971
0.8998
0.9993
0.9995
1.0000
0.9777
0.9992
1.0000
0.9999
1.0000
1.0000
1.0000
1.0000
0.9997
1.0000
1.0000
1.0000
1.0000
0.9996
1.0000
1.0000
1.0000
1.0000
1.0000
1.0000
1.0000
1.0000
1.0000
1.0000
0.9997
0.9900
1.0000
1.0000
1.0000
1.0000
0.9999
0.9974
1.0000

First 60 of 120 rows.

Assumptions

  • Annotators overlap — 100% of items have two or more labels.
  • Every class has items — Every class has at least 5 expected items.
  • Convergence — EM converged after 50 iterations.
  • Annotators label independently — a1 and a6 agree on 100% of 67 shared items; independent labeling would give 69%. Copied or shared labels make the consensus overconfident.

Annotators

AnnotatorLabelsEstimated accuracyAgrees with consensus
a189100.0%100.0%
a28968.7%69.7%
a38971.5%73.0%
a48762.5%62.1%
a59253.3%54.3%
a68899.3%98.9%

Labels

LabelEstimated shareItems (consensus)Items (majority vote)
positive46.4%5659
neutral32.8%3937
negative20.7%2524

Least certain items

ItemConsensusConfidenceMajority voteLabels
t109positive62.6%positive4
t067neutral72.5%neutral3
t015negative78.4%negative3
t111negative81.9%negative3
t071positive83.8%positive3
t024neutral90.0%neutral3
t087neutral91.6%neutral3
t028positive97.8%positive3
t006positive99.0%positive3
t072positive99.0%positive3
t053positive99.0%neutral4
t016positive99.3%positive3
t008neutral99.6%neutral3
t090positive99.7%positive4
t023neutral99.7%neutral3
t101neutral99.7%neutral3
t064positive99.7%positive4
t119neutral99.7%neutral4
t059neutral99.7%positive3
t001positive99.8%positive4
t120neutral99.9%neutral4
t085neutral99.9%neutral4
t062neutral99.9%neutral3
t029negative99.9%positive4
t073neutral99.9%neutral5

Pairs that agree more than independent labeling would

AnnotatorWithShared itemsObserved agreementExpected if independentExcess
a1a667100.0%68.9%0.3106
a2a36163.9%53.6%0.1035
a2a57052.9%42.8%0.1006
a3a46660.6%51.0%0.0960
a4a56949.3%41.9%0.0737
a3a56648.5%42.9%0.0557
a2a46549.2%48.0%0.0120
a4a66564.6%66.3%−0.0172
a1a46761.2%69.5%−0.0829
a1a36768.7%77.0%−0.0830
  • EM from the majority vote; smoothing 0.01. Estimated accuracy is the expected share of an annotator's labels that match the true class. A low value is a statistical pattern, not a judgment of the person.
The exact R script · R R version 4.5.1 (2025-06-13)
# Annotator models (Dawid–Skene, GLAD, MACE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method agreement.dawid_skene 1.0.0 · spec 7d00b6870f97a746
# Dataset: annotations_copy (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/annotations_copy.parquet", col_select = c("item", "annotator", "label")))
n_input <- nrow(df)
df[["item"]] <- factor(df[["item"]], levels = c("t001", "t002", "t003", "t004", "t005", "t006", "t007", "t008", "t009", "t010", "t011", "t012", "t013", "t014", "t015", "t016", "t017", "t018", "t019", "t020", "t021", "t022", "t023", "t024", "t025", "t026", "t027", "t028", "t029", "t030", "t031", "t032", "t033", "t034", "t035", "t036", "t037", "t038", "t039", "t040", "t041", "t042", "t043", "t044", "t045", "t046", "t047", "t048", "t049", "t050", "t051", "t052", "t053", "t054", "t055", "t056", "t057", "t058", "t059", "t060", "t061", "t062", "t063", "t064", "t065", "t066", "t067", "t068", "t069", "t070", "t071", "t072", "t073", "t074", "t075", "t076", "t077", "t078", "t079", "t080", "t081", "t082", "t083", "t084", "t085", "t086", "t087", "t088", "t089", "t090", "t091", "t092", "t093", "t094", "t095", "t096", "t097", "t098", "t099", "t100", "t101", "t102", "t103", "t104", "t105", "t106", "t107", "t108", "t109", "t110", "t111", "t112", "t113", "t114", "t115", "t116", "t117", "t118", "t119", "t120"))  # stored level order
df[["annotator"]] <- factor(df[["annotator"]], levels = c("a1", "a2", "a3", "a4", "a5", "a6"))  # stored level order
df[["label"]] <- factor(df[["label"]], levels = c("positive", "neutral", "negative"))  # stored level order
df <- df[stats::complete.cases(df[c("item", "annotator", "label")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("item", "annotator", "label"))  # infinite values stop the run (registry/errors.yaml)

# %% Codes (one row per label: item, annotator, label)
item_col <- "item"
annot_col <- "annotator"
label_col <- "label"
items <- levels(df[[item_col]])
annots <- levels(df[[annot_col]])
labels <- levels(df[[label_col]])
n <- length(items)
m <- length(annots)
k <- length(labels)
model <- "dawid_skene"
if (n < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = item_col, min = 2, k = n)
if (m < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = annot_col, min = 2, k = m)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = label_col, min = 2, k = k)
if (model == "glad" && k != 2) cs_error("CS_E_GROUP_COUNT", column = label_col, expected = 2, k = k)
item <- as.integer(df[[item_col]])
annot <- as.integer(df[[annot_col]])
label <- as.integer(df[[label_col]])
if (!any(tabulate(item, n) >= 2)) cs_error("CS_E_UNDEFINED", what = "Annotator error rates", reason = "every item has a single label; the models learn from items that two or more annotators labeled")

# %% Fit
smoothing <- 0.01
restarts <- as.integer(0)
seed <- as.integer(1)
fit <- cs_annotator_model(item, annot, label, n, m, k, model = model, smoothing = smoothing, restarts = restarts, seed = seed)
summ <- cs_annotator_summary(fit, item, annot, label, n, m, k, smoothing = smoothing)
mv <- cs_annotator_majority_vote(item, label, n, k)
T <- fit$T
consensus <- summ$consensus
confidence <- summ$confidence
model_label <- c(dawid_skene = "Dawid–Skene", glad = "GLAD", mace = "MACE")[[model]]
per_item <- tabulate(item, n)
pairs <- summ$pairs
if (length(pairs)) {
  pm <- do.call(rbind, pairs)
  pm <- pm[order(-pm[, 6], pm[, 1], pm[, 2]), , drop = FALSE]
} else pm <- matrix(numeric(0), 0, 6)
max_excess <- if (nrow(pm)) pm[1, 6] else NA_real_

values <- list(
  n_items = n, n_annotators = m, n_labels = length(item), k = k,
  loglik = fit$loglik, iterations = fit$iterations, converged = if (fit$converged) 1 else 0,
  mean_confidence = mean(confidence), share_uncertain = mean(confidence < 0.8),
  agree_majority = mean(consensus == mv), max_pair_excess = max_excess,
  model_label = model_label
)
share <- colMeans(T)
for (c0 in seq_len(k)) values[[sprintf("share[%s]", labels[c0])]] <- share[c0]
ann_rows <- list()
for (j in seq_len(m)) {
  a <- annots[j]
  values[[sprintf("accuracy[%s]", a)]] <- summ$accuracy[j]
  values[[sprintf("agreement[%s]", a)]] <- summ$agreement[j]
  row <- list(annotator = a, labels = as.integer(summ$n_labels[j]), accuracy = summ$accuracy[j], agreement = summ$agreement[j])
  if (model == "glad") values[[sprintf("ability[%s]", a)]] <- row$ability <- fit$par$ability[j]
  if (model == "mace") values[[sprintf("competence[%s]", a)]] <- row$competence <- fit$par$competence[j]
  ann_rows[[j]] <- row
}

# %% Assumptions
shared <- vapply(seq_len(m), function(j) any(item[annot != j] %in% unique(item[annot == j])), logical(1))
multi <- mean(per_item >= 2)
alone <- annots[!shared]
support <- colSums(T)
thin <- labels[support < 5]
flagged <- if (nrow(pm)) pm[pm[, 3] >= 20 & pm[, 6] > 0.15, , drop = FALSE] else pm
pct0 <- function(x) sprintf("%.0f%%", 100 * x)
assumptions <- list(
  list(key = "overlap", label = "Annotators overlap", status = if (length(alone) || multi < 0.5) "warn" else "pass",
       detail = paste0(if (length(alone)) sprintf("No shared items for: %s — their error rates rest on the model alone. ", paste(alone, collapse = ", ")) else "",
                       sprintf("%s of items have two or more labels.", pct0(multi)))),
  list(key = "class_support", label = "Every class has items", status = if (length(thin)) "warn" else "pass",
       detail = if (length(thin)) sprintf("Fewer than 5 expected items in: %s.", paste(thin, collapse = ", ")) else "Every class has at least 5 expected items."),
  list(key = "convergence", label = "Convergence", status = if (fit$converged) "pass" else "warn",
       detail = sprintf("EM %s after %d iterations.", if (fit$converged) "converged" else "stopped before converging", fit$iterations)),
  list(key = "conditional_independence", label = "Annotators label independently",
       status = if (nrow(flagged)) "warn" else if (nrow(pm)) "pass" else "info",
       detail = if (nrow(flagged)) sprintf("%s and %s agree on %s of %d shared items; independent labeling would give %s. Copied or shared labels make the consensus overconfident.",
                                          annots[flagged[1, 1]], annots[flagged[1, 2]], pct0(flagged[1, 4]), as.integer(flagged[1, 3]), pct0(flagged[1, 5]))
                else if (nrow(pm)) "No pair agrees more than 15 points above what independent labeling would give." else "Too few shared items to compare pairs of annotators.")
)
if (!fit$converged) warnings <- c(warnings, cs_warning("CS_W_NO_CONVERGENCE", what = model_label))

# %% Tables
ord <- order(confidence, seq_len(n))[seq_len(min(25, n))]
item_rows <- lapply(ord, function(i) list(item = items[i], consensus = labels[consensus[i]], confidence = confidence[i],
                                          majority = labels[mv[i]], labels = per_item[i]))
class_rows <- lapply(seq_len(k), function(c0) list(label = labels[c0], share = share[c0], consensus = sum(consensus == c0),
                                                   majority = sum(mv == c0)))
pair_rows <- lapply(seq_len(min(10, nrow(pm))), function(r) list(a = annots[pm[r, 1]], b = annots[pm[r, 2]], shared = as.integer(pm[r, 3]),
                                                                 observed = pm[r, 4], expected = pm[r, 5], excess = pm[r, 6]))
ann_cols <- list(list(key = "annotator", label = "Annotator", type = "string"), list(key = "labels", label = "Labels", type = "integer"),
                 list(key = "accuracy", label = "Estimated accuracy", type = "percent"),
                 list(key = "agreement", label = "Agrees with consensus", type = "percent"))
if (model == "glad") ann_cols[[length(ann_cols) + 1]] <- list(key = "ability", label = "Ability (α)", type = "number")
if (model == "mace") ann_cols[[length(ann_cols) + 1]] <- list(key = "competence", label = "Competence (θ)", type = "percent")
tables <- list(
  list(key = "annotators", title = "Annotators", columns = ann_cols, rows = ann_rows),
  list(key = "classes", title = "Labels", columns = list(
    list(key = "label", label = "Label", type = "string"), list(key = "share", label = "Estimated share", type = "percent"),
    list(key = "consensus", label = "Items (consensus)", type = "integer"), list(key = "majority", label = "Items (majority vote)", type = "integer")
  ), rows = class_rows),
  list(key = "uncertain", title = "Least certain items", columns = list(
    list(key = "item", label = "Item", type = "string"), list(key = "consensus", label = "Consensus", type = "string"),
    list(key = "confidence", label = "Confidence", type = "percent"), list(key = "majority", label = "Majority vote", type = "string"),
    list(key = "labels", label = "Labels", type = "integer")
  ), rows = item_rows)
)
if (length(pair_rows)) tables[[length(tables) + 1]] <- list(key = "pairs", title = "Pairs that agree more than independent labeling would", columns = list(
  list(key = "a", label = "Annotator", type = "string"), list(key = "b", label = "With", type = "string"),
  list(key = "shared", label = "Shared items", type = "integer"), list(key = "observed", label = "Observed agreement", type = "percent"),
  list(key = "expected", label = "Expected if independent", type = "percent"), list(key = "excess", label = "Excess", type = "number")
), rows = pair_rows)

# %% Charts
charts <- list(cs_chart("annotators", "cleveland-dot", "Annotators: estimated accuracy and agreement with the consensus", list(
  category = cs_col("Annotator", c(annots, annots), "categorical", levels = annots),
  value = cs_col("Share", c(summ$accuracy, summ$agreement), "numeric"),
  group = cs_col("Measure", rep(c("Estimated accuracy", "Agrees with consensus"), each = m), "categorical",
                 levels = c("Estimated accuracy", "Agrees with consensus"))
), controls = list(top = min(30, max(3, m)), sort = "value")))
if (model %in% c("dawid_skene", "mace")) {
  if (model == "dawid_skene") {
    cm <- fit$par$theta
  } else {
    cm <- array(0, dim = c(m, k, k))
    for (c0 in seq_len(k)) {
      cm[, c0, ] <- (1 - fit$par$competence) * fit$par$spam
      cm[, c0, c0] <- cm[, c0, c0] + fit$par$competence
    }
  }
  grid <- expand.grid(l = seq_len(k), c = seq_len(k), j = seq_len(m))
  charts[[length(charts) + 1]] <- cs_chart("confusion", "annotator-confusion", "How each annotator labels each true class", list(
    annotator = cs_col("Annotator", annots[grid$j], "categorical", levels = annots),
    truth = cs_col("True class", labels[grid$c], "categorical", levels = labels),
    given = cs_col("Label given", labels[grid$l], "categorical", levels = labels),
    value = cs_col("Probability", cm[cbind(grid$j, grid$c, grid$l)], "numeric")
  ))
}
charts[[length(charts) + 1]] <- cs_chart("confidence", "histogram", "Confidence in each item's consensus label", list(
  x = cs_col("Confidence", confidence, "numeric")
), controls = list(scale = "count", kde = FALSE))

# %% Result
cs_publish(list(
  method = "agreement.dawid_skene",
  methodVersion = "1.0.0",
  title = sprintf("Annotator model (%s)", model_label),
  engine = cs_engine_info("stats", "codesplashr"),
  n = length(item),
  summary = sprintf("%s for %d labels from %d annotators on %d items: the consensus matches the majority vote on %s of items, with mean confidence %.2f.",
                    model_label, length(item), m, n, pct0(values$agree_majority), values$mean_confidence),
  apa = sprintf("%s model, %d annotators, %d items, %d labels; log-likelihood = %s", model_label, m, n, length(item), cs_fmt_num(fit$loglik, 2)),
  statistics = list(list(key = "mean_confidence", label = "Mean confidence", value = values$mean_confidence),
                    list(key = "agree_majority", label = "Matches majority vote", value = values$agree_majority, format = "percent"),
                    list(key = "loglik", label = "Log-likelihood", value = values$loglik)),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("EM from the majority vote%s; smoothing %s. Estimated accuracy is the expected share of an annotator's labels that match the true class. A low value is a statistical pattern, not a judgment of the person.",
                       if (restarts > 0) sprintf(" plus %d random restarts", restarts) else "", format(smoothing))),
  charts = charts,
  values = values
))
Python

Dawid–Skene model, 6 annotators, 120 items, 534 labels; log-likelihood = −428.04

Mean confidence
0.9876
Matches majority vote
92.5%
Log-likelihood
−428.04

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Annotators overlap — 100% of items have two or more labels.
  • Every class has items — Every class has at least 5 expected items.
  • Convergence — EM converged after 50 iterations.
  • Annotators label independently — a1 and a6 agree on 100% of 67 shared items; independent labeling would give 69%. Copied or shared labels make the consensus overconfident.

Annotators

AnnotatorLabelsEstimated accuracyAgrees with consensus
a189100.0%100.0%
a28968.7%69.7%
a38971.5%73.0%
a48762.5%62.1%
a59253.3%54.3%
a68899.3%98.9%

Labels

LabelEstimated shareItems (consensus)Items (majority vote)
positive46.4%5659
neutral32.8%3937
negative20.7%2524

Least certain items

ItemConsensusConfidenceMajority voteLabels
t109positive62.6%positive4
t067neutral72.5%neutral3
t015negative78.4%negative3
t111negative81.9%negative3
t071positive83.8%positive3
t024neutral90.0%neutral3
t087neutral91.6%neutral3
t028positive97.8%positive3
t006positive99.0%positive3
t072positive99.0%positive3
t053positive99.0%neutral4
t016positive99.3%positive3
t008neutral99.6%neutral3
t090positive99.7%positive4
t023neutral99.7%neutral3
t101neutral99.7%neutral3
t064positive99.7%positive4
t119neutral99.7%neutral4
t059neutral99.7%positive3
t001positive99.8%positive4
t120neutral99.9%neutral4
t085neutral99.9%neutral4
t062neutral99.9%neutral3
t029negative99.9%positive4
t073neutral99.9%neutral5

Pairs that agree more than independent labeling would

AnnotatorWithShared itemsObserved agreementExpected if independentExcess
a1a667100.0%68.9%0.3106
a2a36163.9%53.6%0.1035
a2a57052.9%42.8%0.1006
a3a46660.6%51.0%0.0960
a4a56949.3%41.9%0.0737
a3a56648.5%42.9%0.0557
a2a46549.2%48.0%0.0120
a4a66564.6%66.3%−0.0172
a1a46761.2%69.5%−0.0829
a1a36768.7%77.0%−0.0830
  • EM from the majority vote; smoothing 0.01. Estimated accuracy is the expected share of an annotator's labels that match the true class. A low value is a statistical pattern, not a judgment of the person.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Annotator models (Dawid–Skene, GLAD, MACE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method agreement.dawid_skene 1.0.0 · spec 7d00b6870f97a746
# Dataset: annotations_copy (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.stats import annotators as an  # Dawid–Skene, GLAD, MACE (twin of R's cs_annotator_model)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/annotations_copy.parquet", columns=["item", "annotator", "label"])
n_input = len(df)
df["item"] = pd.Categorical(df["item"], categories=["t001", "t002", "t003", "t004", "t005", "t006", "t007", "t008", "t009", "t010", "t011", "t012", "t013", "t014", "t015", "t016", "t017", "t018", "t019", "t020", "t021", "t022", "t023", "t024", "t025", "t026", "t027", "t028", "t029", "t030", "t031", "t032", "t033", "t034", "t035", "t036", "t037", "t038", "t039", "t040", "t041", "t042", "t043", "t044", "t045", "t046", "t047", "t048", "t049", "t050", "t051", "t052", "t053", "t054", "t055", "t056", "t057", "t058", "t059", "t060", "t061", "t062", "t063", "t064", "t065", "t066", "t067", "t068", "t069", "t070", "t071", "t072", "t073", "t074", "t075", "t076", "t077", "t078", "t079", "t080", "t081", "t082", "t083", "t084", "t085", "t086", "t087", "t088", "t089", "t090", "t091", "t092", "t093", "t094", "t095", "t096", "t097", "t098", "t099", "t100", "t101", "t102", "t103", "t104", "t105", "t106", "t107", "t108", "t109", "t110", "t111", "t112", "t113", "t114", "t115", "t116", "t117", "t118", "t119", "t120"])  # stored level order
df["annotator"] = pd.Categorical(df["annotator"], categories=["a1", "a2", "a3", "a4", "a5", "a6"])  # stored level order
df["label"] = pd.Categorical(df["label"], categories=["positive", "neutral", "negative"])  # stored level order
df = df.dropna(subset=["item", "annotator", "label"])  # listwise deletion over the analysis columns
df["item"] = df["item"].cat.remove_unused_categories()
df["annotator"] = df["annotator"].cat.remove_unused_categories()
df["label"] = df["label"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["item", "annotator", "label"])  # infinite values stop the run (registry/errors.yaml)

# %% Codes (one row per label: item, annotator, label)
item_col, annot_col, label_col = "item", "annotator", "label"
items = [str(x) for x in df[item_col].cat.categories]
annots = [str(x) for x in df[annot_col].cat.categories]
labels = [str(x) for x in df[label_col].cat.categories]
n, m, k = len(items), len(annots), len(labels)
model = "dawid_skene"
if n < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=item_col, min=2, k=n)
if m < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=annot_col, min=2, k=m)
if k < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=label_col, min=2, k=k)
if model == "glad" and k != 2:
    cs.cs_error("CS_E_GROUP_COUNT", column=label_col, expected=2, k=k)
item = df[item_col].cat.codes.to_numpy(dtype=np.int64)
annot = df[annot_col].cat.codes.to_numpy(dtype=np.int64)
label = df[label_col].cat.codes.to_numpy(dtype=np.int64)
if not np.any(np.bincount(item, minlength=n) >= 2):
    cs.cs_error("CS_E_UNDEFINED", what="Annotator error rates", reason="every item has a single label; the models learn from items that two or more annotators labeled")

# %% Fit
smoothing = 0.01
restarts = int(0)
seed = int(1)
fit = an.annotator_model(item, annot, label, n, m, k, model=model, smoothing=smoothing, restarts=restarts, seed=seed)
summ = an.annotator_summary(fit, item, annot, label, n, m, k, smoothing=smoothing)
mv = an.majority_vote(item, label, n, k)
T = fit["T"]
consensus, confidence = summ["consensus"], summ["confidence"]
model_label = {"dawid_skene": "Dawid–Skene", "glad": "GLAD", "mace": "MACE"}[model]
per_item = np.bincount(item, minlength=n)
pairs = sorted(summ["pairs"], key=lambda r: (-r[5], r[0], r[1]))
max_excess = pairs[0][5] if pairs else None

values = {
    "n_items": float(n), "n_annotators": float(m), "n_labels": float(len(item)), "k": float(k),
    "loglik": float(fit["loglik"]), "iterations": float(fit["iterations"]), "converged": 1.0 if fit["converged"] else 0.0,
    "mean_confidence": float(np.mean(confidence)), "share_uncertain": float(np.mean(confidence < 0.8)),
    "agree_majority": float(np.mean(consensus == mv)), "max_pair_excess": None if max_excess is None else float(max_excess),
    "model_label": model_label,
}
share = T.mean(axis=0)
for c, lab in enumerate(labels):
    values[f"share[{lab}]"] = float(share[c])
ann_rows = []
for j, a in enumerate(annots):
    values[f"accuracy[{a}]"] = float(summ["accuracy"][j])
    values[f"agreement[{a}]"] = float(summ["agreement"][j])
    row = {"annotator": a, "labels": int(summ["n_labels"][j]), "accuracy": float(summ["accuracy"][j]),
           "agreement": float(summ["agreement"][j])}
    if model == "glad":
        values[f"ability[{a}]"] = row["ability"] = float(fit["par"]["ability"][j])
    if model == "mace":
        values[f"competence[{a}]"] = row["competence"] = float(fit["par"]["competence"][j])
    ann_rows.append(row)

# %% Assumptions
shared = np.zeros(m, dtype=bool)
for j in range(m):
    its = np.unique(item[annot == j])
    shared[j] = bool(np.any(np.isin(item[annot != j], its)))
multi = float(np.mean(per_item >= 2))
alone = [annots[j] for j in range(m) if not shared[j]]
support = T.sum(axis=0)
thin = [labels[c] for c in range(k) if support[c] < 5]
flagged = [p for p in pairs if p[2] >= 20 and p[5] > 0.15]
assumptions = [
    {"key": "overlap", "label": "Annotators overlap", "status": "warn" if (alone or multi < 0.5) else "pass",
     "detail": (f"No shared items for: {', '.join(alone)} — their error rates rest on the model alone. " if alone else "")
     + f"{multi:.0%} of items have two or more labels."},
    {"key": "class_support", "label": "Every class has items", "status": "warn" if thin else "pass",
     "detail": f"Fewer than 5 expected items in: {', '.join(thin)}." if thin else "Every class has at least 5 expected items."},
    {"key": "convergence", "label": "Convergence", "status": "pass" if fit["converged"] else "warn",
     "detail": f"EM {'converged' if fit['converged'] else 'stopped before converging'} after {fit['iterations']} iterations."},
    {"key": "conditional_independence", "label": "Annotators label independently",
     "status": "warn" if flagged else ("pass" if pairs else "info"),
     "detail": (f"{annots[flagged[0][0]]} and {annots[flagged[0][1]]} agree on {flagged[0][3]:.0%} of {flagged[0][2]} shared items; independent labeling would give {flagged[0][4]:.0%}. Copied or shared labels make the consensus overconfident."
                if flagged else ("No pair agrees more than 15 points above what independent labeling would give." if pairs else "Too few shared items to compare pairs of annotators."))},
]
if not fit["converged"]:
    warnings.append(cs.cs_warning("CS_W_NO_CONVERGENCE", what=model_label))

# %% Tables
order = np.lexsort((np.arange(n), confidence))[:25]
item_rows = [{"item": items[i], "consensus": labels[consensus[i]], "confidence": float(confidence[i]),
              "majority": labels[mv[i]], "labels": int(per_item[i])} for i in order]
class_rows = [{"label": labels[c], "share": float(share[c]), "consensus": int(np.sum(consensus == c)),
               "majority": int(np.sum(mv == c))} for c in range(k)]
pair_rows = [{"a": annots[p[0]], "b": annots[p[1]], "shared": int(p[2]), "observed": float(p[3]), "expected": float(p[4]),
              "excess": float(p[5])} for p in pairs[:10]]
ann_cols = [{"key": "annotator", "label": "Annotator", "type": "string"}, {"key": "labels", "label": "Labels", "type": "integer"},
            {"key": "accuracy", "label": "Estimated accuracy", "type": "percent"},
            {"key": "agreement", "label": "Agrees with consensus", "type": "percent"}]
if model == "glad":
    ann_cols.append({"key": "ability", "label": "Ability (α)", "type": "number"})
if model == "mace":
    ann_cols.append({"key": "competence", "label": "Competence (θ)", "type": "percent"})
tables = [
    {"key": "annotators", "title": "Annotators", "columns": ann_cols, "rows": ann_rows},
    {"key": "classes", "title": "Labels", "columns": [
        {"key": "label", "label": "Label", "type": "string"}, {"key": "share", "label": "Estimated share", "type": "percent"},
        {"key": "consensus", "label": "Items (consensus)", "type": "integer"}, {"key": "majority", "label": "Items (majority vote)", "type": "integer"},
    ], "rows": class_rows},
    {"key": "uncertain", "title": "Least certain items", "columns": [
        {"key": "item", "label": "Item", "type": "string"}, {"key": "consensus", "label": "Consensus", "type": "string"},
        {"key": "confidence", "label": "Confidence", "type": "percent"}, {"key": "majority", "label": "Majority vote", "type": "string"},
        {"key": "labels", "label": "Labels", "type": "integer"},
    ], "rows": item_rows},
]
if pair_rows:
    tables.append({"key": "pairs", "title": "Pairs that agree more than independent labeling would", "columns": [
        {"key": "a", "label": "Annotator", "type": "string"}, {"key": "b", "label": "With", "type": "string"},
        {"key": "shared", "label": "Shared items", "type": "integer"}, {"key": "observed", "label": "Observed agreement", "type": "percent"},
        {"key": "expected", "label": "Expected if independent", "type": "percent"}, {"key": "excess", "label": "Excess", "type": "number"},
    ], "rows": pair_rows})

# %% Charts
charts = [cs.chart("annotators", "cleveland-dot", "Annotators: estimated accuracy and agreement with the consensus", {
    "category": cs.col("Annotator", annots + annots, "categorical", levels=annots),
    "value": cs.col("Share", [float(x) for x in summ["accuracy"]] + [float(x) for x in summ["agreement"]], "numeric"),
    "group": cs.col("Measure", ["Estimated accuracy"] * m + ["Agrees with consensus"] * m, "categorical",
                    levels=["Estimated accuracy", "Agrees with consensus"]),
}, controls={"top": min(30, max(3, m)), "sort": "value"})]
if model in ("dawid_skene", "mace"):
    if model == "dawid_skene":
        cm = fit["par"]["theta"]
    else:
        th, sp = fit["par"]["competence"], fit["par"]["spam"]
        cm = (1.0 - th)[:, None, None] * np.repeat(sp[:, None, :], k, axis=1)
        cm[:, np.arange(k), np.arange(k)] += th[:, None]
    charts.append(cs.chart("confusion", "annotator-confusion", "How each annotator labels each true class", {
        "annotator": cs.col("Annotator", [a for a in annots for _ in range(k * k)], "categorical", levels=annots),
        "truth": cs.col("True class", [labels[c] for _ in annots for c in range(k) for _ in range(k)], "categorical", levels=labels),
        "given": cs.col("Label given", [labels[l] for _ in annots for _ in range(k) for l in range(k)], "categorical", levels=labels),
        "value": cs.col("Probability", [float(cm[j, c, l]) for j in range(m) for c in range(k) for l in range(k)], "numeric"),
    }))
charts.append(cs.chart("confidence", "histogram", "Confidence in each item's consensus label", {
    "x": cs.col("Confidence", [float(x) for x in confidence], "numeric"),
}, controls={"scale": "count", "kde": False}))

# %% Result
cs.publish({
    "method": "agreement.dawid_skene",
    "methodVersion": "1.0.0",
    "title": f"Annotator model ({model_label})",
    "engine": cs.engine_info("numpy", "codesplash"),
    "n": int(len(item)),
    "summary": f"{model_label} for {len(item)} labels from {m} annotators on {n} items: the consensus matches the majority vote on {values['agree_majority']:.0%} of items, with mean confidence {values['mean_confidence']:.2f}.",
    "apa": f"{model_label} model, {m} annotators, {n} items, {len(item)} labels; log-likelihood = {cs.fmt_num(fit['loglik'], 2)}",
    "statistics": [{"key": "mean_confidence", "label": "Mean confidence", "value": values["mean_confidence"]},
                   {"key": "agree_majority", "label": "Matches majority vote", "value": values["agree_majority"], "format": "percent"},
                   {"key": "loglik", "label": "Log-likelihood", "value": values["loglik"]}],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"EM from the majority vote{f' plus {restarts} random restarts' if restarts else ''}; smoothing {smoothing:g}. Estimated accuracy is the expected share of an annotator's labels that match the true class. A low value is a statistical pattern, not a judgment of the person."],
    "charts": charts,
    "values": values,
})
08

Check your understanding

Checkpoint

Check yourself

Why can an annotator model's consensus differ from the majority vote?

Show the answer

Answer: b

The model learns each annotator's error rates from all the items, then trusts reliable annotators more. Two careful annotators can outvote three careless ones.

Check yourself

Two annotators agree on almost every item they share, the model rates both as near perfect, and mean confidence goes up after you add the second one. What should you check first?

Show the answer

Answer: b

Agreement between dependent annotators isn't independent evidence. The model can't tell copying from expertise, so the copied-annotator check compares their agreement with what independent labeling would give.

Check yourself

An annotator's estimated accuracy is 55%. What's the best reading?

Show the answer

Answer: b

The number is a statistical pattern. The confusion matrix shows whether it's one confusable pair of classes (often a guideline problem) or errors everywhere.

09

Recap

Recap
  • Annotator models estimate the true labels and each annotator's error rates together.
  • Dawid–Skene for full confusion matrices, GLAD for item difficulty (two labels), MACE for careless labeling.
  • Dependent annotators make the consensus overconfident; read the independence check before trusting the confidence.

Concepts in this lesson