Homework · Runs in your browser

The evaluation toolkit: splitters, ranking metrics, cost thresholds, calibration and leak checks

Build the evaluation toolkit with nothing but the standard library: stratified, group and forward-chaining splitters, ROC-AUC and average precision, precision and recall at a threshold, a cost threshold and a cost search, a binned calibration error, two leak detectors, and a function that balances a training fold by duplication. 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.

Hints:

  • Stratified folds: walk the classes in sorted order, rows in increasing order, with one running counter that never resets; item c goes to test fold c % k. Every row is tested exactly once, and each class is spread over the folds.
  • Group folds: sort the groups by size (largest first), and put each into the fold that has the fewest rows so far. Check that no group sits on both sides.
  • Time-series folds: the last test block ends at the last row; blocks are equal in size; train is every row before (test start - gap). With 12 rows, 3 splits, test_size 2 and gap 2 the first fold is train 0 to 3, test 6 and 7.
  • ROC-AUC: the chance a random positive scores above a random negative, with a tie counting one half. Average precision: walk the thresholds from the highest score down, grouping equal scores together, and add (recall step) x (precision) at each. As a check, [0, 0, 1, 1] with scores [0.1, 0.4, 0.35, 0.8] gives 0.8333 for AP and 0.75 for ROC-AUC.
  • Cost threshold: C_FP / (C_FP + C_FN). The cost search tries every distinct score and also infinity (call nobody positive); a row is positive when its score is at least the threshold.
  • Calibration error: bin by int(p * n_bins), with the top edge folded into the last bin; weight each bin’s gap by its share of the rows.
  • Convention: a row is called positive when its score is at least the threshold (>=). Some libraries use a strict > instead; the tests here use >=.
  • Leak detectors and balancing: duplicate rows are matched exactly; balancing copies minority indices in the order given, and must only ever use the indices you pass in.
  • Try it: balance a training fold, then check that none of the test indices appear in it.

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.

def stratified_kfold(labels, k):
    """Split row numbers into k folds that keep the class mix. Returns k (train, test) pairs.

    Walk the classes in sorted label order and, inside a class, the rows in increasing
    order, with ONE running counter that is never reset: item number c goes to test
    fold c % k. Both index lists in every pair are sorted. Raise ValueError if k < 2
    or k is larger than the number of rows.
    """
    n = len(labels)
    if k < 2 or k > n:
        raise ValueError("need 2 <= k <= number of rows")
    fold_of = [0] * n
    counter = 0
    for cls in sorted(set(labels)):
        for i in range(n):
            if labels[i] == cls:
                fold_of[i] = counter % k
                counter += 1
    return [([i for i in range(n) if fold_of[i] != f], [i for i in range(n) if fold_of[i] == f]) for f in range(k)]


def group_kfold(groups, k):
    """Split row numbers into k folds so no group appears on both sides of a split.

    Sort the groups by size, largest first (ties keep the order of first appearance),
    and put each group into the fold that currently has the fewest rows (ties go to the
    lowest fold number). Returns k (train, test) pairs with sorted index lists.
    Raise ValueError if k < 2 or k is larger than the number of distinct groups.
    """
    first_seen = []
    members = {}
    for i, g in enumerate(groups):
        if g not in members:
            members[g] = []
            first_seen.append(g)
        members[g].append(i)
    if k < 2 or k > len(first_seen):
        raise ValueError("need 2 <= k <= number of groups")
    order = sorted(first_seen, key=lambda g: -len(members[g]))
    sizes = [0] * k
    test = [[] for _ in range(k)]
    for g in order:
        f = sizes.index(min(sizes))
        test[f].extend(members[g])
        sizes[f] += len(members[g])
    n = len(groups)
    out = []
    for f in range(k):
        t = sorted(test[f])
        ts = set(t)
        out.append(([i for i in range(n) if i not in ts], t))
    return out


def time_series_split(n, n_splits, test_size=None, gap=0):
    """Forward-chaining split of n time-ordered rows. Returns n_splits (train, test) pairs.

    test_size defaults to n // (n_splits + 1). The test blocks are consecutive, equal
    size, and the last one ends at row n. Each train set is every row from 0 up to but
    not including (test start - gap), so `gap` rows just before the test block are
    skipped. Raise ValueError if n_splits < 2, or if the first train set would be empty.
    """
    if n_splits < 2:
        raise ValueError("n_splits must be at least 2")
    if test_size is None:
        test_size = n // (n_splits + 1)
    out = []
    for i in range(n_splits):
        end = n - (n_splits - 1 - i) * test_size
        start = end - test_size
        if test_size < 1 or start - gap < 1:
            raise ValueError("not enough rows for these settings")
        out.append((list(range(0, start - gap)), list(range(start, end))))
    return out


