Homework · Runs in your browser

The interview sanity-check toolkit: confusion metrics, AUC, splits, leakage, curve diagnosis, first debugging step, base rates, intervals and FLOPs

Build the quick checks you would reach for in an ML interview, with nothing but the standard library: confusion counts and precision, recall and F1, the majority-baseline accuracy, AUC from scores, a k-fold index generator, a forward-chaining splitter for time-ordered rows, a leakage fraction, a diagnosis of a pair of error curves, a decision function that returns the first debugging step for a set of symptoms, a base-rate calculator, a Wilson interval and parameter and FLOP counters for dense networks. Edit starter.py, then run the tests. In the browser runner, press Run tests. In Colab or on your own machine, put starter.py and test_starter.py in one folder and run pytest. Nothing needs installing except pytest. Every function has its rules in the docstring.

Hints:

  • Confusion counts: the positive class is 1. A predicted 1 with a true 1 is a true positive, a predicted 1 with a true 0 is a false positive, a predicted 0 with a true 1 is a false negative. Keep the order (tp, fp, fn, tn) and reject anything that is not 0 or 1. Check: true [1, 1, 1, 0] against predicted [1, 0, 0, 0] gives (1, 0, 2, 1).
  • Precision, recall and F1: a ratio with a zero denominator is 0.0, and F1 is 0.0 when precision plus recall is 0. Check: true [1, 1, 1, 0] against predicted [1, 0, 0, 0] gives precision 1.0, recall 1/3 and F1 0.5.
  • Majority baseline: count each label and divide the biggest count by the length. Check: 99 zeros and one 1 give 0.99.
  • AUC: for every (positive, negative) pair count 1 if the positive scores higher and 0.5 if the scores tie, then divide by the number of pairs. Check: true [0, 0, 1, 1] with scores [0.1, 0.4, 0.35, 0.8] gives 0.75.
  • K-fold: the first n % k folds are one row longer, and the folds follow one another from row 0. Check: n = 10 and k = 3 give validation folds [0, 1, 2, 3], [4, 5, 6] and [7, 8, 9].
  • Forward chaining: test_size = n // (n_splits + 1). The last split ends at row n - 1 and every training set is all the rows before its test rows. Check: n = 12 and 3 splits test on rows 3 to 5, 6 to 8 and 9 to 11.
  • Leakage fraction: count each validation row, repeats included, whose id is in the training ids, and divide by the number of validation rows. Check: train [1, 2, 3] and validation [3, 4, 5, 3] gives 0.5.
  • Curve diagnosis: only the last point of each curve counts, and both comparisons are strict. A validation error below the training error is not variance.
  • First step: the rules run in the order written in the docstring and the first match wins. A missing flag counts as false, and the four numbers are needed only when no earlier rule matched.
  • Base rate: true positives are prevalence times sensitivity and false positives are (1 - prevalence) times the false-positive rate. Check: 0.01, 0.99 and 0.05 give 1/6, which is 0.1667.
  • Wilson interval: build the centre and the half width from the docstring and clip into [0, 1]. Check: 50 of 100 gives about (0.4038, 0.5962), and 0 of 10 gives a low end of exactly 0.0.
  • Parameters and FLOPs: a layer has in x out weights plus out biases, and costs 2 x batch x in x out operations in a forward pass. Check: widths 3 and 2 give 8 parameters.
  • Try it: shuffle the labels of a small problem you know and compute the AUC of a good feature. It should land near 0.5, and if it does not, you have found a leak.

Running the tests needs JavaScript. You can still read the starter code below and run it on your own machine with pytest.

Tab inserts 4 spaces. To move on with the keyboard, press Esc, then Tab. Shift+Tab always moves back.

Show a solution

Try it yourself first. This site is static, so the solution is sent to your browser with the page; it is hidden here, not secret.

import math


def confusion_counts(y_true, y_pred):
    """Return (tp, fp, fn, tn) for labels that are 0 or 1, where 1 is the positive class.

    The two lists must have the same length and hold only 0 or 1 (False and True count as 0 and 1),
    otherwise ValueError. Two empty lists give (0, 0, 0, 0).
    """
    if len(y_true) != len(y_pred):
        raise ValueError("length mismatch")
    tp = fp = fn = tn = 0
    for t, p in zip(y_true, y_pred):
        if t not in (0, 1) or p not in (0, 1):
            raise ValueError("labels must be 0 or 1")
        if p == 1 and t == 1:
            tp += 1
        elif p == 1:
            fp += 1
        elif t == 1:
            fn += 1
        else:
            tn += 1
    return tp, fp, fn, tn


