Chapter 27 Responsible NLP Contents Course home

Worked exampleMeasuring a model's harms

Per-group metrics, three fairness criteria that cannot all hold, a WEAT score before and after debiasing, a counterfactual name swap, calibration with abstention, and a drift index. Every model is a toy, so the tables show how to measure.

File responsible.py Chapter 27. Responsible NLP Needs nothing but Python 3

What to try

  1. python3 responsible.py

    All six measurements in order.

  2. python3 responsible.py --groups

    Pooled F1 is 0.782, group A scores 0.875 and group B 0.522. Selection rates are 0.438 and 0.407, so parity nearly holds while the true positive rates are 0.875 and 0.500.

  3. python3 responsible.py --criteria

    Equal true positive and false positive rates leave precision at 0.889 for a group with half the applicants deserving a yes and 0.667 for one with a fifth.

  4. python3 responsible.py --weat

    Projecting out the bias direction takes the direction score from +0.533 to 0.000. A held-out WEAT still gives d = +1.072, down from +1.825.

  5. python3 responsible.py --counterfactual

    Swapping only the name changes the prediction in 11 of 18 pairs, a rate of 0.611.

  6. python3 responsible.py --calibration

    Expected calibration error is 0.0865. The model says 0.95 and is right 83 per cent of the time. Answering only above 0.8 covers 40 per cent at 0.774 accuracy.

  7. python3 responsible.py --drift

    A shift in input length gives a population stability index of 0.3349, a large shift by the usual rule of thumb.

The source

"""Responsible NLP, worked as Chapter 27 works it.

Six things, each reproducing a table in the chapter. Every model here is a
toy with chosen numbers, so each table shows how to measure and none of them
reports a finding about a real system.

    groups        one classifier, scored per group and pooled
    criteria      three fairness criteria that cannot all hold
    association   a WEAT score before and after projecting out a direction
    counterfactual  swap one name, count how often the output moves
    calibration   confidence against accuracy, and abstaining
    drift         the population stability index of live inputs

    python3 responsible.py                  # all six
    python3 responsible.py --groups         # per-group metrics and parity
    python3 responsible.py --criteria       # equal error rates against equal precision
    python3 responsible.py --weat           # the association test and debiasing
    python3 responsible.py --counterfactual # name swaps on a flawed toy model
    python3 responsible.py --calibration    # ECE and selective prediction
    python3 responsible.py --drift          # PSI between training and live

Install:  nothing, the Python standard library is enough
"""

import argparse
import math
from itertools import combinations

# -------------------------------------------------------------------- groups

# A loan classifier on 1000 applications. "Positive" means approve. Counts are
# true positive, false positive, false negative, true negative.
GROUPS = {"group A": (280, 40, 40, 370), "group B": (60, 50, 60, 100)}


def measures(tp, fp, fn, tn):
    n = tp + fp + fn + tn
    prec = tp / (tp + fp) if tp + fp else 0.0
    rec = tp / (tp + fn) if tp + fn else 0.0
    f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0
    return {"n": n, "accuracy": (tp + tn) / n, "precision": prec, "recall": rec,
            "f1": f1, "selection": (tp + fp) / n, "fpr": fp / (fp + tn) if fp + tn else 0.0}


