Skip to content

Weighted kappa for ordered categories

On an ordered scale, "mild" against "moderate" is a smaller miss than "none" against "severe". Weighted kappa gives credit for near misses, if your software knows the order.

Applied ~10 min6 steps

What runs in CodeSplash

You will be able to

  • Explain how linear and quadratic weights give partial credit
  • Compare weighted and unweighted agreement on the same ratings
  • Avoid the alphabetical-order trap when computing weighted kappa

Read first

01

Not all misses are equal

Read

On a four-point severity scale, unweighted κ treats a one-step miss and a three-step miss as equally wrong.

Weighted kappaWeighted kappaKappa for ordered categories, giving partial credit for near misses by linear or quadratic weights. gives partial credit by distance. With categories numbered ii and jj on a scale of kk levels:

Linear: wij=1−∣i−j∣k−1Quadratic: wij=1−(i−j)2(k−1)2\text{Linear: } w_{ij} = 1 - \frac{|i-j|}{k-1} \qquad \text{Quadratic: } w_{ij} = 1 - \frac{(i-j)^2}{(k-1)^2}

Quadratic weights forgive near misses more. With them, κ approximately equals an intraclass correlation.

02

Predict the jump

Predict

Predict first

Two raters match exactly on some patients and are often one step apart on the rest. With quadratic weights, compare the weighted agreement with the raw share of exact matches.

Weighted agreement will be higher than rawAbout the sameWeighted agreement will be lower than raw
Reveal

Higher: raw agreement is 76.7%, weighted is 97.0%, and κw\kappa_w = 0.87. Near misses get most of the credit. Chance agreement is weighted too, so it rises as well: 77.2%.

03

Run it

In the app

Set Weights to Linear or Quadratic.

Quadratically weighted Cohen's kappaRecorded · Python and R agreeRecorded 2026-11-21 · 15 values compared
R

κ = .87, 95% CI [0.82, 0.92], z = 10.62, p < .001

κ
0.8668
95% CI
[0.8151, 0.9185]
p
< .001
Observed agreement
76.7%

Effect size

  • Cohen's κ 0.8668 95% CI [0.8151, 0.9185]

Plots

Agreement tableWhat do the values of a square or rectangular result matrix look like at a glance?
View data
rater eCountrater_aSubjects
none49none49
mild7none7
moderate0none0
severe0none0
none6mild6
mild31mild31
moderate7mild7
severe1mild1
none1moderate1
mild7moderate7
moderate22moderate22
severe3moderate3
none0severe0
mild0severe0
moderate3severe3
severe13severe13
Agreement chart (Bangdiwala)Where do two raters agree, and where do they part?
View data
rater_arater eSubjects
nonenone49
nonemild7
nonemoderate0
nonesevere0
mildnone6
mildmild31
mildmoderate7
mildsevere1
moderatenone1
moderatemild7
moderatemoderate22
moderatesevere3
severenone0
severemild0
severemoderate3
severesevere13

Assumptions

  • Sample size — 150 subjects.
  • Prevalence and bias — The most common category covers 37% of a rater's ratings.

Agreement table

rater_a \ rater enonemildmoderatesevereTotal
none4970056
mild6317145
moderate1722333
severe0031316
Total56453217150

Rows: rater_a; columns: rater e.

Agreement indices

IndexValue
Observed agreement (weighted)0.9696
Expected agreement (weighted)0.7720
PABAK0.6889
κ max (unweighted)—
SE (non-null)0.0264
SE (null)0.0816
  • Categories in stored order: none, mild, moderate, severe. Weights 1 − (i − j)²/(k − 1)².
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 353793cb3ef14a5a
# 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 e")))
n_input <- nrow(df)
df[["rater_a"]] <- factor(df[["rater_a"]], levels = c("none", "mild", "moderate", "severe"))  # stored level order
df[["rater e"]] <- factor(df[["rater e"]], levels = c("none", "mild", "moderate", "severe"))  # stored level order
df <- df[stats::complete.cases(df[c("rater_a", "rater e")]), , 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 e"))  # infinite values stop the run (registry/errors.yaml)

# %% Agreement table
a <- "rater_a"
b <- "rater e"
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 <- "quadratic"
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
))
Python