def precision_recall_f1(y_true, y_pred):
    """Return (precision, recall, f1) as floats.

    precision = tp / (tp + fp), recall = tp / (tp + fn), f1 = 2 p r / (p + r).
    Any ratio with a zero denominator is 0.0 (no crash, no NaN). Bad input raises ValueError as in confusion_counts.
    """
    tp, fp, fn, _ = confusion_counts(y_true, y_pred)
    precision = tp / (tp + fp) if tp + fp else 0.0
    recall = tp / (tp + fn) if tp + fn else 0.0
    f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
    return precision, recall, f1


def majority_baseline_accuracy(y):
    """Accuracy of always predicting the most common label in y: (count of the most common label) / len(y).

    y may hold any hashable labels. An empty list raises ValueError.
    """
    if len(y) == 0:
        raise ValueError("empty labels")
    counts = {}
    for v in y:
        counts[v] = counts.get(v, 0) + 1
    return max(counts.values()) / len(y)


def auc_from_scores(y_true, scores):
    """Area under the ROC curve as the probability that a random positive outscores a random negative.

    Count 1 for every (positive, negative) pair where the positive's score is higher and 0.5 for every
    tie, then divide by the number of pairs. Labels are 0 or 1 (False and True count as 0 and 1). Different lengths, a label outside 0 and 1,
    or a list with no positive or no negative raise ValueError.
    """
    if len(y_true) != len(scores):
        raise ValueError("length mismatch")
    if any(t not in (0, 1) for t in y_true):
        raise ValueError("labels must be 0 or 1")
    pos = [s for t, s in zip(y_true, scores) if t == 1]
    neg = [s for t, s in zip(y_true, scores) if t == 0]
    if not pos or not neg:
        raise ValueError("need both classes")
    wins = 0.0
    for a in pos:
        for b in neg:
            if a > b:
                wins += 1.0
            elif a == b:
                wins += 0.5
    return wins / (len(pos) * len(neg))


def kfold_indices(n, k):
    """Contiguous k-fold splits of the row numbers 0 .. n-1, with no shuffling.

    Return a list of k pairs (train, val) of sorted lists. Fold i is validation once. The first n % k folds
    have n // k + 1 rows and the others n // k. Validation folds follow one another from row 0.
    k < 2 or k > n raises ValueError.
    """
    if k < 2 or k > n:
        raise ValueError("need 2 <= k <= n")
    base, extra = divmod(n, k)
    out = []
    start = 0
    for i in range(k):
        size = base + 1 if i < extra else base
        val = list(range(start, start + size))
        train = list(range(0, start)) + list(range(start + size, n))
        out.append((train, val))
        start += size
    return out


def forward_chain_splits(n, n_splits):
    """Forward-chaining splits for time-ordered rows 0 .. n-1.

    test_size = n // (n_splits + 1). Split i (counting from 0) tests on the rows
    [n - (n_splits - i) * test_size, n - (n_splits - i - 1) * test_size) and trains on every row before them.
    Return a list of (train, test) pairs of lists. n_splits < 1 or test_size < 1 raises ValueError.
    """
    if n_splits < 1:
        raise ValueError("n_splits must be at least 1")
    test_size = n // (n_splits + 1)
    if test_size < 1:
        raise ValueError("too few rows")
    out = []
    for i in range(n_splits):
        start = n - (n_splits - i) * test_size
        out.append((list(range(0, start)), list(range(start, start + test_size))))
    return out


def leak_fraction(train_ids, val_ids):
    """Share of validation rows whose id also appears in the training ids.

    Repeats in val_ids each count. Return 0.0 when val_ids is empty. This is the quickest leakage check:
    the same patient, user or document on both sides of the split.
    """
    if len(val_ids) == 0:
        return 0.0
    seen = set(train_ids)
    return sum(1 for v in val_ids if v in seen) / len(val_ids)