def show_groups():
    pooled = tuple(sum(g[i] for g in GROUPS.values()) for i in range(4))
    rows = {**{k: measures(*v) for k, v in GROUPS.items()}, "pooled": measures(*pooled)}
    print("\nSTEP 1  one classifier, scored per group and pooled\n")
    print(f"  {'':<10}{'TP':>5}{'FP':>5}{'FN':>5}{'TN':>5}{'n':>6}")
    print("  " + "-" * 36)
    for k, v in {**GROUPS, "pooled": pooled}.items():
        print(f"  {k:<10}{v[0]:>5}{v[1]:>5}{v[2]:>5}{v[3]:>5}{sum(v):>6}")
    print(f"\n  {'':<10}{'accuracy':>10}{'precision':>11}{'recall':>8}{'F1':>8}")
    print("  " + "-" * 47)
    for k, m in rows.items():
        print(f"  {k:<10}{m['accuracy']:>10.3f}{m['precision']:>11.3f}{m['recall']:>8.3f}{m['f1']:>8.3f}")
    a, b = rows["group A"], rows["group B"]
    print(f"\n  simple average of the two F1 scores   {(a['f1'] + b['f1']) / 2:.3f}")
    print(f"  pooled F1                             {rows['pooled']['f1']:.3f}")
    print(f"  group A is {a['n'] / rows['pooled']['n']:.0%} of the applications.")
    print("\n  Parity of three quantities, group A against group B:\n")
    print(f"  {'quantity':<28}{'A':>8}{'B':>8}{'gap':>8}")
    print("  " + "-" * 52)
    for label, key in (("selection rate", "selection"), ("true positive rate", "recall"),
                       ("false positive rate", "fpr"), ("precision", "precision")):
        print(f"  {label:<28}{a[key]:>8.3f}{b[key]:>8.3f}{a[key] - b[key]:>8.3f}")
    print("\n  The selection rates are close, so demographic parity nearly holds.")
    print("  The error rates are not close. Group B is approved less often when it")
    print("  should be, and approved more often when it should not.")


# ------------------------------------------------------------------ criteria

def show_criteria():
    print("\n\nSTEP 2  three criteria that cannot all hold\n")
    print("  Give two groups the same true positive rate and the same false positive")
    print("  rate, so the errors are equal. They differ only in how many applicants")
    print("  deserve a yes, the base rate.\n")
    tpr, fpr = 0.8, 0.1
    print(f"  {'':<10}{'base rate':>10}{'TP':>6}{'FN':>6}{'FP':>6}{'TN':>6}{'precision':>11}{'approved':>10}")
    print("  " + "-" * 65)
    for name, base in (("group C", 0.5), ("group D", 0.2)):
        n = 1000
        pos, neg = round(n * base), round(n * (1 - base))
        tp, fp = round(pos * tpr), round(neg * fpr)
        print(f"  {name:<10}{base:>10.2f}{tp:>6}{pos - tp:>6}{fp:>6}{neg - fp:>6}{tp / (tp + fp):>11.3f}{(tp + fp) / n:>10.2f}")
    print("\n  Equal true positive rates and equal false positive rates force unequal")
    print("  precision and unequal approval rates, because both depend on how common")
    print("  the positives are. Making precision equal would break an error rate.")


# -------------------------------------------------------------- association

def dot(u, v):
    return sum(a * b for a, b in zip(u, v))


def norm(u):
    return math.sqrt(dot(u, u))


def cos(u, v):
    return dot(u, v) / (norm(u) * norm(v))


def mean(xs):
    return sum(xs) / len(xs)


def std(xs):
    m = mean(xs)
    return math.sqrt(sum((x - m) ** 2 for x in xs) / (len(xs) - 1))


# Four dimensions: two that carry gender, two that carry topic. The first pair
# of attribute words defines the bias direction, the second pair is held out.
ATTR1_A = [(1.0, 0.6, 0.0, 0.0), (1.1, 0.5, 0.0, 0.0), (0.9, 0.7, 0.0, 0.0)]   # he, man, male
ATTR1_B = [(-1.0, -0.6, 0.0, 0.0), (-1.1, -0.5, 0.0, 0.0), (-0.9, -0.7, 0.0, 0.0)]  # she, woman, female
ATTR2_A = [(0.6, 0.8, 0.0, 0.0), (0.5, 0.9, 0.0, 0.0), (0.7, 0.7, 0.0, 0.0)]    # his, boy, father
ATTR2_B = [(-0.6, -0.8, 0.0, 0.0), (-0.5, -0.9, 0.0, 0.0), (-0.7, -0.7, 0.0, 0.0)]  # hers, girl, mother
CAREER = [(0.5, 0.4, 1.0, 0.0), (0.6, 0.3, 0.9, 0.1), (0.4, 0.5, 1.1, 0.0)]      # executive, engineer, salary
FAMILY = [(-0.5, -0.4, 0.0, 1.0), (-0.6, -0.3, 0.1, 0.9), (-0.4, -0.5, 0.0, 1.1)]  # home, nurse, children