def roc_auc(y_true, scores):
    """Probability that a random positive scores above a random negative; a tie counts 0.5.

    Raise ValueError unless both classes are present.
    """
    pos = [s for y, s in zip(y_true, scores) if y == 1]
    neg = [s for y, s in zip(y_true, scores) if y == 0]
    if not pos or not neg:
        raise ValueError("both classes are needed")
    order = sorted(range(len(scores)), key=lambda i: scores[i])
    ranks = [0.0] * len(scores)
    i = 0
    while i < len(order):
        j = i
        while j + 1 < len(order) and scores[order[j + 1]] == scores[order[i]]:
            j += 1
        for t in range(i, j + 1):
            ranks[order[t]] = (i + j) / 2 + 1
        i = j + 1
    rank_sum = sum(r for r, y in zip(ranks, y_true) if y == 1)
    return (rank_sum - len(pos) * (len(pos) + 1) / 2) / (len(pos) * len(neg))


def average_precision(y_true, scores):
    """Average precision: sum over thresholds of (recall_n - recall_{n-1}) * precision_n.

    Thresholds are the distinct score values, highest first; rows with equal scores
    enter together. No interpolation. Raise ValueError if there are no positives.
    """
    total_pos = sum(1 for y in y_true if y == 1)
    if total_pos == 0:
        raise ValueError("no positives")
    order = sorted(range(len(scores)), key=lambda i: -scores[i])
    tp = seen = 0
    prev_recall = 0.0
    ap = 0.0
    i = 0
    while i < len(order):
        j = i
        while j + 1 < len(order) and scores[order[j + 1]] == scores[order[i]]:
            j += 1
        for t in range(i, j + 1):
            tp += 1 if y_true[order[t]] == 1 else 0
        seen = j + 1
        recall = tp / total_pos
        ap += (recall - prev_recall) * (tp / seen)
        prev_recall = recall
        i = j + 1
    return ap


def precision_recall_at_threshold(y_true, scores, threshold):
    """(precision, recall) when every row with score >= threshold is called positive.

    A ratio with a zero denominator is 0.0.
    """
    tp = sum(1 for y, s in zip(y_true, scores) if s >= threshold and y == 1)
    fp = sum(1 for y, s in zip(y_true, scores) if s >= threshold and y == 0)
    fn = sum(1 for y, s in zip(y_true, scores) if s < threshold and y == 1)
    precision = tp / (tp + fp) if tp + fp else 0.0
    recall = tp / (tp + fn) if tp + fn else 0.0
    return precision, recall


def cost_threshold(c_fn, c_fp):
    """The probability above which predicting positive has the lower expected cost."""
    return c_fp / (c_fp + c_fn)


def best_threshold_by_cost(y_true, scores, c_fn, c_fp):
    """Search the thresholds that matter and return (threshold, total_cost) of the cheapest.

    Candidates are every distinct score, plus infinity (call nobody positive). A row is
    called positive when score >= threshold. Cost is c_fn * (missed positives) +
    c_fp * (false alarms). On equal cost, prefer the larger threshold.
    """
    best = None
    for t in sorted(set(scores)) + [float("inf")]:
        fn = sum(1 for y, s in zip(y_true, scores) if y == 1 and s < t)
        fp = sum(1 for y, s in zip(y_true, scores) if y == 0 and s >= t)
        cost = c_fn * fn + c_fp * fp
        if best is None or cost <= best[1]:
            best = (t, cost)
    return best


def expected_calibration_error(y_true, probs, n_bins=10):
    """Binned calibration error: sum over bins of (rows in bin / all rows) * |fraction positive - mean probability|.

    Bins have equal width on [0, 1]; a probability p goes to bin min(int(p * n_bins), n_bins - 1).
    Empty bins contribute nothing.
    """
    n = len(y_true)
    bins = [[] for _ in range(n_bins)]
    for y, p in zip(y_true, probs):
        bins[min(int(p * n_bins), n_bins - 1)].append((y, p))
    ece = 0.0
    for b in bins:
        if b:
            frac = sum(y for y, _ in b) / len(b)
            conf = sum(p for _, p in b) / len(b)
            ece += len(b) / n * abs(frac - conf)
    return ece


