Sub topic 12
Weighted kappa for ordinal labels
This chapter assumes you can compute Cohen's kappa for two annotators, including observed and chance agreement. It also assumes you have read a confusion matrix and are comfortable with NumPy basics.
Why plain kappa is wrong for ordered labels
Cohen's kappa treats every disagreement as equally bad. For labels like pos, neu and neg that is often acceptable. Ordinal labels such as 1–5 star ratings, severity levels, or "not toxic" to "very toxic" are different. If one annotator gives a 4 and another gives a 5, they nearly agree. If one gives a 1 and the other a 5, they hold opposite views.
Plain kappa scores both cases as a miss. It throws away the ordering and makes annotators on a fine-grained scale look less reliable than they are. Weighted kappa fixes this by giving each pair of labels a penalty that grows with their distance.
The working model
Weighted kappa compares disagreement instead of agreement. Let k be the number of categories, and let O[i][j] be the proportion of items where annotator A chose category i and annotator B chose j. Let E[i][j] be the proportion expected by chance, which is the product of the two annotators' marginal proportions. A weight w[i][j] measures how bad the pair (i, j) is, with w = 0 on the diagonal.
kappa_w = 1 - (sum of w * O) / (sum of w * E)The numerator is the observed weighted disagreement. The denominator is the disagreement you would expect if both annotators labeled independently with their own habits. A score of 1 means perfect agreement, 0 means chance level, and negative values mean worse than chance.
Plain kappa is the special case where w = 0 on the diagonal and w = 1 everywhere else.
Choosing the weights
Two weighting schemes cover most work. With d = |i - j| and k categories:
| Scheme | Weight | Penalty on a 5-point scale for d = 1, 2, 3, 4 |
|---|---|---|
| Unweighted | 1 if i ≠ j | 1, 1, 1, 1 |
| Linear | d / (k - 1) | 0.25, 0.50, 0.75, 1.00 |
| Quadratic | (d / (k - 1))² | 0.0625, 0.25, 0.5625, 1.00 |
Linear weights make the penalty proportional to the distance. Quadratic weights punish large gaps much more than small ones. Quadratic weighted kappa is the usual default in NLP papers and shared tasks, partly because it is closely related to the Pearson correlation between the two annotators' ratings. Whichever you choose, report it, because the two schemes give different numbers on the same data.
From-scratch implementation
The code below builds the observed matrix O, the chance matrix E, and a weight matrix, then applies the formula. It uses the seven ratings from the pilot round of a 1–5 rating task.
import numpy as np
def weighted_kappa(a, b, categories, kind="quadratic"):
k = len(categories)
idx = {c: i for i, c in enumerate(categories)}
O = np.zeros((k, k))
for x, y in zip(a, b):
O[idx[x], idx[y]] += 1
O /= O.sum()
E = np.outer(O.sum(axis=1), O.sum(axis=0))
i, j = np.indices((k, k))
if kind == "linear":
W = np.abs(i - j)
elif kind == "quadratic":
W = (i - j) ** 2
else:
W = (i != j).astype(float)
return 1 - (W * O).sum() / (W * E).sum()
r1 = [1, 2, 3, 4, 5, 3, 2]
r2 = [1, 3, 3, 5, 4, 3, 1]
cats = [1, 2, 3, 4, 5]
for kind in ["none", "linear", "quadratic"]:
print(kind, round(weighted_kappa(r1, r2, cats, kind), 3))The output is:
none 0.282
linear 0.611
quadratic 0.831All four disagreements are one step apart, so they cost little under weighting. Only three of the seven pairs match exactly, so plain kappa is low. The weights are not normalized by (k - 1) here, but that constant appears in both the numerator and denominator and cancels.
Using scikit-learn
For everyday use, cohen_kappa_score accepts a weights argument.
from sklearn.metrics import cohen_kappa_score
r1 = [1, 2, 3, 4, 5, 3, 2]
r2 = [1, 3, 3, 5, 4, 3, 1]
print(round(cohen_kappa_score(r1, r2), 3))
print(round(cohen_kappa_score(r1, r2, weights="linear"), 3))
print(round(cohen_kappa_score(r1, r2, weights="quadratic"), 3))
print(round(cohen_kappa_score(r1, r2, weights="quadratic",
labels=[1, 2, 3, 4, 5]), 3))The four values are 0.282, 0.611, 0.831 and 0.831, matching the from-scratch version.
Common errors
Label order comes from sorting
scikit-learn sorts the label values to decide which categories are adjacent. Integer codes work. String labels do not. The strings "high", "low" and "medium" sort alphabetically as high, low, medium, which puts "low" between "high" and "medium". The weights are then wrong and the score is meaningless. Map ordered strings to integers before scoring, for example {"low": 0, "medium": 1, "high": 2}.
Unused categories collapse the scale
If neither annotator used a 2 in a small sample, the unique labels become 1, 3, 4, 5. A 1 versus 3 disagreement is then treated as one step apart. Pass labels=[1, 2, 3, 4, 5] so the full scale defines the distances.
Comparing scores with different weights
A quadratic value of 0.83 and a linear value of 0.61 on the same data are not contradictory. Never compare kappa values across studies without checking which weighting each one used.
Weighting nominal labels
Weighting only makes sense when the label distance means something. Applying linear weights to pos, neu and neg is defensible, because neutral sits between the other two. Applying them to PER, ORG and LOC is not, because the integer codes are arbitrary and the score would change if you reordered them.
Inheriting the limits of kappa
Weighted kappa still suffers from prevalence and annotator bias. If 90% of items are rated 4 or 5, chance agreement is high and kappa drops even when annotators are accurate. Also note that when every rating is identical for both annotators, the denominator is zero and kappa is undefined.
Reading the result
Interpretation thresholds such as "substantial" or "almost perfect" were proposed for unweighted kappa. Weighted values are usually higher on the same data, so applying those labels to quadratic kappa flatters your data. A practical approach is to report unweighted, linear and quadratic values together with the confusion matrix. A big jump from unweighted to quadratic kappa tells you the annotators disagree mostly by one step. That usually points to fuzzy boundaries between adjacent categories, which you can fix by adding anchor examples to the guidelines for each level.
For more than two annotators, or when some items lack ratings from some annotators, weighted kappa does not apply directly. Krippendorff's alpha with an interval or ordinal distance handles those cases and is covered in the next chapter.
Exercise
On a 5-point scale, annotators A and B disagree on one item by four steps (1 versus 5). Under quadratic weights, how many one-step disagreements carry the same total penalty? How many under linear weights?
Show answer
Quadratic: the 4-step penalty is 1.00 and a 1-step penalty is 0.0625, so 16 one-step disagreements equal one extreme disagreement. Linear: the 1-step penalty is 0.25, so 4 one-step disagreements equal one extreme one. This is why quadratic weighting is the better choice when distant errors are much worse than near ones.
Exercise
You score ratings stored as the strings "low", "medium" and "high" with cohenkappascore(a, b, weights="linear"). Why can the result be wrong, and how do you fix it?
Show answer
scikit-learn orders the labels by sorting them, which gives alphabetical order (high, low, medium), so "low" is treated as lying between "high" and "medium". Convert the labels to integer codes that follow the real order, such as low=0, medium=1, high=2, and pass labels=[0, 1, 2].