def weat(X, Y, A, B):
    """Effect size of the Word Embedding Association Test."""
    def s(w):
        return mean([cos(w, a) for a in A]) - mean([cos(w, b) for b in B])
    sx, sy = [s(w) for w in X], [s(w) for w in Y]
    return (mean(sx) - mean(sy)) / std(sx + sy), sx, sy


def project_out(v, g):
    c = dot(v, g) / dot(g, g)
    return tuple(a - c * b for a, b in zip(v, g))


def show_weat():
    print("\n\nSTEP 3  an association score, and debiasing by projection\n")
    print("  Targets: career words against family words. Attributes: male words")
    print("  against female words. Effect size d is the difference of the mean")
    print("  associations divided by their standard deviation.\n")
    d1, _, _ = weat(CAREER, FAMILY, ATTR1_A, ATTR1_B)
    d2, _, _ = weat(CAREER, FAMILY, ATTR2_A, ATTR2_B)
    print(f"  WEAT with attribute set 1 (used to find the direction)   d = {d1:+.3f}")
    print(f"  WEAT with attribute set 2 (held out)                     d = {d2:+.3f}")

    g = tuple(mean([a[i] for a in ATTR1_A]) - mean([b[i] for b in ATTR1_B]) for i in range(4))
    print(f"\n  bias direction g = mean(male) - mean(female) = "
          f"({g[0]:.3f}, {g[1]:.3f}, {g[2]:.3f}, {g[3]:.3f})")

    def along_g(vs):
        return mean([cos(v, g) for v in vs])

    def proj(vs):
        return [project_out(v, g) for v in vs]
    print("\n  Mean cosine with g, before and after subtracting each vector's")
    print("  component along g:\n")
    print(f"  {'':<10}{'before':>9}{'after':>9}")
    print("  " + "-" * 28)
    for name, vs in (("career", CAREER), ("family", FAMILY)):
        after = [project_out(v, g) for v in vs]
        c = round(mean([dot(v, g) / (norm(v) * norm(g)) for v in after]), 9) + 0.0
        print(f"  {name:<10}{along_g(vs):>+9.3f}{c:>+9.3f}")
    dp, _, _ = weat(proj(CAREER), proj(FAMILY), proj(ATTR2_A), proj(ATTR2_B))
    print(f"\n  WEAT with the held-out set 2 after projection   d = {dp:+.3f}")
    print("\n  The direction score is zero because the direction has been deleted.")
    print("  The held-out test still sees a large association, because gender")
    print("  information also lives in other directions.")


# ------------------------------------------------------------ counterfactual

NAMES = ["Emily", "Greg", "Lakisha", "Jamal"]
TEMPLATES = ["{} said the delivery was fine.", "{} called the service adequate.",
             "{} described the staff as helpful but slow."]
LEXICON = {"fine": 0.3, "adequate": 0.2, "helpful": 0.5, "slow": -0.5}
NAME_LEAK = {"Emily": 0.2, "Greg": 0.2, "Lakisha": -0.2, "Jamal": -0.3}


def toy_sentiment(text):
    """Positive when the lexicon sum, plus a flaw the model has learned from a corpus, is above zero."""
    name = text.split()[0]
    return sum(LEXICON.get(w.strip(".,"), 0.0) for w in text.split()) + NAME_LEAK[name] > 0


def show_counterfactual():
    print("\n\nSTEP 4  swap one name, count how often the output moves\n")
    print("  A toy sentiment model with a deliberate flaw: it adds a small amount")
    print("  for or against the name, as a corpus-trained model might.\n")
    print(f"  {'sentence':<46}" + "".join(f"{n:>9}" for n in NAMES))
    print("  " + "-" * 82)
    flips = total = 0
    for t in TEMPLATES:
        preds = [toy_sentiment(t.format(n)) for n in NAMES]
        print(f"  {t.format('NAME'):<46}" + "".join(f"{'pos' if p else 'neg':>9}" for p in preds))
        for p, q in combinations(preds, 2):
            total += 1
            flips += p != q
    print(f"\n  Pairs that differ only in the name: {total} ({len(NAMES)} choose 2 = "
          f"{len(list(combinations(NAMES, 2)))}, times {len(TEMPLATES)} sentences).")
    print(f"  Pairs where the prediction changed: {flips}, a rate of {flips / total:.3f}.")
    print("  A rate of zero would show nothing wrong with this attribute on these")
    print("  sentences. A rate above zero shows the model is using the name.")


