Cohen's kappa and its test
Two raters can agree a lot by chance alone. Kappa removes that chance, and its significance test answers a question you rarely care about.
What runs in CodeSplash
- STAT307Cohen kappa significance test Runs in CodeSplash
- Cohen's kappa (two raters) Verified in Python and R
You will be able to
- Compute kappa from observed and chance agreement
- Explain why testing kappa = 0 rarely establishes useful agreement
- Read a kappa result and its confidence interval
Read first
Correcting for chance
ReadTwo doctors grade severity on a four-point scale. They agree on 67.3% of 150 patients. Is that good?
Depends on how often they would agree by luck. Multiply how often each uses each grade, sum them up, and you get chance agreementCohen's kappaAgreement between raters beyond what chance would produce; 0 is chance level, 1 is perfect. : here, 28.6%.
Kappa is the share of the possible improvement over chance that the raters achieved.
Compute it
CheckpointCheck yourself
Two raters agree on 80% of items, and chance agreement is 50%. What is kappa?
Show the answer
Answer: 0.6
.
Check yourself
What does kappa = 0 mean?
Show the answer
Answer: b
means . Raters can agree often and still get zero, if chance alone would make them agree that often.
Predict the test
PredictPredict first
The output includes a test with a very small p-value. Its null hypothesis is .
What does rejecting that hypothesis show?
Reveal
Only that agreement is above chance. Here: = 0.54, = 10.9, p < .001. For raters who are supposed to be doing the same job, beating chance is a very low bar. The interval, 0.44 to 0.65, is what you need.
Test against a benchmark instead
ReadIf a protocol sets a minimum, put it in Null value (κ0). The test becomes , using the standard error that doesn't assume (Fleiss, Levin & Paik, 2003). Against = 0.4, the same raters give = 2.69, p = .007: agreement is credibly above that benchmark, a far more useful statement than "above chance".
Check yourself
Why does the test against κ0 = 0.4 use a different standard error from the test against zero?
Show the answer
Answer: b
Under κ = 0 the raters are independent, which gives a simpler null variance. Testing any other value uses the Fleiss–Cohen–Everitt variance that allows for agreement.
Read the card
In the appFind the agreement table, observed and chance agreement, with its interval and the ratio of to its maximum.
κ = .54, 95% CI [0.44, 0.65], z = 10.89, p < .001
- κ
- 0.5425
- 95% CI
- [0.4388, 0.6463]
- p
- < .001
- Observed agreement
- 67.3%
Effect size
- Cohen's κ 0.5425 95% CI [0.4388, 0.6463]
Plots
View data
| rater_b | Count | rater_a | Subjects |
|---|---|---|---|
| none | 44 | none | 44 |
| mild | 12 | none | 12 |
| moderate | 0 | none | 0 |
| severe | 0 | none | 0 |
| none | 8 | mild | 8 |
| mild | 28 | mild | 28 |
| moderate | 7 | mild | 7 |
| severe | 2 | mild | 2 |
| none | 2 | moderate | 2 |
| mild | 7 | moderate | 7 |
| moderate | 18 | moderate | 18 |
| severe | 6 | moderate | 6 |
| none | 0 | severe | 0 |
| mild | 0 | severe | 0 |
| moderate | 5 | severe | 5 |
| severe | 11 | severe | 11 |
View data
| rater_a | rater_b | Subjects |
|---|---|---|
| none | none | 44 |
| none | mild | 12 |
| none | moderate | 0 |
| none | severe | 0 |
| mild | none | 8 |
| mild | mild | 28 |
| mild | moderate | 7 |
| mild | severe | 2 |
| moderate | none | 2 |
| moderate | mild | 7 |
| moderate | moderate | 18 |
| moderate | severe | 6 |
| severe | none | 0 |
| severe | mild | 0 |
| severe | moderate | 5 |
| severe | severe | 11 |
Assumptions
- Sample size — 150 subjects.
- Prevalence and bias — The most common category covers 37% of a rater's ratings.
Agreement table
| rater_a \ rater_b | none | mild | moderate | severe | Total |
|---|---|---|---|---|---|
| none | 44 | 12 | 0 | 0 | 56 |
| mild | 8 | 28 | 7 | 2 | 45 |
| moderate | 2 | 7 | 18 | 6 | 33 |
| severe | 0 | 0 | 5 | 11 | 16 |
| Total | 54 | 47 | 30 | 19 | 150 |
Rows: rater_a; columns: rater_b.
Agreement indices
| Index | Value |
|---|---|
| Observed agreement (weighted) | 0.6733 |
| Expected agreement (weighted) | 0.2859 |
| PABAK | 0.5644 |
| κ max (unweighted) | 0.9533 |
| SE (non-null) | 0.0529 |
| SE (null) | 0.0498 |
- Categories in stored order: none, mild, moderate, severe.
The exact R script · R R version 4.5.1 (2025-06-13)
# Cohen's kappa (two raters)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method agreement.kappa 1.1.0 · spec c464900e1c604d42
# Dataset: ratings_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/ratings_sim.parquet", col_select = c("rater_a", "rater_b")))
n_input <- nrow(df)
df[["rater_a"]] <- factor(df[["rater_a"]], levels = c("none", "mild", "moderate", "severe")) # stored level order
df[["rater_b"]] <- factor(df[["rater_b"]], levels = c("none", "mild", "moderate", "severe")) # stored level order
df <- df[stats::complete.cases(df[c("rater_a", "rater_b")]), , 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("rater_a", "rater_b")) # infinite values stop the run (registry/errors.yaml)
# %% Agreement table
a <- "rater_a"
b <- "rater_b"
cats <- unique(c(levels(df[[a]]), levels(df[[b]]))) # stored order
k <- length(cats)
if (k < 2) cs_error("CS_E_UNDEFINED", what = "Cohen's κ", reason = "the raters used only one category")
tab <- unclass(table(factor(as.character(df[[a]]), levels = cats), factor(as.character(df[[b]]), levels = cats)))
tab <- matrix(as.numeric(tab), k, k)
# %% Cohen's kappa
weights <- "none"
conf <- 0.95
res <- cs_kappa(tab, weights, conf) # FCE variances (twin of codesplash.stats.agreement.kappa)
k0 <- 0 # H0: kappa = kappa0; 0 keeps the usual test with the null SE
if (k0 != 0) {
tst <- cs_kappa_null_test(res$kappa, res$se, k0) # twin of codesplash.stats.agreement_null.kappa_null_test
res$z <- tst$z
res$p <- tst$p
}
weights_label <- c(none = "Unweighted", linear = "Linearly weighted", quadratic = "Quadratically weighted")[[weights]]
fin <- function(x) if (!is.finite(x)) NA else unname(x)
values <- lapply(res[c("kappa", "ci_low", "ci_high", "se", "se0", "z", "p", "po", "pe", "po_raw", "pabak", "kappa_max")], fin)
values$n <- res$n
values$k <- k
values$weights_label <- weights_label
if (k0 != 0) values$null_value <- k0
# %% Assumptions
n <- res$n
empty <- cats[rowSums(tab) + colSums(tab) == 0]
dominant <- max(rowSums(tab) / n, colSums(tab) / n)
assumptions <- list(
list(key = "sample_size", label = "Sample size", status = if (n < 30) "warn" else "pass",
detail = paste0(sprintf("%d subjects", n), if (n < 30) " — the large-sample interval is approximate." else ".")),
list(key = "prevalence", label = "Prevalence and bias", status = if (dominant > 0.8) "warn" else "pass",
detail = paste0(sprintf("The most common category covers %.0f%% of a rater's ratings", 100 * dominant),
if (dominant > 0.8) "; κ can be low despite high agreement (compare PABAK)." else "."))
)
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
cols <- c(list(list(key = "rater_a", label = sprintf("%s \\ %s", a, b), type = "string")),
lapply(seq_len(k), function(j) list(key = sprintf("c%d", j - 1), label = cats[j], type = "integer")),
list(list(key = "total", label = "Total", type = "integer")))
rows <- lapply(seq_len(k), function(i) {
r <- list(rater_a = cats[i])
for (j in seq_len(k)) r[[sprintf("c%d", j - 1)]] <- tab[i, j]
r$total <- sum(tab[i, ])
r
})
tot <- list(rater_a = "Total")
for (j in seq_len(k)) tot[[sprintf("c%d", j - 1)]] <- sum(tab[, j])
tot$total <- n
rows[[k + 1]] <- tot
weight_note <- switch(weights, linear = " Weights 1 − |i − j|/(k − 1).", quadratic = " Weights 1 − (i − j)²/(k − 1)².", "")
cs_publish(list(
method = "agreement.kappa",
methodVersion = "1.1.0",
title = paste(weights_label, "Cohen's kappa"),
engine = cs_engine_info("stats", "codesplashr"),
n = n,
summary = sprintf("%s κ = %.3f, %s CI [%.3f, %.3f]; observed agreement %.1f%%.", weights_label, res$kappa, pct, res$ci_low, res$ci_high, 100 * res$po_raw),
apa = sprintf("κ = %s, %s CI [%s, %s], z = %s, %s", cs_fmt_num(res$kappa, 2, leading_zero = FALSE), pct, cs_fmt_num(res$ci_low),
cs_fmt_num(res$ci_high), cs_fmt_num(res$z), cs_fmt_p(res$p)),
statistics = list(list(key = "kappa", label = "κ", value = res$kappa), list(key = "ci", label = paste(pct, "CI"), value = c(res$ci_low, res$ci_high)),
list(key = "p", label = "p", value = res$p, format = "p"),
list(key = "po_raw", label = "Observed agreement", value = res$po_raw, format = "percent")),
tables = list(
list(key = "agreement", title = "Agreement table", columns = cols, rows = rows, note = sprintf("Rows: %s; columns: %s.", a, b)),
list(key = "indices", title = "Agreement indices", columns = list(
list(key = "index", label = "Index", type = "string"), list(key = "value", label = "Value", type = "number")),
rows = list(list(index = "Observed agreement (weighted)", value = res$po), list(index = "Expected agreement (weighted)", value = res$pe),
list(index = "PABAK", value = res$pabak), list(index = "κ max (unweighted)", value = values$kappa_max),
list(index = "SE (non-null)", value = res$se), list(index = "SE (null)", value = res$se0)))
),
effectSizes = list(list(key = "kappa", label = "Cohen's κ", value = res$kappa, ciLow = res$ci_low, ciHigh = res$ci_high,
ciLevel = conf, method = "Fleiss–Cohen–Everitt large-sample SE")),
assumptions = assumptions,
warnings = c(warnings, if (length(empty)) list(sprintf("Categories never used: %s.", paste(empty, collapse = ", ")))),
notes = c(list(paste0(sprintf("Categories in stored order: %s.", paste(cats, collapse = ", ")), weight_note)),
if (k0 != 0) list(sprintf("The test is against a null value of %s (H₀: κ = %s): z = (κ − κ₀) / SE with the non-null standard error (Fleiss, Levin & Paik, 2003).", cs_fmt_num(k0), cs_fmt_num(k0)))),
charts = c(list(cs_chart("table", "matrix-heatmap", "Agreement table", list(
row = cs_col(a, rep(cats, each = k), "categorical", levels = cats),
col = cs_col(b, rep(cats, times = k), "categorical", levels = cats),
value = cs_col("Subjects", as.vector(t(tab)), "numeric"),
label = cs_col("Count", as.character(as.vector(t(tab))), "categorical")
), controls = list(scale = "sequential"))), if (k <= 12) list(cs_chart("agreement", "agreement-chart", "Agreement chart (Bangdiwala)", list(
a = cs_col(a, rep(cats, each = k), "categorical", levels = cats),
b = cs_col(b, rep(cats, times = k), "categorical", levels = cats),
count = cs_col("Subjects", as.vector(t(tab)), "numeric")
), controls = list(partial = weights != "none")))),
values = values
))
κ = .54, 95% CI [0.44, 0.65], z = 10.89, p < .001
- κ
- 0.5425
- 95% CI
- [0.4388, 0.6463]
- p
- < .001
- Observed agreement
- 67.3%
Effect size
- Cohen's κ 0.5425 95% CI [0.4388, 0.6463]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Sample size — 150 subjects.
- Prevalence and bias — The most common category covers 37% of a rater's ratings.
Agreement table
| rater_a \ rater_b | none | mild | moderate | severe | Total |
|---|---|---|---|---|---|
| none | 44 | 12 | 0 | 0 | 56 |
| mild | 8 | 28 | 7 | 2 | 45 |
| moderate | 2 | 7 | 18 | 6 | 33 |
| severe | 0 | 0 | 5 | 11 | 16 |
| Total | 54 | 47 | 30 | 19 | 150 |
Rows: rater_a; columns: rater_b.
Agreement indices
| Index | Value |
|---|---|
| Observed agreement (weighted) | 0.6733 |
| Expected agreement (weighted) | 0.2859 |
| PABAK | 0.5644 |
| κ max (unweighted) | 0.9533 |
| SE (non-null) | 0.0529 |
| SE (null) | 0.0498 |
- Categories in stored order: none, mild, moderate, severe.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Cohen's kappa (two raters)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method agreement.kappa 1.1.0 · spec c464900e1c604d42
# Dataset: ratings_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 agreement as ag # Cohen's κ with FCE variances (twin of R's cs_kappa)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ratings_sim.parquet", columns=["rater_a", "rater_b"])
n_input = len(df)
df["rater_a"] = pd.Categorical(df["rater_a"], categories=["none", "mild", "moderate", "severe"]) # stored level order
df["rater_b"] = pd.Categorical(df["rater_b"], categories=["none", "mild", "moderate", "severe"]) # stored level order
df = df.dropna(subset=["rater_a", "rater_b"]) # listwise deletion over the analysis columns
df["rater_a"] = df["rater_a"].cat.remove_unused_categories()
df["rater_b"] = df["rater_b"].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, ["rater_a", "rater_b"]) # infinite values stop the run (registry/errors.yaml)
# %% Agreement table
a, b = "rater_a", "rater_b"
cats = list(dict.fromkeys([str(x) for x in df[a].cat.categories] + [str(x) for x in df[b].cat.categories])) # stored order
k = len(cats)
if k < 2:
cs.cs_error("CS_E_UNDEFINED", what="Cohen's κ", reason="the raters used only one category")
ia = np.array([cats.index(x) for x in df[a].astype(str)])
ib = np.array([cats.index(x) for x in df[b].astype(str)])
table = np.zeros((k, k))
np.add.at(table, (ia, ib), 1)
# %% Cohen's kappa
weights = "none"
conf = 0.95
res = ag.kappa(table, weights, conf)
k0 = 0 # H0: κ = κ0; 0 keeps the usual test with the null SE
if k0 != 0:
from codesplash.stats import agreement_null as agn # twin of R's cs_kappa_null_test
res["z"], res["p"] = agn.kappa_null_test(res["kappa"], res["se"], k0)
weights_label = {"none": "Unweighted", "linear": "Linearly weighted", "quadratic": "Quadratically weighted"}[weights]
nan = lambda x: None if not np.isfinite(x) else float(x) # noqa: E731
values = {key: nan(res[key]) for key in ("kappa", "ci_low", "ci_high", "se", "se0", "z", "p", "po", "pe", "po_raw", "pabak", "kappa_max")}
values.update({"n": float(res["n"]), "k": float(k), "weights_label": weights_label})
if k0 != 0:
values["null_value"] = k0
# %% Assumptions
n = int(res["n"])
empty = [c for i, c in enumerate(cats) if table[i].sum() + table[:, i].sum() == 0]
pr, pc = table.sum(axis=1) / n, table.sum(axis=0) / n
dominant = max(pr.max(), pc.max())
assumptions = [
{"key": "sample_size", "label": "Sample size", "status": "warn" if n < 30 else "pass",
"detail": f"{n} subjects" + (" — the large-sample interval is approximate." if n < 30 else ".")},
{"key": "prevalence", "label": "Prevalence and bias", "status": "warn" if dominant > 0.8 else "pass",
"detail": f"The most common category covers {dominant:.0%} of a rater's ratings"
+ ("; κ can be low despite high agreement (compare PABAK)." if dominant > 0.8 else ".")},
]
# %% Result
pct = f"{conf:.0%}"
cols = [{"key": "rater_a", "label": f"{a} \\ {b}", "type": "string"}] + [
{"key": f"c{j}", "label": c, "type": "integer"} for j, c in enumerate(cats)] + [{"key": "total", "label": "Total", "type": "integer"}]
rows = [{"rater_a": c, **{f"c{j}": float(table[i, j]) for j in range(k)}, "total": float(table[i].sum())} for i, c in enumerate(cats)]
rows.append({"rater_a": "Total", **{f"c{j}": float(table[:, j].sum()) for j in range(k)}, "total": float(n)})
cs.publish({
"method": "agreement.kappa",
"methodVersion": "1.1.0",
"title": f"{weights_label} Cohen's kappa",
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": n,
"summary": f"{weights_label} κ = {res['kappa']:.3f}, {pct} CI [{res['ci_low']:.3f}, {res['ci_high']:.3f}]; observed agreement {res['po_raw']:.1%}.",
"apa": f"κ = {cs.fmt_num(res['kappa'], 2, leading_zero=False)}, {pct} CI [{cs.fmt_num(res['ci_low'])}, {cs.fmt_num(res['ci_high'])}], z = {cs.fmt_num(res['z'])}, {cs.fmt_p(res['p'])}",
"statistics": [{"key": "kappa", "label": "κ", "value": res["kappa"]}, {"key": "ci", "label": f"{pct} CI", "value": [res["ci_low"], res["ci_high"]]},
{"key": "p", "label": "p", "value": res["p"], "format": "p"}, {"key": "po_raw", "label": "Observed agreement", "value": res["po_raw"], "format": "percent"}],
"tables": [
{"key": "agreement", "title": "Agreement table", "columns": cols, "rows": rows, "note": f"Rows: {a}; columns: {b}."},
{"key": "indices", "title": "Agreement indices", "columns": [
{"key": "index", "label": "Index", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [{"index": "Observed agreement (weighted)", "value": res["po"]}, {"index": "Expected agreement (weighted)", "value": res["pe"]},
{"index": "PABAK", "value": res["pabak"]}, {"index": "κ max (unweighted)", "value": values["kappa_max"]},
{"index": "SE (non-null)", "value": res["se"]}, {"index": "SE (null)", "value": res["se0"]}]},
],
"effectSizes": [{"key": "kappa", "label": "Cohen's κ", "value": res["kappa"], "ciLow": res["ci_low"], "ciHigh": res["ci_high"],
"ciLevel": conf, "method": "Fleiss–Cohen–Everitt large-sample SE"}],
"assumptions": assumptions,
"warnings": warnings + ([f"Categories never used: {', '.join(empty)}."] if empty else []),
"notes": [f"Categories in stored order: {', '.join(cats)}." + (" Weights 1 − |i − j|/(k − 1)." if weights == "linear" else " Weights 1 − (i − j)²/(k − 1)²." if weights == "quadratic" else "")]
+ ([f"The test is against a null value of {cs.fmt_num(k0)} (H₀: κ = {cs.fmt_num(k0)}): z = (κ − κ₀) / SE with the non-null standard error (Fleiss, Levin & Paik, 2003)."] if k0 != 0 else []),
"charts": [cs.chart("table", "matrix-heatmap", "Agreement table", {
"row": cs.col(a, [c for c in cats for _ in cats], "categorical", levels=cats),
"col": cs.col(b, [c for _ in cats for c in cats], "categorical", levels=cats),
"value": cs.col("Subjects", table.ravel().tolist(), "numeric"),
"label": cs.col("Count", [f"{int(x)}" for x in table.ravel()], "categorical"),
}, controls={"scale": "sequential"})] + ([cs.chart("agreement", "agreement-chart", "Agreement chart (Bangdiwala)", {
"a": cs.col(a, [c for c in cats for _ in cats], "categorical", levels=cats),
"b": cs.col(b, [c for _ in cats for c in cats], "categorical", levels=cats),
"count": cs.col("Subjects", table.ravel().tolist(), "numeric"),
}, controls={"partial": weights != "none"})] if k <= 12 else []),
"values": values,
})
Labels such as "moderate" or "substantial" come from Landis and Koch (1977). They were offered as rough guides, and they ignore the interval and the stakes. A κ you would accept for grouping customer complaints may be unacceptable for a cancer diagnosis.
Same statistic, two dialects
Readscikit-learn gives only the coefficient. statsmodels and irr also give the test or the interval.
import pandas as pd
from sklearn.metrics import cohen_kappa_score
from statsmodels.stats.inter_rater import cohens_kappa
df = pd.read_csv("ratings_sim.csv")
print(cohen_kappa_score(df["rater_a"], df["rater_b"]))
table = pd.crosstab(df["rater_a"], df["rater_b"]).to_numpy()
print(cohens_kappa(table))library(irr)
df <- read.csv("ratings_sim.csv")
kappa2(df[, c("rater_a", "rater_b")], weight = "unweighted")Check your understanding
CheckpointCheck yourself
Which is the best report?
Show the answer
Answer: c
Give the coefficient, its interval, the raw agreement and the scale. A p-value against zero adds almost nothing.
Check yourself
Two raters reach κ = 0.8 over only 12 items. What should you check first?
Show the answer
Answer: a
With few items the interval can stretch from poor to excellent. A planned study should choose its size to make that interval narrow enough.
Recap
Recap- Kappa measures agreement beyond chance, relative to the most that could be achieved.
- Testing κ = 0 shows only that raters beat chance. Report the interval.
- Benchmarks are rough, so judge against what the decision needs.
Concepts in this lesson