def diagnose_curves(train_err, val_err, target_err, gap_tol):
    """Read the last point of two error curves (lists, oldest first) and name the problem.

    high bias: the last training error is above target_err (strictly).
    high variance: last validation error minus last training error is above gap_tol (strictly).
    Return "ok", "high-bias", "high-variance" or "high-bias-and-variance".
    Empty lists or lists of different length raise ValueError.
    """
    if len(train_err) == 0 or len(train_err) != len(val_err):
        raise ValueError("need two curves of the same non-zero length")
    tr, va = train_err[-1], val_err[-1]
    bias = tr > target_err
    var = (va - tr) > gap_tol
    if bias and var:
        return "high-bias-and-variance"
    if bias:
        return "high-bias"
    if var:
        return "high-variance"
    return "ok"


def first_step(s):
    """First diagnostic step for a model problem. s is a dict of symptoms; the first matching rule wins.

    1. s["loss_nan"] true: "check-data-and-lr".
    2. s["loss_flat"] true: look at s.get("overfits_tiny_batch").
       None or missing: "overfit-tiny-batch". False: "fix-pipeline-bug". True: "tune-optimiser".
    3. s["leakage_suspected"] or s["suspiciously_good"] true: "audit-leakage".
    4. s["offline_online_gap"] true: "check-experiment-then-features".
    5. Otherwise use diagnose_curves-style numbers s["train_err"], s["val_err"], s["target_err"], s["gap_tol"]
       (single numbers, all required, else ValueError). high-bias gives "fix-bias", high-variance gives
       "fix-variance", both give "fix-bias-first", neither gives "error-analysis".
    A missing flag counts as false.
    """
    if s.get("loss_nan"):
        return "check-data-and-lr"
    if s.get("loss_flat"):
        tiny = s.get("overfits_tiny_batch")
        if tiny is None:
            return "overfit-tiny-batch"
        return "tune-optimiser" if tiny else "fix-pipeline-bug"
    if s.get("leakage_suspected") or s.get("suspiciously_good"):
        return "audit-leakage"
    if s.get("offline_online_gap"):
        return "check-experiment-then-features"
    for key in ("train_err", "val_err", "target_err", "gap_tol"):
        if key not in s:
            raise ValueError("missing " + key)
    verdict = diagnose_curves([s["train_err"]], [s["val_err"]], s["target_err"], s["gap_tol"])
    return {
        "high-bias": "fix-bias",
        "high-variance": "fix-variance",
        "high-bias-and-variance": "fix-bias-first",
        "ok": "error-analysis",
    }[verdict]


def ppv_from_rates(prevalence, sensitivity, fpr):
    """Positive predictive value from a base rate: P(condition | positive result).

    true positives = prevalence x sensitivity, false positives = (1 - prevalence) x fpr,
    ppv = tp / (tp + fp), or 0.0 if both are zero. Any input outside [0, 1] raises ValueError.
    """
    for v in (prevalence, sensitivity, fpr):
        if not 0 <= v <= 1:
            raise ValueError("rates must be in [0, 1]")
    tp = prevalence * sensitivity
    fp = (1 - prevalence) * fpr
    return tp / (tp + fp) if tp + fp > 0 else 0.0


def wilson_interval(successes, n, z=1.96):
    """Wilson score interval for a proportion, as (low, high), both clipped into [0, 1].

    With p = successes / n:  centre = (p + z^2 / (2n)) / (1 + z^2 / n)
    half width = z * sqrt(p (1 - p) / n + z^2 / (4 n^2)) / (1 + z^2 / n).
    n < 1, successes < 0 or successes > n raises ValueError.
    """
    if n < 1 or successes < 0 or successes > n:
        raise ValueError("bad counts")
    p = successes / n
    denom = 1 + z * z / n
    centre = (p + z * z / (2 * n)) / denom
    half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom
    return max(0.0, centre - half), min(1.0, centre + half)


def mlp_params(sizes):
    """Parameter count of a dense network with layer widths sizes, e.g. [784, 256, 10].

    Each layer has in x out weights and out biases. At least two sizes, all at least 1, else ValueError.
    """
    if len(sizes) < 2 or any(s < 1 for s in sizes):
        raise ValueError("need at least two positive sizes")
    return sum(a * b + b for a, b in zip(sizes[:-1], sizes[1:]))