# --------------------------------------------------------------- calibration

# (bin label, predictions, mean confidence, accuracy)
BINS = [("0.5-0.6", 150, 0.55, 0.52), ("0.6-0.7", 200, 0.65, 0.58),
        ("0.7-0.8", 250, 0.75, 0.66), ("0.8-0.9", 250, 0.85, 0.74),
        ("0.9-1.0", 150, 0.95, 0.83)]


def show_calibration():
    N = sum(b[1] for b in BINS)
    print("\n\nSTEP 5  confidence against accuracy, and abstaining\n")
    print(f"  {'bin':<10}{'n':>6}{'confidence':>12}{'accuracy':>10}{'gap':>8}")
    print("  " + "-" * 46)
    ece = 0.0
    for lab, n, c, a in BINS:
        ece += n / N * abs(c - a)
        print(f"  {lab:<10}{n:>6}{c:>12.2f}{a:>10.2f}{c - a:>8.2f}")
    acc = sum(n * a for _, n, _, a in BINS) / N
    print(f"\n  overall accuracy {acc:.3f}")
    print(f"  expected calibration error = sum of (n / N) x |confidence - accuracy| = {ece:.4f}")
    print("\n  The model says 0.95 and is right 83 per cent of the time.\n")
    print(f"  {'answer only above':>18}{'answered':>10}{'coverage':>10}{'accuracy':>10}")
    print("  " + "-" * 50)
    for t in (0.5, 0.7, 0.8, 0.9):
        kept = [b for b in BINS if float(b[0][:3]) >= t]
        n = sum(b[1] for b in kept)
        a = sum(b[1] * b[3] for b in kept) / n
        print(f"  {t:>18.1f}{n:>10}{n / N:>10.2f}{a:>10.3f}")
    print("\n  Abstaining trades coverage for accuracy. What it hands to a person")
    print("  is the answers the model was least sure of.")


# --------------------------------------------------------------------- drift

TRAIN = [0.40, 0.35, 0.15, 0.10]
LIVE = [0.20, 0.30, 0.25, 0.25]
BUCKETS = ["1-10 words", "11-30 words", "31-100 words", "over 100 words"]


def psi(expected, actual):
    return sum((a - e) * math.log(a / e) for e, a in zip(expected, actual))


def show_drift():
    print("\n\nSTEP 6  has the live input drifted from training?\n")
    print(f"  {'input length':<18}{'training':>10}{'live':>8}{'(live-train) x ln(live/train)':>32}")
    print("  " + "-" * 68)
    for b, e, a in zip(BUCKETS, TRAIN, LIVE):
        print(f"  {b:<18}{e:>10.2f}{a:>8.2f}{(a - e) * math.log(a / e):>32.4f}")
    v = psi(TRAIN, LIVE)
    print("  " + "-" * 68)
    print(f"  {'population stability index':<36}{v:>32.4f}")
    print("\n  A common rule of thumb reads below 0.1 as stable, 0.1 to 0.25 as a")
    print("  moderate shift and above 0.25 as a large one. This one is large.")
    print("  The check needs no labels, so it can run on every day of live traffic.")


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    for f in ("groups", "criteria", "weat", "counterfactual", "calibration", "drift"):
        ap.add_argument(f"--{f}", action="store_true")
    a = ap.parse_args()
    picked = any(vars(a).values())
    for flag, fn in (("groups", show_groups), ("criteria", show_criteria), ("weat", show_weat),
                     ("counterfactual", show_counterfactual), ("calibration", show_calibration),
                     ("drift", show_drift)):
        if getattr(a, flag) or not picked:
            fn()
    print()


if __name__ == "__main__":
    main()