Chapter 15 Text Classification and Evaluation Contents Course home

Worked exampleAccuracy, F1 and a confusion matrix

The four outcomes (TP, FP, FN, TN) and every measure built from them, the accuracy trap, the confusion matrix, the threshold-free metrics underneath, which average to trust on skewed classes, and a recurrent network as a classifier.

File classification.py Chapter 15. Text Classification and Evaluation Needs nothing but Python 3

What to try

  1. python3 classification.py

    The whole evaluation, from counts to macro-F1.

  2. python3 classification.py --outcomes

    A spam filter on 1000 emails: 80 TP, 40 FP, 20 FN, 860 TN. Accuracy 0.94, recall 0.80, specificity 0.9556, precision 0.6667, and the same precision falling to 0.1538 when spam is 1 per cent of the mail.

  3. python3 classification.py --trap

    A four-class model scoring 0.90 accuracy and 0.24 macro-F1 by always answering the majority class. Three classes score exactly zero and accuracy does not notice.

  4. python3 classification.py --read

    The hardest class and the most confused pair, computed rather than judged. government has the lowest F1 at 0.6364, and news and government exchange 5 documents.

  5. python3 classification.py --threshold

    Precision, recall and F1 describe one cut through a ranking. The same ordering scores ROC-AUC 0.9490 and PR-AUC 0.2667 once the positive class is rare, and only the second describes what a user would experience.

  6. python3 classification.py --calibration

    A score of 0.9 should mean right nine times in ten. The most confident bin here promises 0.95 and delivers 0.40, an expected calibration error of 0.247, and no ranking metric would notice.

  7. python3 classification.py --rank

    Three classifiers on one skewed test set. Accuracy, the news F1 and the weighted F1 all crown C, which never finds a learned document. Macro-F1 crowns B, 0.6971 against 0.5544.

  8. python3 classification.py --recurrent

    One sentence through an RNN, an LSTM and a GRU into the same classification head. Last, mean and max pooling give losses 0.4174, 0.6433 and 0.8355, and with only the last state the error reaching the first word is 0.30 of what it is at the last.

The source