κ = .87, 95% CI [0.82, 0.92], z = 10.62, p < .001

κ
0.8668
95% CI
[0.8151, 0.9185]
p
< .001
Observed agreement
76.7%

Effect size

  • Cohen's κ 0.8668 95% CI [0.8151, 0.9185]

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 enonemildmoderatesevereTotal
none4970056
mild6317145
moderate1722333
severe0031316
Total56453217150

Rows: rater_a; columns: rater e.

Agreement indices

IndexValue
Observed agreement (weighted)0.9696
Expected agreement (weighted)0.7720
PABAK0.6889
κ max (unweighted)—
SE (non-null)0.0264
SE (null)0.0816
  • Categories in stored order: none, mild, moderate, severe. Weights 1 − (i − j)²/(k − 1)².
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 353793cb3ef14a5a
# 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 e"])
n_input = len(df)
df["rater_a"] = pd.Categorical(df["rater_a"], categories=["none", "mild", "moderate", "severe"])  # stored level order
df["rater e"] = pd.Categorical(df["rater e"], categories=["none", "mild", "moderate", "severe"])  # stored level order
df = df.dropna(subset=["rater_a", "rater e"])  # listwise deletion over the analysis columns
df["rater_a"] = df["rater_a"].cat.remove_unused_categories()
df["rater e"] = df["rater e"].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 e"])  # infinite values stop the run (registry/errors.yaml)

# %% Agreement table
a, b = "rater_a", "rater e"
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 = "quadratic"
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,
})

Choose the weights before computing, and report which you used. Quadratic always looks more flattering when disagreements are small, and that makes it a tempting choice after the fact.

04

The alphabetical trap

Read

Weights depend on order, and software often sorts categories alphabetically: mild, moderate, none, severe. Now "none" and "severe" look one step apart, and the weights mean nothing.

CodeSplash uses the category order stored with the dataset, which you can set in the data dictionary. In code you must set it yourself. Run both versions below and compare.

Python
import pandas as pd
from sklearn.metrics import cohen_kappa_score

df = pd.read_csv("ratings_sim.csv")
order = ["none", "mild", "moderate", "severe"]

right = cohen_kappa_score(df["rater_a"], df["rater e"], labels=order, weights="quadratic")
wrong = cohen_kappa_score(df["rater_a"], df["rater e"], weights="quadratic")  # alphabetical
print(right, wrong)
R
library(irr)
df <- read.csv("ratings_sim.csv", check.names = FALSE)
order <- c("none", "mild", "moderate", "severe")

ok <- data.frame(a = factor(df$rater_a, order), b = factor(df[["rater e"]], order))
kappa2(ok, weight = "squared")$value

bad <- data.frame(a = factor(df$rater_a), b = factor(df[["rater e"]]))  # alphabetical
kappa2(bad, weight = "squared")$value
05

Check your understanding

Checkpoint

Check yourself

On a 5-point scale, what credit does a linear weight give two ratings one step apart? Give two decimals.

Show the answer

Answer: 0.75

1−1/(5−1)=0.751 - 1/(5-1) = 0.75.

Check yourself

Two coders classify complaints as billing, delivery or product. Should you use weighted kappa?

Show the answer

Answer: c

Weighting needs a meaningful order. These categories are nominal, so use unweighted κ.

Check yourself

A colleague's weighted κ falls from 0.85 to 0.40 after moving to another tool, with the same data. What's your first suspect?

Show the answer

Answer: b

Check the ordering first. It silently changes every weight and is the most common way to get this wrong.

06

Recap

Recap
  • Weighted κ gives partial credit for near misses on an ordered scale.
  • Choose linear or quadratic in advance, and say which you used.
  • Make sure the software knows the category order.
  • Don't weight nominal categories.

Concepts in this lesson