def mlp_forward_flops(sizes, batch):
    """Floating-point operations of one forward pass of a dense network on a batch.

    One layer costs 2 x batch x in x out (a multiply and an add per weight). Ignore biases and activations.
    Same size rules as mlp_params, and batch < 1 raises ValueError.
    """
    if len(sizes) < 2 or any(s < 1 for s in sizes) or batch < 1:
        raise ValueError("bad sizes or batch")
    return sum(2 * batch * a * b for a, b in zip(sizes[:-1], sizes[1:]))
Show the tests (test_starter.py)

Python

import math

import pytest

from starter import (
    auc_from_scores,
    confusion_counts,
    diagnose_curves,
    first_step,
    forward_chain_splits,
    kfold_indices,
    leak_fraction,
    majority_baseline_accuracy,
    mlp_forward_flops,
    mlp_params,
    ppv_from_rates,
    precision_recall_f1,
    wilson_interval,
)


def close(a, b, tol=1e-9):
    return abs(a - b) <= tol


# ---- confusion counts, precision, recall, F1 ----------------------------------


def test_confusion_counts_order_and_roles():
    assert confusion_counts([1, 1, 0, 0, 1, 0], [1, 0, 0, 1, 1, 0]) == (2, 1, 1, 2)
    assert confusion_counts([1, 1, 1, 0], [1, 0, 0, 0]) == (1, 0, 2, 1)
    assert confusion_counts([0, 0, 0, 1], [1, 1, 1, 1]) == (1, 3, 0, 0)
    assert confusion_counts([1, 0], [0, 1]) == (0, 1, 1, 0)


def test_confusion_counts_edges():
    assert confusion_counts([], []) == (0, 0, 0, 0)
    assert confusion_counts([True, False, True], [True, True, False]) == (1, 1, 1, 0)
    assert confusion_counts([1, 1], [1, 1]) == (2, 0, 0, 0)
    assert confusion_counts([0, 0], [0, 0]) == (0, 0, 0, 2)


def test_confusion_counts_rejects_bad_input():
    bad = [([1, 0], [1]), ([1], [1, 0]), ([2, 0], [1, 0]), ([1, 0], [1, 2]), ([0.5], [1]), ([1], [0.5]), (["1"], [1]), ([-1], [0])]
    for t, p in bad:
        with pytest.raises(ValueError):
            confusion_counts(t, p)


def test_precision_recall_f1_values():
    p, r, f = precision_recall_f1([1, 1, 0, 0, 1, 0], [1, 0, 0, 1, 1, 0])
    assert close(p, 2 / 3) and close(r, 2 / 3) and close(f, 2 / 3)
    p, r, f = precision_recall_f1([1, 1, 1, 0], [1, 0, 0, 0])
    assert close(p, 1.0) and close(r, 1 / 3) and close(f, 0.5)
    p, r, f = precision_recall_f1([0, 1, 0, 0], [1, 1, 1, 0])
    assert close(p, 1 / 3) and close(r, 1.0) and close(f, 0.5)
    p, r, f = precision_recall_f1([1, 1, 0], [1, 1, 0])
    assert (p, r, f) == (1.0, 1.0, 1.0)


def test_precision_recall_f1_zero_denominators_give_zero():
    assert precision_recall_f1([1, 0], [0, 0]) == (0.0, 0.0, 0.0)
    assert precision_recall_f1([0, 0], [1, 0]) == (0.0, 0.0, 0.0)
    assert precision_recall_f1([0, 0], [0, 0]) == (0.0, 0.0, 0.0)
    assert precision_recall_f1([], []) == (0.0, 0.0, 0.0)
    p, r, f = precision_recall_f1([1, 0, 1], [0, 1, 0])
    assert (p, r, f) == (0.0, 0.0, 0.0)
    for v in precision_recall_f1([1, 0], [0, 0]):
        assert not math.isnan(v)


def test_precision_recall_f1_rejects_bad_input():
    with pytest.raises(ValueError):
        precision_recall_f1([1], [1, 0])
    with pytest.raises(ValueError):
        precision_recall_f1([1, 3], [1, 0])


# ---- majority baseline --------------------------------------------------------


def test_majority_baseline_accuracy():
    assert close(majority_baseline_accuracy([0] * 99 + [1]), 0.99)
    assert close(majority_baseline_accuracy([1] * 3 + [0] * 7), 0.7)
    assert close(majority_baseline_accuracy(["a", "b", "a"]), 2 / 3)
    assert majority_baseline_accuracy([7]) == 1.0
    assert close(majority_baseline_accuracy([1, 2]), 0.5)
    assert close(majority_baseline_accuracy([1, 2, 3, 3]), 0.5)
    assert close(majority_baseline_accuracy([1, 2, 3, 4]), 0.25)
    assert close(majority_baseline_accuracy([0, 1, 0, 1, 1]), 0.6)