def duplicate_rows(train_rows, test_rows):
    """Sorted positions of the test rows whose exact values also appear among the train rows."""
    seen = {tuple(r) for r in train_rows}
    return [i for i, r in enumerate(test_rows) if tuple(r) in seen]


def shared_groups(train_groups, test_groups):
    """Sorted list of the group ids that appear on both sides of a split."""
    return sorted(set(train_groups) & set(test_groups))


def balance_by_duplication(indices, labels):
    """Training indices after copying minority rows until every class matches the largest.

    Return the original indices in their original order, followed by the extra copies.
    Extras are taken from each class by cycling through that class's indices in the
    order given, classes in sorted label order. Only the indices passed in are used,
    so call it on a training fold, never on all the data.
    """
    by_class = {}
    for i in indices:
        by_class.setdefault(labels[i], []).append(i)
    if not by_class:
        return []
    target = max(len(v) for v in by_class.values())
    out = list(indices)
    for cls in sorted(by_class):
        rows = by_class[cls]
        for j in range(target - len(rows)):
            out.append(rows[j % len(rows)])
    return out
Show the tests (test_starter.py)

Python

import math

import pytest

from starter import (
    average_precision,
    balance_by_duplication,
    best_threshold_by_cost,
    cost_threshold,
    duplicate_rows,
    expected_calibration_error,
    group_kfold,
    precision_recall_at_threshold,
    roc_auc,
    shared_groups,
    stratified_kfold,
    time_series_split,
)


def counts(idx, labels):
    out = {}
    for i in idx:
        out[labels[i]] = out.get(labels[i], 0) + 1
    return out


# ---- stratified_kfold -------------------------------------------------------

def test_stratified_keeps_class_counts_on_the_docs_example():
    y = [0] * 45 + [1] * 5
    folds = stratified_kfold(y, 3)
    assert [counts(te, y) for _, te in folds] == [{0: 15, 1: 2}, {0: 15, 1: 2}, {0: 15, 1: 1}]
    assert [counts(tr, y) for tr, _ in folds] == [{0: 30, 1: 3}, {0: 30, 1: 3}, {0: 30, 1: 4}]


def test_stratified_exact_assignment_uses_sorted_labels_and_one_running_counter():
    y = [1, 0, 1, 0, 0, 1]
    folds = stratified_kfold(y, 2)
    assert folds[0] == ([0, 3, 5], [1, 2, 4])
    assert folds[1] == ([1, 2, 4], [0, 3, 5])


def test_stratified_every_row_is_tested_exactly_once_and_train_is_the_complement():
    y = ["b", "a", "b", "b", "a", "c", "c", "b", "a", "a", "b"]
    folds = stratified_kfold(y, 4)
    assert len(folds) == 4
    tested = sorted(i for _, te in folds for i in te)
    assert tested == list(range(len(y)))
    for tr, te in folds:
        assert tr == sorted(tr) and te == sorted(te)
        assert sorted(tr + te) == list(range(len(y)))


def test_stratified_with_one_rare_row_puts_it_in_exactly_one_test_fold():
    y = [0] * 8 + [1]
    folds = stratified_kfold(y, 3)
    with_rare = [te for _, te in folds if 8 in te]
    assert len(with_rare) == 1
    assert sum(1 for tr, _ in folds if 8 in tr) == 2
    assert sorted(len(te) for _, te in folds) == [3, 3, 3]


def test_stratified_class_counts_differ_by_at_most_one_between_folds():
    y = [0] * 23 + [1] * 7 + [2] * 5
    folds = stratified_kfold(y, 5)
    for cls in (0, 1, 2):
        per_fold = [counts(te, y).get(cls, 0) for _, te in folds]
        assert max(per_fold) - min(per_fold) <= 1


def test_stratified_rejects_bad_k_and_does_not_change_the_input():
    y = [0, 1, 0, 1]
    with pytest.raises(ValueError):
        stratified_kfold(y, 1)
    with pytest.raises(ValueError):
        stratified_kfold(y, 5)
    assert len(stratified_kfold(y, 4)) == 4
    assert y == [0, 1, 0, 1]


# ---- group_kfold -------------------------------------------------------------

def test_group_kfold_matches_the_docs_example_test_sets():
    folds = group_kfold([1, 1, 1, 2, 2, 2, 3, 3, 3, 3], 3)
    assert sorted(te for _, te in folds) == [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]], "the same three test sets as the docs, in any fold order"