"""Evaluating a classifier, worked as Chapter 15 works it.

Nine things, all reproducing the chapter's tables:

    the four outcomes    TP, FP, FN and TN, and every measure built from them
    the accuracy trap    a useless model with 90 per cent accuracy
    the confusion matrix per-class precision, recall and F1, computed
    reading the matrix   hardest class and most-confused pair, derived
    macro against micro  why they differ, and when they cannot
    the threshold sweep  ROC and PR from one ranked list, and their areas
    calibration          a model that ranks well and lies about probability
    a recurrent classifier  one sentence through an RNN, an LSTM and a GRU
    which score is best   three classifiers on one skewed test set, and who
                          each score crowns

    python3 classification.py              # all nine
    python3 classification.py --outcomes   # the 2 x 2 table and its measures
    python3 classification.py --trap       # the accuracy trap
    python3 classification.py --matrix     # the full per-class table
    python3 classification.py --read       # hardest class, confused pairs
    python3 classification.py --averages   # macro, micro and accuracy
    python3 classification.py --threshold  # ROC-AUC against PR-AUC
    python3 classification.py --calibration# scores that are not probabilities
    python3 classification.py --recurrent  # RNN, LSTM, GRU as a classifier
    python3 classification.py --rank       # which score picks the right model

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

import argparse
import math

# The genre confusion matrix from the lectures. Rows are the true class,
# columns the predicted class. Twelve documents of each genre.
GENRES = ["news", "fiction", "government", "learned"]
MATRIX = [
    [9, 0, 2, 1],     # news
    [0, 11, 0, 1],    # fiction
    [3, 0, 7, 2],     # government
    [1, 1, 1, 9],     # learned
]


def counts(M, i):
    """TP, FP, FN for class i, treating the task as one against the rest."""
    tp = M[i][i]
    fp = sum(M[r][i] for r in range(len(M))) - tp
    fn = sum(M[i]) - tp
    return tp, fp, fn


def prf(tp, fp, fn):
    p = tp / (tp + fp) if tp + fp else 0.0
    r = tp / (tp + fn) if tp + fn else 0.0
    f = 2 * p * r / (p + r) if p + r else 0.0
    return p, r, f


def macro_f1(M):
    return sum(prf(*counts(M, i))[2] for i in range(len(M))) / len(M)


def accuracy(M):
    return sum(M[i][i] for i in range(len(M))) / sum(sum(r) for r in M)


# ------------------------------------------------- a recurrent classifier

# The sentence and the weights are those of Chapters 12 and 13, so the numbers
# here continue theirs. Embeddings and the plain RNN come from Chapter 12, and
# the LSTM and GRU gates from the one step Chapter 13 worked. Two units, input
# of size two. The weights are chosen, not trained, so the predictions mean
# nothing. The shapes and the flow of the signal are the point.
WORDS = ["the", "dog", "ran"]
EMB = {"the": [0.50, -0.20], "dog": [0.10, 0.80], "ran": [-0.60, 0.30]}
RNN_W = [[0.60, -0.30], [0.20, 0.50]]
RNN_U = [[0.40, 0.10], [-0.20, 0.70]]
RNN_B = [0.05, -0.05]
GATE_F = [[0.3, -0.2, 0.5, 0.1], [0.1, 0.4, -0.3, 0.2]]     # forget; GRU update
GATE_I = [[-0.2, 0.3, 0.4, -0.1], [0.5, -0.1, 0.2, 0.3]]    # input;  GRU reset
GATE_C = [[0.4, 0.1, -0.2, 0.5], [-0.3, 0.2, 0.6, -0.1]]    # candidate
GATE_O = [[0.2, 0.5, 0.1, -0.3], [0.4, -0.2, 0.3, 0.2]]     # output
# The classification head: two scores, one for each class.
CLASSES = ["negative", "positive"]
HEAD = [[0.9, -0.4], [-0.5, 0.7]]


def matvec(M, v):
    return [sum(a * b for a, b in zip(row, v)) for row in M]


def vadd(a, b):
    return [x + y for x, y in zip(a, b)]


def sigmoid(v):
    return [1 / (1 + math.exp(-x)) for x in v]


def softmax(z):
    m = max(z)
    e = [math.exp(x - m) for x in z]
    return [x / sum(e) for x in e]


def rnn_states(xs):
    h, out = [0.0, 0.0], []
    for x in xs:
        a = vadd(vadd(matvec(RNN_W, x), matvec(RNN_U, h)), RNN_B)
        h = [math.tanh(v) for v in a]
        out.append(h)
    return out


def lstm_states(xs):
    h, c, out = [0.0, 0.0], [0.0, 0.0], []
    for x in xs:
        q = h + x
        f = sigmoid([v + 1.0 for v in matvec(GATE_F, q)])      # b_f = 1
        i = sigmoid(matvec(GATE_I, q))
        ct = [math.tanh(v) for v in matvec(GATE_C, q)]
        o = sigmoid(matvec(GATE_O, q))
        c = [fi * ci + ii * ti for fi, ci, ii, ti in zip(f, c, i, ct)]
        h = [oi * math.tanh(ci) for oi, ci in zip(o, c)]
        out.append(h)
    return out


def gru_states(xs):
    h, out = [0.0, 0.0], []
    for x in xs:
        q = h + x
        z = sigmoid(matvec(GATE_F, q))
        r = sigmoid(matvec(GATE_I, q))
        ht = [math.tanh(v) for v in matvec(GATE_C, [ri * hi for ri, hi in zip(r, h)] + x)]
        h = [(1 - zi) * hi + zi * ti for zi, hi, ti in zip(z, h, ht)]
        out.append(h)
    return out


def classify(r, target=1):
    """The head: scores, probabilities, and the cross-entropy loss."""
    z = matvec(HEAD, r)
    p = softmax(z)
    return z, p, -math.log(p[target])


def vec(a):
    return "(" + ", ".join(f"{v:+.4f}" for v in a) + ")"


def norm(a):
    return math.sqrt(sum(v * v for v in a))


def show_recurrent():
    xs = [EMB[w] for w in WORDS]
    states = rnn_states(xs)
    print("\n\nSTEP 8  a recurrent network as a classifier\n")
    print("  Beyond the leaderboard task: the evaluation above does not care how")
    print("  the scores are produced, so here is one more way to produce them.\n")
    print("  Chapter 12 built a state h_t that summarises everything read so")
    print("  far. A classifier needs one decision per document, so it takes a")
    print("  vector r from the states and gives it to a linear layer and a softmax:\n")
    print("    words -> embeddings -> RNN / LSTM / GRU -> r -> W_c r + b_c -> softmax\n")
    print("  The sentence is 'the dog ran', the weights are Chapter 12's, and the")
    print("  label is positive. The weights are chosen, not trained, so the")
    print("  predictions mean nothing. The flow of the signal is the point.\n")
    print(f"  {'t':>2}{'word':>6}{'x_t':>21}{'h_t':>21}")
    print("  " + "-" * 52)
    for t, (w, x, h) in enumerate(zip(WORDS, xs, states), start=1):
        print(f"  {t:>2}{w:>6}{vec(x):>21}{vec(h):>21}")

    print(f"\n  Which vector goes to the head? Three common choices:\n")
    pooled = [("last state", states[-1]),
              ("mean of states", [sum(h[k] for h in states) / 3 for k in range(2)]),
              ("max of states", [max(h[k] for h in states) for k in range(2)])]
    print(f"  {'r':<16}{'value':>21}{'scores':>21}{'P(neg), P(pos)':>20}{'loss':>8}")
    print("  " + "-" * 86)
    for name, r in pooled:
        z, p, loss = classify(r)
        print(f"  {name:<16}{vec(r):>21}{vec(z):>21}"
              f"{'(' + f'{p[0]:.4f}, {p[1]:.4f}' + ')':>20}{loss:>8.4f}")
    print("\n  The loss is -log of the probability given to the true class,")
    print("  the same cross-entropy as Chapters 11 and 12, now once per document.")

    # ---- where the learning signal goes
    print("\n\n  ONE LOSS, AND WHERE ITS ERROR GOES\n")
    print("  Backpropagation through time (Chapter 12) now starts from a single")
    print("  loss. With the last state, the error enters at step 3 only and has")
    print("  to be carried back through U. With mean pooling every step receives")
    print("  its own share of the error, a third each, before the carried part.\n")
    z, p, _ = classify(states[-1])
    d = [p[0] - 0.0, p[1] - 1.0]                      # y_hat - y
    HT = [[HEAD[j][k] for j in range(2)] for k in range(2)]
    UT = [[RNN_U[j][k] for j in range(2)] for k in range(2)]
    own = matvec(HT, d)
    last = {}
    nxt = [0.0, 0.0]
    for k in (3, 2, 1):
        h = states[k - 1]
        enter = own if k == 3 else [0.0, 0.0]
        raw = vadd(enter, matvec(UT, nxt)) if k < 3 else enter
        last[k] = [r * (1 - hh * hh) for r, hh in zip(raw, h)]
        nxt = last[k]
    r_mean = pooled[1][1]
    zm, pm, _ = classify(r_mean)
    dm = [pm[0], pm[1] - 1.0]
    share = [v / 3 for v in matvec(HT, dm)]
    mean = {}
    nxt = [0.0, 0.0]
    for k in (3, 2, 1):
        h = states[k - 1]
        raw = vadd(share, matvec(UT, nxt)) if k < 3 else share
        mean[k] = [r * (1 - hh * hh) for r, hh in zip(raw, h)]
        nxt = mean[k]
    print(f"  {'step':>5}{'word':>6}{'|delta|, last state':>22}{'|delta|, mean pooling':>24}")
    print("  " + "-" * 57)
    for k in (3, 2, 1):
        print(f"  {k:>5}{WORDS[k - 1]:>6}{norm(last[k]):>22.4f}{norm(mean[k]):>24.4f}")
    print(f"\n  Last state: the error at 'the' is {norm(last[1]) / norm(last[3]):.2f} of what")
    print("  it is at 'ran', after only two steps back. Mean pooling gives the")
    print("  first word more than the last. In a long document that matters.")

    # ---- swap the cell
    print("\n\n  SWAP THE CELL, KEEP THE HEAD\n")
    print("  An LSTM (Chapter 13, b_f = 1) or a GRU produces h_3 in place of the")
    print("  RNN's. The head, the loss and every metric after this are unchanged.\n")
    print(f"  {'cell':<8}{'h_3':>21}{'P(neg), P(pos)':>20}{'loss':>8}")
    print("  " + "-" * 57)
    for name, fn in (("RNN", rnn_states), ("LSTM", lstm_states), ("GRU", gru_states)):
        h3 = fn(xs)[-1]
        z, p, loss = classify(h3)
        print(f"  {name:<8}{vec(h3):>21}{'(' + f'{p[0]:.4f}, {p[1]:.4f}' + ')':>20}{loss:>8.4f}")
    print("\n  The numbers differ because the weights are different. Nothing here")
    print("  shows one cell classifying better. What changes with the cell is")
    print("  what survives a long document:\n")
    print(f"  {'tokens':>8}{'RNN, factor 0.9':>18}{'LSTM, f = 0.99':>17}")
    print("  " + "-" * 43)
    for n in (10, 50, 200):
        print(f"  {n:>8}{0.9 ** (n - 1):>18.3e}{0.99 ** (n - 1):>17.3e}")
    print("\n  That is the gradient reaching the first word of an n-token document")
    print("  when only the last state is classified. At 200 tokens the plain")
    print("  RNN has lost it, and an LSTM with a forget gate near 1 has not.")

    print("\n\n  BIDIRECTIONAL, FOR CLASSIFICATION\n")
    print("  Chapter 12 noted that a bidirectional RNN cannot generate text, since")
    print("  the backward pass needs words not yet written. A classifier reads")
    print("  the whole document, so it can. Run one recurrence each way and give")
    print("  the head both final states joined:\n")
    print("    r = [forward h_T ; backward h_1]      size 2H, so W_c is C x 2H")
    print("\n  With H = 2 here that is a vector of four numbers instead of two,")
    print("  and the head for C classes holds 2 H C weights instead of H C.")


# ------------------------------------------------------- the four outcomes

def four(tp, fp, fn, tn):
    """Every measure the chapter builds from the 2 x 2 table.

    A ratio whose denominator is zero is reported as 0.0, which is what the
    chapter's tables print and what sklearn's zero_division=0 gives.
    """
    def div(a, b):
        return a / b if b else 0.0
    n = tp + fp + fn + tn
    prec, rec = div(tp, tp + fp), div(tp, tp + fn)
    spec = div(tn, tn + fp)
    f1 = div(2 * prec * rec, prec + rec)
    f2 = div(5 * prec * rec, 4 * prec + rec)
    root = ((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) ** 0.5
    return {"n": n, "accuracy": div(tp + tn, n), "error": div(fp + fn, n),
            "precision": prec, "recall": rec, "specificity": spec,
            "fpr": div(fp, fp + tn), "fnr": div(fn, fn + tp),
            "npv": div(tn, tn + fn), "f1": f1, "f2": f2,
            "balanced": (rec + spec) / 2,
            "mcc": div(tp * tn - fp * fn, root)}


# A spam filter on a thousand emails, a hundred of them spam. Spam is the
# positive class, because it is the thing being looked for.
SPAM = dict(tp=80, fp=40, fn=20, tn=860)


def show_outcomes():
    t = SPAM
    m = four(**t)
    print("\nSTEP 1  the four outcomes, and everything built from them\n")
    print("  A spam filter reads 1000 emails. A hundred are spam, which is the")
    print("  positive class because it is the thing being looked for. It flags")
    print("  120 emails as spam. Every email lands in exactly one of four cells:\n")
    print(f"  {'':<18}{'flagged spam':>14}{'passed':>10}{'total':>8}")
    print("  " + "-" * 50)
    print(f"  {'really spam':<18}{'TP = ' + str(t['tp']):>14}"
          f"{'FN = ' + str(t['fn']):>10}{t['tp'] + t['fn']:>8}")
    print(f"  {'really not spam':<18}{'FP = ' + str(t['fp']):>14}"
          f"{'TN = ' + str(t['tn']):>10}{t['fp'] + t['tn']:>8}")
    print(f"  {'total':<18}{t['tp'] + t['fp']:>14}{t['fn'] + t['tn']:>10}"
          f"{m['n']:>8}")
    print("\n  TP  true positive   spam, flagged        a correct catch")
    print("  FP  false positive  not spam, flagged    a good email lost")
    print("  FN  false negative  spam, passed         spam in the inbox")
    print("  TN  true negative   not spam, passed     a correct pass")

    print("\n  Each measure is a ratio of these four counts. The question is")
    print("  which cells it puts on top and which on the bottom:\n")
    rows = [
        ("accuracy", "(TP + TN) / all", f"({t['tp']} + {t['tn']}) / {m['n']}", m["accuracy"]),
        ("error rate", "(FP + FN) / all", f"({t['fp']} + {t['fn']}) / {m['n']}", m["error"]),
        ("recall, TPR", "TP / (TP + FN)", f"{t['tp']} / {t['tp'] + t['fn']}", m["recall"]),
        ("miss rate, FNR", "FN / (TP + FN)", f"{t['fn']} / {t['tp'] + t['fn']}", m["fnr"]),
        ("specificity, TNR", "TN / (TN + FP)", f"{t['tn']} / {t['tn'] + t['fp']}", m["specificity"]),
        ("false positive rate", "FP / (TN + FP)", f"{t['fp']} / {t['tn'] + t['fp']}", m["fpr"]),
        ("precision, PPV", "TP / (TP + FP)", f"{t['tp']} / {t['tp'] + t['fp']}", m["precision"]),
        ("NPV", "TN / (TN + FN)", f"{t['tn']} / {t['tn'] + t['fn']}", m["npv"]),
    ]
    print(f"  {'measure':<22}{'formula':<18}{'here':<20}{'value':>8}")
    print("  " + "-" * 68)
    for name, formula, here, v in rows:
        print(f"  {name:<22}{formula:<18}{here:<20}{v:>8.4f}")

    print("\n  Read them in pairs. Recall and miss rate share a denominator,")
    print("  the real spam, so they add to 1. Specificity and the false")
    print("  positive rate share the real non-spam and also add to 1.")
    print("  Precision and NPV take their denominators from the predictions.")

    print("\n\n  F1 AND ITS RELATIVES\n")
    print(f"  F1  = 2 P R / (P + R)         = {m['f1']:.4f}")
    print(f"  F2  = 5 P R / (4 P + R)       = {m['f2']:.4f}   recall counts four times as much")
    print(f"  balanced accuracy = (R + TNR) / 2 = {m['balanced']:.4f}")
    print(f"  MCC = (TP*TN - FP*FN) / sqrt((TP+FP)(TP+FN)(TN+FP)(TN+FN))")
    print(f"      = ({t['tp']}*{t['tn']} - {t['fp']}*{t['fn']}) / sqrt("
          f"{t['tp'] + t['fp']}*{t['tp'] + t['fn']}*{t['tn'] + t['fp']}*{t['tn'] + t['fn']})"
          f" = {m['mcc']:.4f}")
    print("\n  F1 and F2 never use TN. Balanced accuracy and MCC use all four.")

    print("\n\n  THE FILTER THAT FLAGS NOTHING\n")
    z = four(tp=0, fp=0, fn=100, tn=900)
    print("  A filter that lets everything through has TP 0, FP 0, FN 100, TN 900.\n")
    print(f"  accuracy {z['accuracy']:.4f}   recall {z['recall']:.4f}   "
          f"specificity {z['specificity']:.4f}")
    print(f"  precision is 0/0 here, and is reported as {z['precision']:.4f}")
    print("\n  Ninety per cent accuracy, and it has never caught a single spam.")
    print("  Accuracy rewards the 900 true negatives. Recall refuses to.")

    print("\n\n  ONE MODEL, THREE THRESHOLDS\n")
    print("  The same filter, flagging more or fewer emails by moving its cut:\n")
    pts = [("strict", dict(tp=60, fp=6, fn=40, tn=894)),
           ("middle", SPAM),
           ("loose", dict(tp=95, fp=135, fn=5, tn=765))]
    print(f"  {'cut':<8}{'TP':>5}{'FP':>5}{'FN':>5}{'TN':>6}"
          f"{'precision':>11}{'recall':>8}{'FPR':>8}{'F1':>8}")
    print("  " + "-" * 64)
    for name, c in pts:
        q = four(**c)
        print(f"  {name:<8}{c['tp']:>5}{c['fp']:>5}{c['fn']:>5}{c['tn']:>6}"
              f"{q['precision']:>11.4f}{q['recall']:>8.4f}{q['fpr']:>8.4f}{q['f1']:>8.4f}")
    print("\n  Recall and the false positive rate rise together as the cut")
    print("  loosens, and precision falls. No cut is best in every column.")

    print("\n\n  THE SAME FILTER ON A RARER CLASS\n")
    print(f"  Recall {m['recall']:.4f} and false positive rate {m['fpr']:.4f} describe the")
    print("  filter. They do not change with how much spam there is. Precision")
    print("  does, because it divides by what was flagged, which includes the")
    print("  false alarms from a bigger pile of good email.\n")
    print(f"  {'spam share':<12}{'spam':>7}{'not spam':>10}{'TP':>6}{'FP':>6}"
          f"{'precision':>11}")
    print("  " + "-" * 52)
    shown = []
    for share, spam, ham in (("50%", 900, 900), ("10%", 100, 900), ("1%", 100, 9900)):
        tp = round(spam * m["recall"])
        fp = round(ham * m["fpr"])
        shown.append(tp / (tp + fp))
        print(f"  {share:<12}{spam:>7}{ham:>10}{tp:>6}{fp:>6}"
              f"{tp / (tp + fp):>11.4f}")
    print(f"\n  Same recall, same false positive rate. Precision falls from")
    print(f"  {shown[0]:.4f} to {shown[-1]:.4f} because the spam became rare. A precision")
    print("  figure without the class balance behind it says very little.")


# ------------------------------------------------------------ the trap

def show_trap():
    """Imbalanced classes, and a model that has learned nothing."""
    support = [90, 5, 3, 2]
    labels = ["news", "fiction", "government", "learned"]

    # Everything predicted as the majority class.
    M = [[0] * 4 for _ in range(4)]
    for i, n in enumerate(support):
        M[i][0] = n

    print("\nSTEP 2  why accuracy is not enough\n")
    print("  A hundred test documents, unevenly distributed:")
    print("    " + ",  ".join(f"{l} {n}" for l, n in zip(labels, support)))
    print("\n  The model is a single line of code: always answer 'news'.\n")
    print(f"  {'true class':<12}" + "".join(f"{l[:7]:>10}" for l in labels))
    print("  " + "-" * 52)
    for i, l in enumerate(labels):
        print(f"  {l:<12}" + "".join(f"{v:>10}" for v in M[i]))

    print(f"\n  {'class':<12}{'P':>9}{'R':>9}{'F1':>9}")
    print("  " + "-" * 40)
    for i, l in enumerate(labels):
        p, r, f = prf(*counts(M, i))
        print(f"  {l:<12}{p:>9.4f}{r:>9.4f}{f:>9.4f}")

    print(f"\n  accuracy  {accuracy(M):.4f}")
    print(f"  macro-F1  {macro_f1(M):.4f}")
    print("\n  Ninety per cent accuracy, and the model cannot tell any two")
    print("  documents apart. Three of the four classes score exactly zero.")
    print("\n  Macro-F1 sees it immediately, because it averages the per-class")
    print("  scores and a class the model ignores contributes 0 to that mean.")
    print("\n  This is why Assignment 5's leaderboard uses macro-F1. You cannot")
    print("  win it by chasing the majority class.")


# -------------------------------------------------------- the real matrix

def show_matrix():
    print("\n\nSTEP 3  a real confusion matrix, scored\n")
    print("  Rows are the true class, columns the prediction.")
    print("  The diagonal is correct. Everything else is an error.\n")
    print(f"  {'true / pred':<13}" + "".join(f"{g[:7]:>10}" for g in GENRES)
          + f"{'total':>9}")
    print("  " + "-" * 62)
    for i, g in enumerate(GENRES):
        cells = "".join(f"{v:>10}" for v in MATRIX[i])
        print(f"  {g:<13}{cells}{sum(MATRIX[i]):>9}")
    print("  " + "-" * 62)
    cols = "".join(f"{sum(MATRIX[r][c] for r in range(4)):>10}" for c in range(4))
    print(f"  {'predicted':<13}{cols}{sum(sum(r) for r in MATRIX):>9}")

    n = sum(sum(r) for r in MATRIX)
    print(f"\n  Now one row per class, treating each as one against the rest.")
    print(f"  The true negatives are everything that is neither a TP, an FP")
    print(f"  nor an FN, so TN = {n} - TP - FP - FN. For news that is")
    tp, fp, fn = counts(MATRIX, 0)
    print(f"  {n} - {tp} - {fp} - {fn} = {n - tp - fp - fn}.")
    print(f"  Check: TP + FN = {tp + fn} is the row total, TP + FP = {tp + fp} is the")
    print(f"  column total.\n")
    print(f"  {'class':<12}{'TP':>5}{'FP':>5}{'FN':>5}{'TN':>5}{'P':>9}{'R':>9}"
          f"{'F1':>9}{'spec.':>9}")
    print("  " + "-" * 68)
    for i, g in enumerate(GENRES):
        tp, fp, fn = counts(MATRIX, i)
        tn = n - tp - fp - fn
        p, r, f = prf(tp, fp, fn)
        print(f"  {g:<12}{tp:>5}{fp:>5}{fn:>5}{tn:>5}{p:>9.4f}{r:>9.4f}{f:>9.4f}"
              f"{tn / (tn + fp):>9.4f}")
    print("\n  The four counts of each row add to 48, the size of the test set.")
    print("  Precision, recall and F1 never touch TN, which is why they can be")
    print("  computed from the three counts alone.")

    print(f"\n  accuracy  {accuracy(MATRIX):.4f}")
    print(f"  macro-F1  {macro_f1(MATRIX):.4f}")
    print("\n  Here the classes are balanced at twelve each, so accuracy is")
    print("  not misleading. It is still less informative: it says 0.75 and")
    print("  stops, where the per-class table says which genre is failing.")

    print("\n  Look at 'government'. Its recall is 0.5833, the lowest in the")
    print("  table, because five of its twelve documents went elsewhere.")
    print("  Precision is 0.7000, because three documents from other genres")
    print("  were labelled government. Both directions are wrong at once.")


# ------------------------------------------------------- reading the matrix

def show_read():
    print("\n\nSTEP 4  two diagnoses the matrix hands you\n")
    f1 = [(prf(*counts(MATRIX, i))[2], GENRES[i]) for i in range(len(GENRES))]
    f1.sort()
    print("  HARDEST CLASS is the lowest per-class F1.\n")
    for f, g in f1:
        print(f"    {g:<12}{f:>9.4f}")
    print(f"\n    hardest: {f1[0][1]}")

    print("\n  MOST-CONFUSED PAIR is the unordered pair with the most cross")
    print("  errors. Add the two off-diagonal cells that join them.\n")
    pairs = []
    for i in range(len(GENRES)):
        for j in range(i + 1, len(GENRES)):
            total = MATRIX[i][j] + MATRIX[j][i]
            pairs.append((total, GENRES[i], GENRES[j],
                          MATRIX[i][j], MATRIX[j][i]))
    pairs.sort(reverse=True)
    print(f"  {'pair':<26}{'i->j':>6}{'j->i':>6}{'total':>8}")
    print("  " + "-" * 48)
    for t, a, b, ab, ba in pairs:
        print(f"  {a + ' / ' + b:<26}{ab:>6}{ba:>6}{t:>8}")
    print(f"\n    most confused: {pairs[0][1]} and {pairs[0][2]}, {pairs[0][0]}"
          f" errors")

    print("\n  Both answers are properties of the matrix, not opinions. Two")
    print("  people reading the same matrix must reach the same pair.")
    print("\n  Note that the errors are directional. Government loses 3")
    print("  documents to news and takes 2 back, which are different")
    print("  mistakes with different causes.")


# --------------------------------------------------------- macro and micro

def show_averages():
    print("\n\nSTEP 5  macro, micro, and why one of them is redundant\n")
    tp = sum(counts(MATRIX, i)[0] for i in range(len(GENRES)))
    fp = sum(counts(MATRIX, i)[1] for i in range(len(GENRES)))
    fn = sum(counts(MATRIX, i)[2] for i in range(len(GENRES)))
    micro = prf(tp, fp, fn)

    print("  MACRO averages the per-class F1 scores. Every class counts once,")
    print("  however rare it is.\n")
    print("  MICRO pools every decision first, then computes one F1. Frequent")
    print("  classes therefore dominate it.\n")
    print(f"  pooled TP = {tp}, FP = {fp}, FN = {fn}")
    print(f"\n  {'measure':<14}{'value':>9}")
    print("  " + "-" * 26)
    print(f"  {'accuracy':<14}{accuracy(MATRIX):>9.4f}")
    print(f"  {'micro-F1':<14}{micro[2]:>9.4f}")
    print(f"  {'macro-F1':<14}{macro_f1(MATRIX):>9.4f}")

    print("\n  Micro-F1 and accuracy are the same number, and that is not a")
    print("  coincidence. When every document gets exactly one label, every")
    print("  error is one FP and one FN at the same time, so the pooled")
    print("  precision and recall are both the fraction correct.")
    print("\n  So on single-label tasks micro-F1 tells you nothing accuracy")
    print("  did not. Report macro-F1, or report the per-class table.")

    print("\n\n  ABLATION DISCIPLINE\n")
    runs = [("unigrams, raw counts", 0.612),
            ("unigrams, tf-idf", 0.681),
            ("unigrams + bigrams, tf-idf", 0.724),
            ("+ min document frequency 2", 0.748),
            ("+ lowercasing", 0.741)]
    print(f"  {'configuration':<32}{'validation macro-F1':>20}")
    print("  " + "-" * 54)
    best = max(runs, key=lambda r: r[1])
    for name, score in runs:
        mark = "   <- best" if (name, score) == best else ""
        print(f"  {name:<32}{score:>20.3f}{mark}")

    print("\n  One factor changes per row. That is what makes it an ablation")
    print("  rather than a list of guesses.")
    print("\n  The last row went down, and reporting it is the point. An")
    print("  ablation is a record of runs you did, not of runs that worked.")
    print("\n  The best row must be the model you actually submit. If it is")
    print("  not, your experiment log and your system have diverged.")


# --------------------------------------------------------- threshold sweep
# Ten documents, scored by the model and ranked. 1 marks the rare class.
RANKED = [(0.95, 1), (0.90, 1), (0.80, 0), (0.70, 1), (0.60, 0),
          (0.50, 0), (0.40, 0), (0.30, 0), (0.20, 0), (0.10, 0)]

# The same model's behaviour on a realistically rare class: 2 positives in
# 100 documents, ranked 3rd and 10th.
RARE_RANKS, RARE_N, RARE_P = [3, 10], 100, 2


def roc_auc(ranked):
    """Area under ROC, by the rank identity rather than by trapezoids."""
    pos = [i for i, (_, y) in enumerate(sorted(ranked), 1) if y == 1]
    P, N = len(pos), len(ranked) - len(pos)
    return (sum(pos) - P * (P + 1) / 2) / (P * N)


def pr_points(ranked):
    """Precision and recall at every threshold, walking down the ranking."""
    P = sum(y for _, y in ranked)
    tp = fp = 0
    out = []
    for score, y in ranked:
        tp, fp = tp + (y == 1), fp + (y == 0)
        out.append((score, tp, fp, tp / (tp + fp), tp / P))
    return out


def average_precision(ranked):
    """Precision averaged over the thresholds where recall actually moves."""
    P = sum(y for _, y in ranked)
    tp = fp = 0
    total = 0.0
    for _, y in ranked:
        tp, fp = tp + (y == 1), fp + (y == 0)
        if y == 1:
            total += tp / (tp + fp)
    return total / P


def show_threshold():
    print("\nSTEP 6  the threshold is a separate decision\n")
    print("  Precision, recall and F1 all describe one cut through a ranking.")
    print("  Move the cut and every one of them moves. The model itself only")
    print("  produces an order, so judge the order.\n")
    print("   score  label   TP  FP  precision  recall")
    print("  " + "-" * 46)
    for (score, tp, fp, pr, rc), (_, y) in zip(pr_points(RANKED), RANKED):
        print(f"   {score:5.2f}  {y:5d}  {tp:4d}{fp:4d}   {pr:8.3f}  {rc:6.3f}")
    print("  " + "-" * 46)
    P = sum(y for _, y in RANKED)
    N = len(RANKED) - P
    print(f"\n  The same sweep with all four outcomes at each cut. There are {P}")
    print(f"  positives and {N} negatives, so TPR = TP / {P} and FPR = FP / {N}.\n")
    print("   score   TP  FP  FN  TN    TPR     FPR")
    print("  " + "-" * 42)
    pts = [(0.0, 0.0)]
    for score, tp, fp, pr, rc in pr_points(RANKED):
        fn, tn = P - tp, N - fp
        pts.append((fp / N, tp / P))
        print(f"   {score:5.2f}  {tp:3d}{fp:4d}{fn:4d}{tn:4d}  {tp / P:6.3f}  {fp / N:6.3f}")
    print("  " + "-" * 42)
    print("\n  ROC stands for receiver operating characteristic. Plot TPR (up)")
    print("  against FPR (across) and the points form the ROC curve. The points,")
    print("  from the origin, where nothing is flagged, to (1, 1), where")
    print("  everything is:\n")
    cells = [f"({x:.3f}, {y:.3f})" for x, y in pts]
    for i in range(0, len(cells), 4):
        print("    " + "  ".join(cells[i:i + 4]))
    print("\n  A model that guesses stays on the diagonal TPR = FPR, and a")
    print("  perfect one passes through the corner (0, 1). The area under the")
    print("  curve is the AUC: 0.5 for guessing, 1 for perfect. By trapezoids")
    print("  on those points:\n")
    trap = sum((x2 - x1) * (y1 + y2) / 2 for (x1, y1), (x2, y2) in zip(pts, pts[1:]))
    print(f"    trapezoid area  {trap:.4f}")
    below = []
    for i, (score, y) in enumerate(RANKED):
        if y == 1:
            below.append(sum(1 for s2, y2 in RANKED[i + 1:] if y2 == 0))
    print(f"\n  The same number by counting pairs. Each positive is compared with")
    print(f"  each of the {N} negatives, and wins if it was scored higher:\n")
    for (score, y), b in zip([r for r in RANKED if r[1] == 1], below):
        print(f"    positive scored {score:.2f} beats {b} of {N} negatives")
    print(f"\n    {sum(below)} of {P * N} pairs  =  {sum(below) / (P * N):.4f}")
    a_roc, a_pr = roc_auc(RANKED), average_precision(RANKED)
    print(f"\n  ROC-AUC {a_roc:.4f}      PR-AUC {a_pr:.4f}")
    print("\n  The precision-recall curve plots precision (up) against recall")
    print("  (across) at every cut, and PR-AUC averages the precision at the cuts")
    print("  where recall moves. Its points, as (recall, precision):\n")
    cells = [f"({rc:.3f}, {pr:.3f})" for _, _, _, pr, rc in pr_points(RANKED)]
    for i in range(0, len(cells), 5):
        print("    " + "  ".join(cells[i:i + 5]))
    print("\n  Both look strong, and on a balanced problem they usually agree.")
    print("  Now make the positive class rare, which is the normal case.\n")
    rare = [(0.0, 1) if i + 1 in RARE_RANKS else (0.0, 0) for i in range(RARE_N)]
    # ranks are given from the top of the ranking
    pos_from_bottom = [RARE_N - r + 1 for r in RARE_RANKS]
    a_roc2 = (sum(pos_from_bottom) - RARE_P * (RARE_P + 1) / 2) / (RARE_P * (RARE_N - RARE_P))
    ap2 = sum((i + 1) / r for i, r in enumerate(RARE_RANKS)) / RARE_P
    print(f"  {RARE_P} positives among {RARE_N} documents, ranked {RARE_RANKS[0]} and {RARE_RANKS[1]}:\n")
    print(f"    ROC-AUC {a_roc2:.4f}   still excellent")
    print(f"    PR-AUC  {ap2:.4f}   barely better than guessing")
    print("\n  The same ranking. ROC-AUC counts how many negatives sit below each")
    print(f"  positive, and {RARE_N - RARE_P} negatives is a lot of credit. PR-AUC asks what")
    print("  fraction of what you flagged was right, and at rank 10 that is")
    print(f"  {RARE_P}/{RARE_RANKS[1]} = {RARE_P / RARE_RANKS[1]:.2f}. Under imbalance, report PR-AUC.")


# ------------------------------------------------------------- calibration
# Three confidence bins. The model orders documents perfectly inside every
# bin, and its numbers still do not mean what they say.
BINS = [("0.6 - 0.7", 0.65, 40, 26), ("0.7 - 0.9", 0.80, 35, 17),
        ("0.9 - 1.0", 0.95, 25, 10)]


def show_calibration():
    print("\n\nSTEP 7  ranking well is not the same as being right\n")
    print("  A score of 0.9 should mean the model is right nine times in ten.")
    print("  Nothing in cross-entropy training guarantees it, and nothing in")
    print("  ROC-AUC or F1 would notice if it were false.\n")
    print("   bin         mean score      n   correct   observed   gap")
    print("  " + "-" * 56)
    tot_gap = tot_n = 0
    for name, mean, n, correct in BINS:
        obs = correct / n
        gap = mean - obs
        tot_gap += abs(gap) * n
        tot_n += n
        print(f"   {name:11} {mean:10.2f} {n:6d} {correct:9d} {obs:10.3f} {gap:+6.3f}")
    print("  " + "-" * 56)
    print(f"   expected calibration error{' ' * 26}{tot_gap / tot_n:.3f}")
    print("\n  The least confident bin is honest. The other two are not, and the")
    print(f"  most confident is the worst: it promises {BINS[-1][1]:.2f} and delivers "
          f"{BINS[-1][3] / BINS[-1][2]:.2f}.")
    print("  Over-confidence grows with the score, which is the usual shape.")
    print("  The ordering may still be perfect, so a ranking metric sees nothing")
    print("  wrong. Any decision with a cost attached needs the probability, not")
    print("  the order, and that is when this table is the one that matters.")



# ------------------------------------------------ which score is best

# One skewed test set (news 90, fiction 5, government 3, learned 2) and three
# classifiers. Rows are the true class, columns the predicted class.
RANK_MODELS = [
    ("A  always news",
     [[90, 0, 0, 0], [5, 0, 0, 0], [3, 0, 0, 0], [2, 0, 0, 0]]),
    ("B  spreads its effort",
     [[85, 3, 1, 1], [1, 4, 0, 0], [1, 0, 2, 0], [1, 0, 0, 1]]),
    ("C  chases the majority",
     [[90, 0, 0, 0], [2, 3, 0, 0], [2, 0, 1, 0], [2, 0, 0, 0]]),
]


def weighted_f1(M):
    """Per-class F1 averaged with each class weighted by its size."""
    sup = [sum(r) for r in M]
    return sum(prf(*counts(M, i))[2] * sup[i] for i in range(len(M))) / sum(sup)


def show_rank():
    print("\n\nSTEP 9  which score picks the right classifier\n")
    print("  One test set of 100 documents: news 90, fiction 5, government 3,")
    print("  learned 2. Three classifiers, each given as how many of each class")
    print("  it got right.\n")
    print(f"  {'classifier':<24}" + "".join(f"{lab:>12}" for lab in
                                          ("news /90", "fiction /5", "gov /3", "learned /2")))
    print("  " + "-" * 72)
    for name, M in RANK_MODELS:
        print(f"  {name:<24}" + "".join(f"{M[i][i]:>12}" for i in range(4)))

    scores = []
    for name, M in RANK_MODELS:
        f = [prf(*counts(M, i))[2] for i in range(4)]
        scores.append((name, accuracy(M), f, weighted_f1(M), macro_f1(M)))

    print("\n  The scores. Accuracy is also micro-F1 here.\n")
    head = (f"  {'classifier':<24}{'accuracy':>10}{'F1 news':>9}"
            f"{'F1 fict':>9}{'F1 gov':>9}{'F1 learn':>9}{'weighted':>10}{'macro':>8}")
    print(head)
    print("  " + "-" * len(head.rstrip()))
    for name, acc, f, w, m in scores:
        print(f"  {name:<24}{acc:>10.4f}{f[0]:>9.4f}{f[1]:>9.4f}{f[2]:>9.4f}"
              f"{f[3]:>9.4f}{w:>10.4f}{m:>8.4f}")

    def crown(key):
        return max(scores, key=key)[0][0]

    print("  " + "-" * len(head.rstrip()))
    print(f"  {'ranks first':<24}{crown(lambda r: r[1]):>10}{crown(lambda r: r[2][0]):>9}"
          f"{crown(lambda r: r[2][1]):>9}{crown(lambda r: r[2][2]):>9}"
          f"{crown(lambda r: r[2][3]):>9}{crown(lambda r: r[3]):>10}{crown(lambda r: r[4]):>8}")

    print("\n  Accuracy, micro-F1, the F1 of the news class and the weighted F1")
    print("  all rank C first. Each is dominated by the 90 news documents. C")
    print("  never finds a learned document and finds one government document in")
    print("  three, and those scores barely move the totals.")
    print("\n  Macro-F1 gives each class one quarter of the score, so it ranks B")
    print("  first. A single F1 is also biased by which class you call positive:")
    print("  the same classifier C scores 0.9677 on news and 0.0000 on learned.")
    print("\n  Two documents make the learned class. One more right or wrong moves")
    print("  its F1 a long way, so give the counts beside a macro-F1.")


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    for f in ("outcomes", "trap", "matrix", "read", "averages",
              "threshold", "calibration", "recurrent", "rank"):
        ap.add_argument(f"--{f}", action="store_true")
    a = ap.parse_args()
    picked = (a.outcomes or a.trap or a.matrix or a.read or a.averages
              or a.threshold or a.calibration or a.recurrent or a.rank)
    if a.outcomes or not picked:
        show_outcomes()
    if a.trap or not picked:
        show_trap()
    if a.matrix or not picked:
        show_matrix()
    if a.read or not picked:
        show_read()
    if a.averages or not picked:
        show_averages()
    if a.threshold or not picked:
        show_threshold()
    if a.calibration or not picked:
        show_calibration()
    if a.recurrent or not picked:
        show_recurrent()
    if a.rank or not picked:
        show_rank()
    print()


if __name__ == "__main__":
    main()