def test_majority_baseline_accuracy_empty():
    with pytest.raises(ValueError):
        majority_baseline_accuracy([])


# ---- AUC ----------------------------------------------------------------------


def test_auc_known_values():
    assert close(auc_from_scores([0, 0, 1, 1], [0.1, 0.4, 0.35, 0.8]), 0.75)
    assert close(auc_from_scores([0, 0, 1, 1], [0.1, 0.2, 0.8, 0.9]), 1.0)
    assert close(auc_from_scores([0, 0, 1, 1], [0.9, 0.8, 0.2, 0.1]), 0.0)
    assert close(auc_from_scores([1, 0, 0, 0], [0.5, 0.1, 0.2, 0.9]), 2 / 3)
    assert close(auc_from_scores([False, False, True, True], [0.1, 0.4, 0.35, 0.8]), 0.75)
    assert close(auc_from_scores([True, False], [0.2, 0.9]), 0.0)
    assert close(auc_from_scores([0, 1, 0, 1], [0.1, 0.4, 0.35, 0.8]), 1.0)


def test_auc_ties_count_half():
    assert close(auc_from_scores([0, 1], [0.5, 0.5]), 0.5)
    assert close(auc_from_scores([0, 0, 1, 1], [1, 1, 1, 1]), 0.5)
    assert close(auc_from_scores([0, 1, 1, 0, 1], [0.2, 0.2, 0.9, 0.5, 0.1]), 2.5 / 6)
    assert close(auc_from_scores([0, 1], [1, 1.0]), 0.5)
    assert close(auc_from_scores([1, 0, 1], [3, 3, 4]), 0.75)


def test_auc_invariances_and_complement():
    y = [0, 1, 1, 0, 1, 0, 0, 1, 1, 0]
    s = [0.3, 0.8, 0.5, 0.4, 0.9, 0.1, 0.5, 0.2, 0.7, 0.6]
    a = auc_from_scores(y, s)
    assert close(a, 0.78)
    assert close(auc_from_scores(y, [10 * v + 3 for v in s]), a)
    assert close(auc_from_scores(y, [-v for v in s]), 1 - a)
    assert close(auc_from_scores([1 - v for v in y], s), 1 - a)


def test_auc_rejects_bad_input():
    with pytest.raises(ValueError):
        auc_from_scores([1, 1, 1], [0.1, 0.2, 0.3])
    with pytest.raises(ValueError):
        auc_from_scores([0, 0], [0.1, 0.2])
    with pytest.raises(ValueError):
        auc_from_scores([], [])
    with pytest.raises(ValueError):
        auc_from_scores([0, 1], [0.1])
    with pytest.raises(ValueError):
        auc_from_scores([0, 2, 1], [0.1, 0.2, 0.3])


# ---- k-fold and forward chaining ----------------------------------------------


def test_kfold_known_split():
    folds = kfold_indices(10, 3)
    assert len(folds) == 3
    assert [list(f[1]) for f in folds] == [[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]
    assert list(folds[0][0]) == [4, 5, 6, 7, 8, 9]
    assert list(folds[1][0]) == [0, 1, 2, 3, 7, 8, 9]
    assert list(folds[2][0]) == [0, 1, 2, 3, 4, 5, 6]
    two = kfold_indices(7, 2)
    assert [list(f[1]) for f in two] == [[0, 1, 2, 3], [4, 5, 6]]
    assert [list(f[1]) for f in kfold_indices(8, 4)] == [[0, 1], [2, 3], [4, 5], [6, 7]]
    assert [list(f[1]) for f in kfold_indices(5, 5)] == [[0], [1], [2], [3], [4]]
    assert [list(f[1]) for f in kfold_indices(11, 4)] == [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]]