def test_group_kfold_never_splits_a_group():
    groups = ["p1", "p2", "p1", "p3", "p2", "p4", "p4", "p4", "p5", "p1", "p6", "p3"]
    folds = group_kfold(groups, 3)
    for tr, te in folds:
        assert not set(groups[i] for i in tr) & set(groups[i] for i in te)
        assert sorted(tr + te) == list(range(len(groups)))
    assert sorted(i for _, te in folds for i in te) == list(range(len(groups)))


def test_group_kfold_puts_a_big_group_alone_and_fills_the_lightest_fold():
    groups = ["a"] * 5 + ["b", "c", "d", "e", "f"]
    folds = group_kfold(groups, 2)
    assert [te for _, te in folds] == [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]


def test_group_kfold_ties_go_to_the_lowest_fold_and_keep_first_appearance_order():
    folds = group_kfold(["a", "b", "c", "d"], 2)
    assert [te for _, te in folds] == [[0, 2], [1, 3]]


def test_group_kfold_rejects_more_folds_than_groups_or_k_below_two():
    with pytest.raises(ValueError):
        group_kfold([1, 1, 2, 2], 3)
    with pytest.raises(ValueError):
        group_kfold([1, 1, 2, 2], 1)


# ---- time_series_split --------------------------------------------------------

def test_time_series_split_default_test_size():
    assert time_series_split(6, 3) == [([0, 1, 2], [3]), ([0, 1, 2, 3], [4]), ([0, 1, 2, 3, 4], [5])]


def test_time_series_split_fixed_test_size_and_gap_match_the_docs():
    assert time_series_split(12, 3, test_size=2) == [
        ([0, 1, 2, 3, 4, 5], [6, 7]),
        ([0, 1, 2, 3, 4, 5, 6, 7], [8, 9]),
        ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11]),
    ]
    assert time_series_split(12, 3, test_size=2, gap=2) == [
        ([0, 1, 2, 3], [6, 7]),
        ([0, 1, 2, 3, 4, 5], [8, 9]),
        ([0, 1, 2, 3, 4, 5, 6, 7], [10, 11]),
    ]


def test_time_series_split_leftover_rows_go_to_the_first_train_set():
    assert time_series_split(8, 3) == [([0, 1], [2, 3]), ([0, 1, 2, 3], [4, 5]), ([0, 1, 2, 3, 4, 5], [6, 7])]


def test_time_series_split_never_trains_on_the_future():
    for tr, te in time_series_split(50, 4, gap=3):
        assert max(tr) < min(te) - 3 + 1
        assert te == list(range(te[0], te[0] + len(te)))
    assert time_series_split(50, 4)[-1][1][-1] == 49


def test_time_series_split_rejects_impossible_settings():
    with pytest.raises(ValueError):
        time_series_split(10, 1)
    with pytest.raises(ValueError):
        time_series_split(3, 3)
    with pytest.raises(ValueError):
        time_series_split(6, 3, test_size=1, gap=3)


# ---- roc_auc and average_precision ------------------------------------------

def test_roc_auc_basic_cases():
    assert math.isclose(roc_auc([0, 0, 1, 1], [0.1, 0.4, 0.35, 0.8]), 0.75)
    assert roc_auc([0, 0, 1, 1], [0.1, 0.2, 0.8, 0.9]) == 1.0
    assert roc_auc([1, 1, 0, 0], [0.1, 0.2, 0.8, 0.9]) == 0.0


def test_roc_auc_counts_ties_as_half():
    assert math.isclose(roc_auc([1, 0, 0], [0.5, 0.5, 0.9]), 0.25)
    assert math.isclose(roc_auc([0, 1, 0, 1], [0.3, 0.3, 0.3, 0.3]), 0.5)


def test_roc_auc_for_one_rare_positive_and_order_independence():
    y = [0] * 9 + [1] + [0] * 90
    s = [1.0 - i / 100 for i in range(100)]
    assert math.isclose(roc_auc(y, s), 90 / 99)
    pairs = list(zip(y, s))
    pairs.reverse()
    assert math.isclose(roc_auc([p[0] for p in pairs], [p[1] for p in pairs]), 90 / 99)