def test_kfold_properties_for_many_sizes():
    for n in range(2, 16):
        for k in range(2, n + 1):
            folds = kfold_indices(n, k)
            assert len(folds) == k
            seen = []
            for train, val in folds:
                assert list(train) == sorted(train)
                assert list(val) == sorted(val)
                assert set(train).isdisjoint(val)
                assert sorted(list(train) + list(val)) == list(range(n))
                seen += list(val)
            assert sorted(seen) == list(range(n))
            sizes = [len(v) for _, v in folds]
            assert max(sizes) - min(sizes) <= 1
            assert sizes == sorted(sizes, reverse=True)
            assert sum(1 for s in sizes if s == n // k + 1) == n % k


def test_kfold_rejects_bad_k():
    for n, k in ((10, 1), (10, 0), (10, -2), (5, 6), (3, 4)):
        with pytest.raises(ValueError):
            kfold_indices(n, k)


def test_forward_chain_known_splits():
    got = forward_chain_splits(12, 3)
    assert [(list(a), list(b)) for a, b in got] == [
        ([0, 1, 2], [3, 4, 5]),
        ([0, 1, 2, 3, 4, 5], [6, 7, 8]),
        ([0, 1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11]),
    ]
    got = forward_chain_splits(10, 2)
    assert [(list(a), list(b)) for a, b in got] == [
        ([0, 1, 2, 3], [4, 5, 6]),
        ([0, 1, 2, 3, 4, 5, 6], [7, 8, 9]),
    ]
    got = forward_chain_splits(11, 2)
    assert [(list(a), list(b)) for a, b in got] == [
        ([0, 1, 2, 3, 4], [5, 6, 7]),
        ([0, 1, 2, 3, 4, 5, 6, 7], [8, 9, 10]),
    ]
    got = forward_chain_splits(10, 1)
    assert [(list(a), list(b)) for a, b in got] == [([0, 1, 2, 3, 4], [5, 6, 7, 8, 9])]
    got = forward_chain_splits(4, 3)
    assert [(list(a), list(b)) for a, b in got] == [([0], [1]), ([0, 1], [2]), ([0, 1, 2], [3])]


def test_forward_chain_never_trains_on_the_future():
    for n in range(2, 30):
        for k in range(1, 6):
            if n // (k + 1) < 1:
                continue
            got = forward_chain_splits(n, k)
            assert len(got) == k
            for train, test in got:
                assert max(train) < min(test)
                assert list(train) == list(range(len(train)))
                assert len(test) == n // (k + 1)
            assert max(got[-1][1]) <= n - 1


def test_forward_chain_rejects_bad_input():
    for n, k in ((3, 3), (2, 2), (5, 0), (10, -1), (1, 1)):
        with pytest.raises(ValueError):
            forward_chain_splits(n, k)


# ---- leakage fraction ---------------------------------------------------------


def test_leak_fraction():
    assert close(leak_fraction([1, 2, 3], [3, 4, 5, 3]), 0.5)
    assert leak_fraction([1, 2, 3], [4, 5, 6]) == 0.0
    assert leak_fraction([1, 2, 3], [1, 2, 3]) == 1.0
    assert leak_fraction([1, 2, 3], []) == 0.0
    assert leak_fraction([], [1, 2]) == 0.0
    assert close(leak_fraction(["a", "b", "a"], ["a", "c", "d", "e"]), 0.25)
    assert close(leak_fraction([1], [1, 1, 1, 2]), 0.75)
    assert close(leak_fraction([1, 1, 1, 2, 3, 4], [4, 9]), 0.5)


# ---- diagnose_curves ----------------------------------------------------------


def test_diagnose_curves_four_verdicts():
    assert diagnose_curves([0.3, 0.1, 0.02], [0.4, 0.3, 0.25], 0.05, 0.05) == "high-variance"
    assert diagnose_curves([0.3, 0.25], [0.32, 0.27], 0.1, 0.05) == "high-bias"
    assert diagnose_curves([0.3, 0.25], [0.6, 0.55], 0.1, 0.05) == "high-bias-and-variance"
    assert diagnose_curves([0.2, 0.04], [0.1, 0.06], 0.05, 0.05) == "ok"


def test_diagnose_curves_uses_last_point_only():
    assert diagnose_curves([0.9, 0.01], [0.9, 0.02], 0.05, 0.05) == "ok"
    assert diagnose_curves([0.01, 0.9], [0.01, 0.92], 0.05, 0.05) == "high-bias"
    assert diagnose_curves([0.0, 0.0, 0.01], [0.9, 0.0, 0.5], 0.05, 0.05) == "high-variance"


def test_diagnose_curves_boundaries_are_strict():
    assert diagnose_curves([0.25], [0.25], 0.25, 0.25) == "ok"
    assert diagnose_curves([0.25], [0.5], 0.25, 0.25) == "ok"
    assert diagnose_curves([0.25], [0.75], 0.5, 0.25) == "high-variance"
    assert diagnose_curves([0.5], [0.5], 0.25, 0.25) == "high-bias"
    assert diagnose_curves([0.5], [1.0], 0.25, 0.25) == "high-bias-and-variance"


def test_diagnose_curves_validation_below_training_is_not_variance():
    assert diagnose_curves([0.3], [0.1], 0.5, 0.05) == "ok"
    assert diagnose_curves([0.3], [0.1], 0.2, 0.05) == "high-bias"


def test_diagnose_curves_rejects_bad_curves():
    for tr, va in (([], []), ([0.1], []), ([0.1, 0.2], [0.1]), ([], [0.1])):
        with pytest.raises(ValueError):
            diagnose_curves(tr, va, 0.1, 0.1)


# ---- first_step ---------------------------------------------------------------


def test_first_step_nan_and_flat_loss():
    assert first_step({"loss_nan": True}) == "check-data-and-lr"
    assert first_step({"loss_flat": True}) == "overfit-tiny-batch"
    assert first_step({"loss_flat": True, "overfits_tiny_batch": None}) == "overfit-tiny-batch"
    assert first_step({"loss_flat": True, "overfits_tiny_batch": False}) == "fix-pipeline-bug"
    assert first_step({"loss_flat": True, "overfits_tiny_batch": True}) == "tune-optimiser"


def test_first_step_leakage_and_online_gap():
    assert first_step({"leakage_suspected": True}) == "audit-leakage"
    assert first_step({"suspiciously_good": True}) == "audit-leakage"
    assert first_step({"offline_online_gap": True}) == "check-experiment-then-features"


def test_first_step_numbers():
    base = {"target_err": 0.05, "gap_tol": 0.05}
    assert first_step({**base, "train_err": 0.02, "val_err": 0.25}) == "fix-variance"
    assert first_step({**base, "train_err": 0.2, "val_err": 0.22}) == "fix-bias"
    assert first_step({**base, "train_err": 0.2, "val_err": 0.5}) == "fix-bias-first"
    assert first_step({**base, "train_err": 0.03, "val_err": 0.06}) == "error-analysis"


def test_first_step_rule_order():
    nums = {"train_err": 0.2, "val_err": 0.5, "target_err": 0.05, "gap_tol": 0.05}
    assert first_step({"loss_nan": True, "loss_flat": True, "leakage_suspected": True}) == "check-data-and-lr"
    assert first_step({"loss_flat": True, "leakage_suspected": True, "offline_online_gap": True}) == "overfit-tiny-batch"
    assert first_step({"leakage_suspected": True, "offline_online_gap": True, **nums}) == "audit-leakage"
    assert first_step({"suspiciously_good": True, "offline_online_gap": True}) == "audit-leakage"
    assert first_step({"offline_online_gap": True, **nums}) == "check-experiment-then-features"
    assert first_step({"loss_nan": True, **nums}) == "check-data-and-lr"
    assert first_step({"loss_flat": True, "overfits_tiny_batch": True, **nums}) == "tune-optimiser"


def test_first_step_false_flags_are_ignored_and_input_is_unchanged():
    s = {
        "loss_nan": False,
        "loss_flat": False,
        "leakage_suspected": False,
        "suspiciously_good": False,
        "offline_online_gap": False,
        "train_err": 0.02,
        "val_err": 0.25,
        "target_err": 0.05,
        "gap_tol": 0.05,
    }
    before = dict(s)
    assert first_step(s) == "fix-variance"
    assert s == before


def test_first_step_missing_numbers_raise_only_when_needed():
    for key in ("train_err", "val_err", "target_err", "gap_tol"):
        s = {"train_err": 0.02, "val_err": 0.25, "target_err": 0.05, "gap_tol": 0.05}
        del s[key]
        with pytest.raises(ValueError):
            first_step(s)
    with pytest.raises(ValueError):
        first_step({})
    assert first_step({"leakage_suspected": True}) == "audit-leakage"
    assert first_step({"loss_nan": True}) == "check-data-and-lr"


# ---- base rate ----------------------------------------------------------------


def test_ppv_from_rates():
    assert close(ppv_from_rates(0.01, 0.99, 0.05), 1 / 6, 1e-9)
    assert close(ppv_from_rates(0.5, 0.9, 0.1), 0.9)
    assert close(ppv_from_rates(0.1, 0.8, 0.2), 0.08 / (0.08 + 0.18))
    assert close(ppv_from_rates(0.001, 0.9, 0.01), 0.0009 / (0.0009 + 0.00999))
    assert ppv_from_rates(0.2, 1.0, 0.0) == 1.0
    assert ppv_from_rates(1.0, 0.7, 0.4) == 1.0
    assert ppv_from_rates(0.0, 0.9, 0.1) == 0.0


def test_ppv_from_rates_degenerate_and_bad_input():
    assert ppv_from_rates(0.5, 0.0, 0.0) == 0.0
    assert ppv_from_rates(0.0, 1.0, 0.0) == 0.0
    for args in ((-0.1, 0.5, 0.5), (1.1, 0.5, 0.5), (0.5, -0.1, 0.5), (0.5, 1.1, 0.5), (0.5, 0.5, -0.1), (0.5, 0.5, 1.1)):
        with pytest.raises(ValueError):
            ppv_from_rates(*args)


# ---- Wilson interval ----------------------------------------------------------


def test_wilson_interval_known_values():
    lo, hi = wilson_interval(50, 100)
    assert close(lo, 0.4038298, 1e-6) and close(hi, 0.5961702, 1e-6)
    lo, hi = wilson_interval(0, 10)
    assert lo == 0.0 and close(hi, 3.8416 / 13.8416, 1e-6)
    lo, hi = wilson_interval(10, 10)
    assert hi == 1.0 and close(lo, 1 - 3.8416 / 13.8416, 1e-6)
    lo, hi = wilson_interval(182, 200)
    assert close(lo, 0.8622333, 1e-6) and close(hi, 0.9423130, 1e-6)
    lo, hi = wilson_interval(8, 10)
    assert close(lo, 0.4901568, 1e-6) and close(hi, 0.9433191, 1e-6)


def test_wilson_interval_z_and_n_behaviour():
    lo1, hi1 = wilson_interval(30, 100, z=1.0)
    lo2, hi2 = wilson_interval(30, 100, z=2.5)
    assert lo2 < lo1 < 0.3 < hi1 < hi2
    narrow = wilson_interval(1820, 2000)
    wide = wilson_interval(182, 200)
    assert narrow[1] - narrow[0] < wide[1] - wide[0]
    lo, hi = wilson_interval(1, 1)
    assert 0.0 <= lo < hi == 1.0
    lo, hi = wilson_interval(0, 1)
    assert lo == 0.0 and 0.0 < hi < 1.0
    for k in range(0, 21):
        lo, hi = wilson_interval(k, 20)
        assert 0.0 <= lo <= k / 20 <= hi <= 1.0


def test_wilson_interval_rejects_bad_counts():
    for k, n in ((1, 0), (-1, 10), (11, 10), (0, -5)):
        with pytest.raises(ValueError):
            wilson_interval(k, n)
    with pytest.raises(ValueError):
        wilson_interval(11, 10, z=3.0)


# ---- parameters and FLOPs -----------------------------------------------------


def test_mlp_params():
    assert mlp_params([784, 256, 128, 10]) == 235146
    assert mlp_params([3, 2]) == 8
    assert mlp_params([4, 1]) == 5
    assert mlp_params([2, 3, 1]) == 9 + 4
    assert mlp_params([1, 1, 1, 1]) == 6


def test_mlp_forward_flops():
    assert mlp_forward_flops([784, 256, 128, 10], 1) == 469504
    assert mlp_forward_flops([784, 256, 128, 10], 64) == 30048256
    assert mlp_forward_flops([2, 3, 1], 5) == 2 * 5 * (6 + 3)
    assert mlp_forward_flops([3, 2], 1) == 12


def test_mlp_size_validation():
    for sizes in ([5], [], [3, 0], [0, 3], [4, -1, 2]):
        with pytest.raises(ValueError):
            mlp_params(sizes)
        with pytest.raises(ValueError):
            mlp_forward_flops(sizes, 1)
    with pytest.raises(ValueError):
        mlp_forward_flops([3, 2], 0)