def test_roc_auc_does_not_change_when_negatives_are_repeated():
    pos = [0.9, 0.6, 0.3]
    neg = [0.8, 0.5, 0.2, 0.1]
    a = roc_auc([1] * 3 + [0] * 4, pos + neg)
    b = roc_auc([1] * 3 + [0] * 40, pos + neg * 10)
    assert math.isclose(a, b) and math.isclose(a, 9 / 12)


def test_roc_auc_needs_both_classes():
    with pytest.raises(ValueError):
        roc_auc([1, 1], [0.1, 0.2])
    with pytest.raises(ValueError):
        roc_auc([0, 0], [0.1, 0.2])


def test_average_precision_docs_example_and_perfect_ranking():
    assert math.isclose(average_precision([0, 0, 1, 1], [0.1, 0.4, 0.35, 0.8]), 0.5 + 0.5 * 2 / 3)
    assert average_precision([0, 1, 0, 1], [0.1, 0.9, 0.2, 0.8]) == 1.0


def test_average_precision_ties_enter_together():
    assert math.isclose(average_precision([0, 1, 0, 0], [0.5, 0.5, 0.5, 0.5]), 0.25)
    assert math.isclose(average_precision([1, 1, 0], [0.5, 0.5, 0.5]), 2 / 3), "two positives tied with a negative: one threshold, recall jumps 0 to 1 at precision 2/3"
    assert math.isclose(average_precision([1, 0, 1, 0], [0.9, 0.5, 0.5, 0.1]), 0.5 * 1.0 + 0.5 * (2 / 3))


def test_average_precision_drops_with_false_alarms_while_roc_auc_stays_high():
    y = [1] + [0] * 98 + [1] + [0] * 900
    s = [1000 - i for i in range(len(y))]
    assert math.isclose(average_precision(y, s), 0.5 * 1.0 + 0.5 * (2 / 100))
    assert math.isclose(roc_auc(y, s), (998 + 900) / (2 * 998))


def test_average_precision_is_not_interpolated():
    assert math.isclose(average_precision([1, 0, 1, 1], [0.9, 0.8, 0.7, 0.6]), (1 + 2 / 3 + 3 / 4) / 3)


def test_average_precision_edge_cases():
    assert average_precision([1, 1, 1], [0.3, 0.2, 0.1]) == 1.0
    with pytest.raises(ValueError):
        average_precision([0, 0], [0.3, 0.2])


# ---- thresholds and cost -----------------------------------------------------

def fraud_data():
    y = [1] * 15 + [0] * 25 + [1] * 5 + [0] * 9955
    s = [0.9] * 40 + [0.1] * 9960
    return y, s


def test_precision_recall_at_threshold_on_the_fraud_example():
    y, s = fraud_data()
    p, r = precision_recall_at_threshold(y, s, 0.5)
    assert math.isclose(p, 0.375) and math.isclose(r, 0.75)


def test_threshold_is_inclusive_and_empty_denominators_are_zero():
    y = [1, 0, 1, 0]
    s = [0.5, 0.5, 0.2, 0.1]
    assert precision_recall_at_threshold(y, s, 0.5) == (0.5, 0.5)
    assert precision_recall_at_threshold(y, s, 0.9) == (0.0, 0.0)
    assert precision_recall_at_threshold([0, 0], [0.9, 0.8], 0.5) == (0.0, 0.0)
    assert precision_recall_at_threshold([1, 1], [0.9, 0.8], 0.5) == (1.0, 1.0)


def test_cost_threshold_formula():
    assert math.isclose(cost_threshold(5000, 50), 50 / 5050)
    assert math.isclose(cost_threshold(1, 1), 0.5)
    assert math.isclose(cost_threshold(1, 9), 0.9), "false alarms nine times as costly: need 90% confidence"


def test_best_threshold_by_cost_cheap_misses_and_dear_misses():
    y = [1, 1, 0, 0, 0]
    s = [0.9, 0.4, 0.8, 0.3, 0.1]
    assert best_threshold_by_cost(y, s, 5, 1) == (0.4, 1)
    assert best_threshold_by_cost(y, s, 1, 5) == (0.9, 1)


def test_best_threshold_can_be_to_call_nobody_positive():
    t, cost = best_threshold_by_cost([0, 0, 1], [0.9, 0.8, 0.1], 1, 10)
    assert t == float("inf") and cost == 1


def test_best_threshold_prefers_the_larger_threshold_on_equal_cost():
    assert best_threshold_by_cost([1, 1, 0], [0.9, 0.5, 0.5], 1, 1) == (0.9, 1)


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

def test_ece_zero_when_calibrated_and_large_when_overconfident():
    assert math.isclose(expected_calibration_error([1] * 8 + [0] * 2, [0.8] * 10), 0.0, abs_tol=1e-12)
    assert math.isclose(expected_calibration_error([1] * 5 + [0] * 5, [0.9] * 10), 0.4)


def test_ece_weights_bins_by_how_many_rows_they_hold():
    y = [0] * 8 + [1] * 2
    p = [0.2] * 8 + [0.9] * 2
    assert math.isclose(expected_calibration_error(y, p), 0.8 * 0.2 + 0.2 * 0.1)


def test_ece_bins_are_left_closed_and_not_rounded():
    assert math.isclose(expected_calibration_error([1, 0, 0], [0.1, 0.15, 0.05]), 4 / 15, abs_tol=1e-9)


def test_ece_respects_n_bins_and_the_top_edge():
    y = [0] * 8 + [1] * 2
    p = [0.2] * 8 + [0.9] * 2
    assert math.isclose(expected_calibration_error(y, p, n_bins=1), abs(0.2 - 0.34))
    assert math.isclose(expected_calibration_error([1, 1], [1.0, 1.0]), 0.0, abs_tol=1e-12)
    assert math.isclose(expected_calibration_error([0, 1], [0.1, 0.9], n_bins=10), 0.1)


# ---- leakage detectors and inside-fold resampling -----------------------------

def test_duplicate_rows_reports_test_positions_with_exact_matches():
    train = [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]
    test = [[3.0, 4.0], [3.0, 4.1], [9.0, 9.0], [1.0, 2.0], [9.0, 9.0]]
    assert duplicate_rows(train, test) == [0, 3]
    assert duplicate_rows([], test) == []
    assert duplicate_rows(train, [[7.0, 7.0], [7.0, 7.0]]) == []


def test_duplicate_rows_accepts_tuples_and_lists_interchangeably():
    assert duplicate_rows([(1, 2)], [[1, 2]]) == [0]


def test_shared_groups_with_larger_integer_ids():
    assert shared_groups([10, 2, 33, 2, 100], [100, 33, 7, 10, 10]) == [10, 33, 100]


def test_shared_groups_is_sorted_and_empty_when_clean():
    assert shared_groups(["b", "a", "c", "a"], ["c", "z", "b", "c"]) == ["b", "c"]
    assert shared_groups([1, 2], [3, 4]) == []
    assert shared_groups([], [1]) == []


def test_balance_by_duplication_cycles_through_the_minority_in_order():
    assert balance_by_duplication([0, 1, 2, 3, 4, 5], [0, 0, 0, 0, 1, 1]) == [0, 1, 2, 3, 4, 5, 4, 5]
    assert balance_by_duplication([0, 1, 2, 3, 4, 5], [0, 0, 0, 1, 2, 2]) == [0, 1, 2, 3, 4, 5, 3, 3, 4]


def test_balance_by_duplication_with_unsorted_label_values():
    labels = [2, 2, 2, 1, 0, 0]
    assert balance_by_duplication([0, 1, 2, 3, 4, 5], labels) == [0, 1, 2, 3, 4, 5, 4, 3, 3]


def test_balance_by_duplication_uses_only_the_indices_it_is_given():
    labels = [0, 0, 0, 1, 1]
    assert balance_by_duplication([0, 1, 2, 4], labels) == [0, 1, 2, 4, 4, 4]


def test_balance_by_duplication_follows_the_order_given_and_leaves_balanced_data_alone():
    labels = [0, 0, 0, 0, 1, 1]
    assert balance_by_duplication([5, 4, 0, 1, 2, 3], labels) == [5, 4, 0, 1, 2, 3, 5, 4]
    assert balance_by_duplication([0, 1, 4, 5], labels) == [0, 1, 4, 5]
    assert balance_by_duplication([], labels) == []
    given = [0, 1, 2, 4]
    balance_by_duplication(given, [0, 0, 0, 0, 1])
    assert given == [0, 1, 2, 4]


def test_balancing_inside_folds_never_touches_test_rows():
    y = [0] * 18 + [1] * 2
    for tr, te in stratified_kfold(y, 2):
        balanced = balance_by_duplication(tr, y)
        assert not set(balanced) & set(te)
        assert counts(balanced, y)[0] == counts(balanced, y)[1]
        assert set(balanced) == set(tr)