Homework · Runs in your browser

The feature pipeline toolkit: imputer, scaler, encoders, target encoding, PSI, KS and point-in-time join

Build the preprocessing and monitoring pieces of a production feature pipeline with nothing but the standard library: an imputer that learns on the training column and adds a missing indicator, a standard scaler, a one-hot encoder that survives unseen levels, smoothed and out-of-fold target encoding, quantile bins with PSI, the KS statistic, a point-in-time join with a TTL, and a past-only rolling mean. 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. Two small helpers are already written for you, and the constructors of the classes are given.

Hints:

  • Anything learned (a fill value, a mean, a category list, an encoding) is learned in fit and only applied in transform. Calling transform on test data must never change what was learned.
  • Imputer: None and NaN both mean missing. A median of an even count is the average of the two middle values. A fill value of 0 is a real fill value, so test is None, not truthiness. Check: fit [1, 2, None, 6] with the mean strategy gives 3.0.
  • Scaler: divide by the population standard deviation (divisor n). A constant column has no spread, so use a scale of 1.0 and return zeros. Check: fit [1, 2, 3, 4, 5] gives scale sqrt(2).
  • Target encoding: value = (sum + smooth x prior) / (n + smooth). Out-of-fold: row i is in fold i % n_folds and is encoded from the other folds only, including their own prior for a level they have never seen. Test it yourself: flip one target and check that the encoding of that same row does not move.
  • Leave-one-out looks safe and is not: within one level the value falls when the row’s own target rises, so it still encodes the label. Use folds.
  • Quantile edges: cut k sits at position k x (n - 1) / bins in the sorted values, with linear interpolation. Check: the values 1 to 11 with 4 bins give [3.5, 6, 8.5]. A value equal to a cut belongs to the upper bin.
  • PSI: shares are count / total, raised to at least eps, then the sum of (a - e) x ln(a / e). Check: shares (0.5, 0.5) against (0.3, 0.7) give 0.1695.
  • KS: take in every copy of a value, from both samples, before comparing the two CDFs. Check: [1, 1, 1, 2] against [1, 2, 2, 2] gives 0.5, not 0.75.
  • Point-in-time join: the latest feature row with ts <= the event ts, same key. With a TTL, a row older than ts - ttl is too stale. Equal timestamps: the later row in the list wins.
  • Try it: compute the PSI of a feature between two weeks of your own data and decide whether the number is bigger than the noise floor for that sample size.

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
from bisect import bisect_right

EPS = 1e-12


# Provided helper.
def _is_missing(v):
    return v is None or (isinstance(v, float) and math.isnan(v))


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


class Imputer:
    """Fill missing values with a statistic learned on the training column only.

    strategy is 'mean', 'median' or 'most_frequent'. fit(values) ignores None and NaN, stores
    the statistic in self.fill_ and returns self. The median of an even count is the average of
    the two middle values. For 'most_frequent' a tie goes to the smallest value. fit raises
    ValueError when no value is observed, and the constructor raises ValueError for an unknown
    strategy. transform(values) returns (filled, flags): filled has the statistic in place of
    each missing value, and flags has 1 where the value was missing and 0 where it was not.
    transform before fit raises RuntimeError. Neither method changes its input.
    """

    def __init__(self, strategy="mean"):
        if strategy not in ("mean", "median", "most_frequent"):
            raise ValueError("strategy must be 'mean', 'median' or 'most_frequent'")
        self.strategy = strategy
        self.fill_ = None

    def fit(self, values):
        present = [v for v in values if not _is_missing(v)]
        if not present:
            raise ValueError("no observed values to learn from")
        if self.strategy == "mean":
            self.fill_ = _mean(present)
        elif self.strategy == "median":
            s = sorted(present)
            mid = len(s) // 2
            self.fill_ = s[mid] if len(s) % 2 == 1 else (s[mid - 1] + s[mid]) / 2
        else:
            counts = {}
            for v in present:
                counts[v] = counts.get(v, 0) + 1
            best = max(counts.values())
            self.fill_ = min(v for v, c in counts.items() if c == best)
        return self

    def transform(self, values):
        if self.fill_ is None:
            raise RuntimeError("call fit first")
        filled, flags = [], []
        for v in values:
            if _is_missing(v):
                filled.append(self.fill_)
                flags.append(1)
            else:
                filled.append(v)
                flags.append(0)
        return filled, flags


class StandardScaler:
    """Centre and scale with the mean and population standard deviation of the training column.

    fit(values) stores self.mean_ and self.scale_ and returns self. The standard deviation divides
    by n. When it is below 1e-12 (a constant column) scale_ is 1.0, so transform gives zeros
    instead of dividing by nearly nothing. fit raises ValueError on an empty list. transform returns
    (v - mean_) / scale_ for every value and raises RuntimeError before fit.
    """

    def __init__(self):
        self.mean_ = None
        self.scale_ = None

    def fit(self, values):
        if len(values) == 0:
            raise ValueError("cannot fit on an empty column")
        self.mean_ = _mean(values)
        std = math.sqrt(sum((v - self.mean_) ** 2 for v in values) / len(values))
        self.scale_ = std if std >= EPS else 1.0
        return self

    def transform(self, values):
        if self.mean_ is None:
            raise RuntimeError("call fit first")
        return [(v - self.mean_) / self.scale_ for v in values]


class OneHotEncoder:
    """One 0/1 column per category seen in fit.

    fit(values) stores the sorted distinct values in self.categories_ and returns self.
    transform(values) returns one row per value with a single 1 in the column of its category.
    A category not seen in fit gives a row of all zeros (it must not raise). transform before
    fit raises RuntimeError.
    """

    def __init__(self):
        self.categories_ = None

    def fit(self, values):
        self.categories_ = sorted(set(values))
        return self

    def transform(self, values):
        if self.categories_ is None:
            raise RuntimeError("call fit first")
        index = {c: i for i, c in enumerate(self.categories_)}
        rows = []
        for v in values:
            row = [0] * len(self.categories_)
            if v in index:
                row[index[v]] = 1
            rows.append(row)
        return rows


def target_encoding_fit(categories, y, smooth):
    """Smoothed target mean per category. Returns (encoding, prior).

    prior is the mean of all of y. For a category with n rows whose targets sum to s the value is
    (s + smooth * prior) / (n + smooth), so a category with few rows is pulled towards the prior.
    encoding is a dict from category to value. Raise ValueError if the lists differ in length or
    are empty, or if smooth is negative.
    """
    if len(categories) != len(y) or len(y) == 0 or smooth < 0:
        raise ValueError("need equal, non-empty lists and smooth >= 0")
    prior = _mean(y)
    n, s = {}, {}
    for c, t in zip(categories, y):
        n[c] = n.get(c, 0) + 1
        s[c] = s.get(c, 0) + t
    encoding = {c: (s[c] + smooth * prior) / (n[c] + smooth) for c in n}
    return encoding, prior


def target_encoding_apply(categories, encoding, prior):
    """Look each category up in encoding. A category that is not there gets prior."""
    return [encoding.get(c, prior) for c in categories]


def target_encoding_oof(categories, y, n_folds, smooth):
    """Out-of-fold target encoding for the training rows.

    Row i belongs to fold i % n_folds. The value for a row comes from target_encoding_fit and
    target_encoding_apply run on the rows of the OTHER folds only, so its own target never
    enters its own encoding. A category absent from the other folds gets the prior of the other
    folds. Return the encoded values in the original row order. Raise ValueError if the lists
    differ in length, if n_folds < 2 or n_folds > len(y), or if smooth is negative.
    """
    n = len(y)
    if len(categories) != n or n_folds < 2 or n_folds > n or smooth < 0:
        raise ValueError("need equal lists, 2 <= n_folds <= len(y) and smooth >= 0")
    out = [0.0] * n
    for f in range(n_folds):
        train = [i for i in range(n) if i % n_folds != f]
        enc, prior = target_encoding_fit([categories[i] for i in train], [y[i] for i in train], smooth)
        for i in range(f, n, n_folds):
            out[i] = enc.get(categories[i], prior)
    return out


def quantile_edges(values, bins):
    """The bins - 1 interior cut points that split values into bins of about equal size.

    Sort the values. Cut k (k = 1 .. bins - 1) sits at position k * (n - 1) / bins in the sorted
    list, with linear interpolation between the two neighbouring values. Raise ValueError for an
    empty list or bins < 2.
    """
    if len(values) == 0 or bins < 2:
        raise ValueError("need values and bins >= 2")
    s = sorted(values)
    n = len(s)
    edges = []
    for k in range(1, bins):
        lo, rem = divmod(k * (n - 1), bins)
        hi = min(lo + 1, n - 1)
        edges.append(s[lo] + rem / bins * (s[hi] - s[lo]))
    return edges


def bin_counts(values, edges):
    """Count values per bin. Bin i holds the values v with edges[i-1] <= v < edges[i], so a value
    equal to a cut goes to the upper bin. There are len(edges) + 1 bins. Repeated cuts leave empty
    bins between them. Raise ValueError if edges are not in non-decreasing order."""
    if any(edges[i] > edges[i + 1] for i in range(len(edges) - 1)):
        raise ValueError("edges must be sorted")
    counts = [0] * (len(edges) + 1)
    for v in values:
        counts[bisect_right(edges, v)] += 1
    return counts


def psi(expected_counts, actual_counts, eps=1e-4):
    """Population Stability Index from two lists of bin counts.

    Turn each list into shares (count / total) and raise any share below eps to eps, so an empty
    bin does not give log(0). Return the sum over bins of (a - e) * ln(a / e), where e is the
    expected (reference) share and a the actual share. Raise ValueError if the lists differ in
    length or are empty, if a count is negative, or if either total is zero.
    """
    if len(expected_counts) != len(actual_counts) or len(expected_counts) == 0:
        raise ValueError("need two lists of the same non-zero length")
    if min(expected_counts) < 0 or min(actual_counts) < 0:
        raise ValueError("counts cannot be negative")
    te, ta = sum(expected_counts), sum(actual_counts)
    if te == 0 or ta == 0:
        raise ValueError("a total of zero has no shares")
    total = 0.0
    for ce, ca in zip(expected_counts, actual_counts):
        e = max(ce / te, eps)
        a = max(ca / ta, eps)
        total += (a - e) * math.log(a / e)
    return total


def ks_statistic(a, b):
    """Two-sample Kolmogorov-Smirnov statistic: the largest gap between the two empirical CDFs.

    Compare the CDFs after taking in every copy of a value, so tied values (also tied across the
    two samples) never create a gap that is not there. Raise ValueError if either list is empty.
    """
    if len(a) == 0 or len(b) == 0:
        raise ValueError("both samples need values")
    xs, ys = sorted(a), sorted(b)
    n, m = len(xs), len(ys)
    i = j = 0
    best = 0.0
    while i < n or j < m:
        if j >= m or (i < n and xs[i] <= ys[j]):
            v = xs[i]
        else:
            v = ys[j]
        while i < n and xs[i] <= v:
            i += 1
        while j < m and ys[j] <= v:
            j += 1
        best = max(best, abs(i / n - j / m))
    return best


def point_in_time_join(events, features, ttl=None):
    """For each (key, ts) event return the value of the latest feature row available then.

    features is a list of (key, ts, value) rows in any order. An event may only use a row with the
    same key and ts <= event ts (equal counts as available). Of those take the one with the
    largest ts; if two rows share that ts, the one that comes later in the list wins. When ttl
    is not None, a row older than the event by more than ttl (ts < event ts - ttl) is too stale
    and is ignored. Return None for an event with no usable row. Results follow the order of the
    events. Raise ValueError if ttl is negative.
    """
    if ttl is not None and ttl < 0:
        raise ValueError("ttl cannot be negative")
    by_key = {}
    for key, ts, value in features:
        by_key.setdefault(key, []).append((ts, value))
    stamps = {}
    for key, rows in by_key.items():
        rows.sort(key=lambda r: r[0])
        stamps[key] = [r[0] for r in rows]
    out = []
    for key, ts in events:
        if key not in by_key:
            out.append(None)
            continue
        idx = bisect_right(stamps[key], ts) - 1
        if idx < 0:
            out.append(None)
            continue
        f_ts, value = by_key[key][idx]
        if ttl is not None and f_ts < ts - ttl:
            out.append(None)
        else:
            out.append(value)
    return out


def past_rolling_mean(values, window):
    """Mean of the previous `window` values at every position, never including the current one.

    Position i uses values[max(0, i - window):i]. Position 0 has no past, so it is None. Raise
    ValueError if window < 1.
    """
    if window < 1:
        raise ValueError("window must be at least 1")
    out = []
    for i in range(len(values)):
        past = values[max(0, i - window):i]
        out.append(_mean(past) if past else None)
    return out
Show the tests (test_starter.py)

Python

import math

import pytest

from starter import (
    Imputer,
    OneHotEncoder,
    StandardScaler,
    bin_counts,
    ks_statistic,
    past_rolling_mean,
    point_in_time_join,
    psi,
    quantile_edges,
    target_encoding_apply,
    target_encoding_fit,
    target_encoding_oof,
)

NAN = float("nan")


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


def all_close(xs, ys, tol=1e-9):
    return len(xs) == len(ys) and all(close(x, y, tol) for x, y in zip(xs, ys))


# ---- Imputer -----------------------------------------------------------------


def test_mean_imputer_learns_from_the_observed_values_only():
    imp = Imputer("mean").fit([1, 2, None, 6])
    assert close(imp.fill_, 3.0)
    assert close(Imputer("mean").fit([0, 4, None]).fill_, 2.0)
    assert close(Imputer("mean").fit([0, 0, 6]).fill_, 2.0)
    filled, flags = imp.transform([None, 5, None])
    assert filled == [3.0, 5, 3.0]
    assert flags == [1, 0, 1]


def test_nan_counts_as_missing_like_none():
    imp = Imputer("mean").fit([2.0, NAN, 4.0, None])
    assert close(imp.fill_, 3.0)
    filled, flags = imp.transform([NAN, 7.0, None])
    assert filled == [3.0, 7.0, 3.0]
    assert flags == [1, 0, 1]


def test_median_odd_even_and_outlier():
    assert Imputer("median").fit([5, 1, None, 3]).fill_ == 3
    assert close(Imputer("median").fit([1, 2, 3, 10]).fill_, 2.5)
    skewed = [1, 2, 3, 100]
    assert close(Imputer("median").fit(skewed).fill_, 2.5)
    assert close(Imputer("mean").fit(skewed).fill_, 26.5)
    assert Imputer("median").fit([9]).fill_ == 9
    assert close(Imputer("median").fit([4, None, 8]).fill_, 6.0)


def test_most_frequent_and_ties_go_to_the_smallest_value():
    assert Imputer("most_frequent").fit([5, 5, 2, 2, 2]).fill_ == 2
    assert Imputer("most_frequent").fit([3, 1, 3, 1, 2]).fill_ == 1
    assert Imputer("most_frequent").fit([9, 9, 4, 4]).fill_ == 4
    assert Imputer("most_frequent").fit([7, None, 7, 1, None, None]).fill_ == 7


def test_fit_on_train_then_transform_test_uses_the_training_statistic():
    imp = Imputer("mean").fit([1, 2, 3])
    filled, flags = imp.transform([100, None, 300])
    assert filled == [100, 2.0, 300]
    assert flags == [0, 1, 0]


def test_a_fill_value_of_zero_is_still_a_fitted_imputer():
    imp = Imputer("median").fit([0, 0, None])
    filled, flags = imp.transform([None, 4])
    assert filled == [0, 4]
    assert flags == [1, 0]


def test_imputer_flags_are_zero_when_nothing_is_missing_and_inputs_are_untouched():
    imp = Imputer("mean")
    train = [1.0, None, 3.0]
    imp.fit(train)
    assert train == [1.0, None, 3.0]
    test = [4.0, None]
    imp.transform(test)
    assert test == [4.0, None]
    filled, flags = imp.transform([1.5, 2.5])
    assert filled == [1.5, 2.5]
    assert flags == [0, 0]
    assert imp.transform([]) == ([], [])


def test_imputer_refit_replaces_the_statistic_and_fit_returns_self():
    imp = Imputer("mean")
    assert imp.fit([1, 3]) is imp
    imp.fit([10, 30])
    assert close(imp.fill_, 20.0)


def test_imputer_validation():
    with pytest.raises(ValueError):
        Imputer("mode")
    with pytest.raises(ValueError):
        Imputer("mean").fit([None, NAN])
    with pytest.raises(ValueError):
        Imputer("mean").fit([])
    with pytest.raises(RuntimeError):
        Imputer("mean").transform([1, None])


# ---- StandardScaler ----------------------------------------------------------


def test_scaler_uses_the_population_standard_deviation():
    sc = StandardScaler().fit([1, 2, 3, 4, 5])
    assert close(sc.mean_, 3.0)
    assert close(sc.scale_, math.sqrt(2.0))
    z = sc.transform([3, 3 + math.sqrt(2.0), 1])
    assert all_close(z, [0.0, 1.0, -2 / math.sqrt(2.0)])


def test_scaler_applies_training_statistics_to_new_data():
    sc = StandardScaler().fit([0, 10])
    assert close(sc.mean_, 5.0)
    assert close(sc.scale_, 5.0)
    assert all_close(sc.transform([20, -5, 5]), [3.0, -2.0, 0.0])
    assert all_close(StandardScaler().fit([0, 4]).transform([4]), [1.0])


def test_scaler_constant_column_gives_zeros_not_a_blow_up():
    assert StandardScaler().fit([7, 7, 7]).transform([7, 8]) == [0.0, 1.0]
    z = StandardScaler().fit([0.1, 0.1, 0.1]).transform([0.1, 0.1])
    assert all_close(z, [0.0, 0.0], 1e-6)
    assert close(StandardScaler().fit([5]).scale_, 1.0)


def test_scaler_keeps_a_small_but_real_spread():
    sc = StandardScaler().fit([0, 1e-6])
    assert close(sc.scale_, 5e-7, 1e-12)
    assert all_close(sc.transform([1e-6]), [1.0], 1e-6)


def test_scaler_fit_returns_self_and_validation():
    sc = StandardScaler()
    assert sc.fit([1, 2]) is sc
    with pytest.raises(ValueError):
        StandardScaler().fit([])
    with pytest.raises(RuntimeError):
        StandardScaler().transform([1])


def test_one_outlier_squeezes_the_scaled_values_of_everyone_else():
    clean = [float(i) for i in range(1, 11)]
    with_outlier = clean[:-1] + [1000.0]
    z_clean = StandardScaler().fit(clean).transform(clean)
    z_out = StandardScaler().fit(with_outlier).transform(with_outlier)
    assert max(abs(z) for z in z_out[:-1]) < 0.4 * max(abs(z) for z in z_clean)


# ---- OneHotEncoder -----------------------------------------------------------


def test_one_hot_columns_follow_the_sorted_categories():
    enc = OneHotEncoder().fit(["b", "a", "b", "c"])
    assert enc.categories_ == ["a", "b", "c"]
    assert enc.transform(["c", "a", "b"]) == [[0, 0, 1], [1, 0, 0], [0, 1, 0]]


def test_one_hot_unseen_category_is_all_zeros_and_adds_no_column():
    enc = OneHotEncoder().fit(["x", "y"])
    rows = enc.transform(["y", "z", "x"])
    assert rows == [[0, 1], [0, 0], [1, 0]]
    assert enc.categories_ == ["x", "y"]


def test_one_hot_numbers_empty_input_and_errors():
    enc = OneHotEncoder().fit([3, 1, 2, 3])
    assert enc.categories_ == [1, 2, 3]
    assert enc.transform([2]) == [[0, 1, 0]]
    assert enc.transform([]) == []
    assert OneHotEncoder().fit(["only"]).transform(["only", "other"]) == [[1], [0]]
    assert OneHotEncoder().fit(["a"]) is not None
    with pytest.raises(RuntimeError):
        OneHotEncoder().transform(["a"])


def test_one_hot_each_known_row_sums_to_one():
    enc = OneHotEncoder().fit(list("abcde"))
    for row in enc.transform(list("edcba")):
        assert sum(row) == 1
        assert len(row) == 5


# ---- target encoding ---------------------------------------------------------


def test_target_encoding_fit_known_values():
    cats = ["a", "a", "b", "b", "b", "c"]
    y = [1, 0, 1, 1, 0, 1]
    enc, prior = target_encoding_fit(cats, y, 0)
    assert close(prior, 4 / 6)
    assert close(enc["a"], 0.5) and close(enc["b"], 2 / 3) and close(enc["c"], 1.0)
    enc, prior = target_encoding_fit(cats, y, 2)
    assert close(enc["a"], (1 + 2 * 4 / 6) / 4)
    assert close(enc["b"], (2 + 2 * 4 / 6) / 5)
    assert close(enc["c"], (1 + 2 * 4 / 6) / 3)
    assert set(enc) == {"a", "b", "c"}


def test_target_encoding_pulls_small_categories_towards_the_prior():
    cats = ["x"] + ["y"] * 7
    y = [1, 0, 0, 0, 0, 0, 0, 0]
    enc, prior = target_encoding_fit(cats, y, 3)
    assert close(prior, 0.125)
    assert close(enc["x"], (1 + 3 * 0.125) / 4)
    assert close(enc["y"], (0 + 3 * 0.125) / 10)
    plain, _ = target_encoding_fit(cats, y, 0)
    assert close(plain["x"], 1.0) and close(plain["y"], 0.0)
    big, _ = target_encoding_fit(cats, y, 1e9)
    assert close(big["x"], 0.125, 1e-6) and close(big["y"], 0.125, 1e-6)


def test_target_encoding_values_are_a_blend_between_category_mean_and_prior():
    cats = ["a"] * 4 + ["b"] * 6
    y = [1, 1, 1, 0, 0, 0, 0, 1, 0, 0]
    enc, prior = target_encoding_fit(cats, y, 5)
    assert prior == 0.4
    for c, mean_c in (("a", 0.75), ("b", 1 / 6)):
        lo, hi = sorted([mean_c, prior])
        assert lo < enc[c] < hi
    assert close(enc["a"], (3 + 5 * 0.4) / 9)
    assert close(enc["b"], (1 + 5 * 0.4) / 11)


def test_target_encoding_apply_uses_the_prior_for_unseen_categories():
    enc = {"a": 0.2, "b": 0.9}
    assert target_encoding_apply(["b", "z", "a", "b"], enc, 0.4) == [0.9, 0.4, 0.2, 0.9]
    assert target_encoding_apply([], enc, 0.4) == []


def test_target_encoding_validation():
    with pytest.raises(ValueError):
        target_encoding_fit(["a"], [1, 0], 1)
    with pytest.raises(ValueError):
        target_encoding_fit([], [], 1)
    with pytest.raises(ValueError):
        target_encoding_fit(["a"], [1], -1)
    with pytest.raises(ValueError):
        target_encoding_oof(["a", "b"], [1], 2, 1)
    with pytest.raises(ValueError):
        target_encoding_oof(["a", "b", "c"], [1, 0, 1], 1, 1)
    with pytest.raises(ValueError):
        target_encoding_oof(["a", "b", "c"], [1, 0, 1], 4, 1)
    with pytest.raises(ValueError):
        target_encoding_oof(["a", "b", "c"], [1, 0, 1], 2, -0.5)


def test_oof_known_values():
    cats = ["a", "a", "a", "a", "b", "b"]
    y = [1, 0, 1, 0, 1, 1]
    out = target_encoding_oof(cats, y, 2, 0)
    assert all_close(out, [0, 1, 0, 1, 1, 1])


def test_oof_unseen_category_gets_the_prior_of_the_other_folds_not_the_global_prior():
    cats = ["a", "a", "b", "a", "a", "a"]
    y = [1, 0, 0, 0, 1, 1]
    out = target_encoding_oof(cats, y, 2, 0)
    # Row 2 is the only "b". The other folds are rows 1, 3, 5 with targets 0, 0, 1.
    assert close(out[2], 1 / 3)
    assert not close(out[2], 0.5)


def reference_oof(cats, y, k, smooth):
    out = []
    for i in range(len(y)):
        rest = [j for j in range(len(y)) if j % k != i % k]
        prior = sum(y[j] for j in rest) / len(rest)
        same = [y[j] for j in rest if cats[j] == cats[i]]
        out.append((sum(same) + smooth * prior) / (len(same) + smooth) if same else prior)
    return out


def test_oof_matches_a_plain_reference_with_smoothing():
    cats = list("aabbbcacbbadda")
    y = [1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1]
    for k in (2, 3, 5):
        for smooth in (0, 1, 2.5):
            got = target_encoding_oof(cats, y, k, smooth)
            assert all_close(got, reference_oof(cats, y, k, smooth)), (k, smooth)


def test_oof_never_uses_a_rows_own_target():
    cats = list("aabbbcacbbadda")
    y = [1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1]
    base = target_encoding_oof(cats, y, 3, 1)
    for i in range(len(y)):
        changed = list(y)
        changed[i] = 1 - changed[i]
        again = target_encoding_oof(cats, changed, 3, 1)
        assert close(again[i], base[i]), i


def test_in_sample_encoding_of_unique_ids_memorises_the_target_but_oof_does_not():
    cats = ["id%d" % i for i in range(8)]
    y = [1, 0, 0, 1, 1, 0, 1, 0]
    enc, prior = target_encoding_fit(cats, y, 0)
    assert target_encoding_apply(cats, enc, prior) == [float(t) for t in y]
    oof = target_encoding_oof(cats, y, 4, 0)
    for i in range(8):
        rest = [y[j] for j in range(8) if j % 4 != i % 4]
        assert close(oof[i], sum(rest) / len(rest))


def test_oof_keeps_the_row_order_and_length():
    cats = ["p", "q", "p", "q", "p"]
    y = [1, 0, 1, 0, 1]
    out = target_encoding_oof(cats, y, 5, 0)
    assert len(out) == 5
    assert all_close(out, reference_oof(cats, y, 5, 0))


# ---- quantile edges and bin counts ------------------------------------------


def test_quantile_edges_interpolate_linearly():
    assert all_close(quantile_edges(list(range(1, 12)), 2), [6])
    assert all_close(quantile_edges(list(range(1, 12)), 4), [3.5, 6, 8.5])
    assert all_close(quantile_edges([0, 10], 5), [2, 4, 6, 8])
    assert all_close(quantile_edges([9, 1, 5, 3, 7], 4), [3.0, 5.0, 7.0])


def test_quantile_edges_with_ties_and_a_single_value():
    assert quantile_edges([1, 1, 1, 1, 100], 2) == [1]
    assert all_close(quantile_edges([5], 3), [5, 5])
    assert all_close(quantile_edges([1, 1, 1, 1, 100], 5), [1, 1, 1, 20.8])


def test_quantile_edges_do_not_change_the_input_and_validate():
    vals = [3, 1, 2]
    quantile_edges(vals, 2)
    assert vals == [3, 1, 2]
    with pytest.raises(ValueError):
        quantile_edges([], 4)
    with pytest.raises(ValueError):
        quantile_edges([1, 2, 3], 1)


def test_bin_counts_put_a_value_on_a_cut_in_the_upper_bin():
    assert bin_counts([0, 1, 1.5, 2, 3], [1, 2]) == [1, 2, 2]
    assert bin_counts([], [1, 2]) == [0, 0, 0]
    assert bin_counts([5, 6], []) == [2]


def test_bin_counts_repeated_cuts_leave_empty_bins():
    assert bin_counts([0, 1, 1, 2], [1, 1, 2]) == [1, 0, 2, 1]


def test_bin_counts_every_value_is_counted_once():
    vals = [0.1 * i for i in range(-20, 40)]
    edges = quantile_edges(vals, 6)
    counts = bin_counts(vals, edges)
    assert len(counts) == 6
    assert sum(counts) == len(vals)
    assert max(counts) - min(counts) <= 1


def test_bin_counts_validation():
    with pytest.raises(ValueError):
        bin_counts([1], [2, 1])


# ---- PSI ---------------------------------------------------------------------


def test_psi_hand_example():
    expected = (0.3 - 0.5) * math.log(0.3 / 0.5) + (0.7 - 0.5) * math.log(0.7 / 0.5)
    assert close(psi([50, 50], [30, 70]), expected)
    assert close(expected, 0.169459, 1e-5)


def test_psi_is_zero_for_equal_shares_and_ignores_the_totals():
    assert close(psi([10, 20, 30], [10, 20, 30]), 0.0)
    assert close(psi([10, 20, 30], [1000, 2000, 3000]), 0.0)
    assert close(psi([5, 5], [3, 7]), psi([5000, 5000], [30, 70]))


def test_psi_is_symmetric_when_no_share_is_clipped():
    a, b = [40, 35, 25], [20, 30, 50]
    assert close(psi(a, b), psi(b, a))
    assert psi(a, b) > 0


def test_psi_is_positive_and_grows_with_the_shift():
    base = [25, 25, 25, 25]
    small = psi(base, [27, 25, 25, 23])
    big = psi(base, [40, 25, 25, 10])
    assert 0 < small < big


def test_psi_empty_bin_is_clipped_to_eps():
    expected = 2 * (0.4 - 0.5) * math.log(0.4 / 0.5) + (0.2 - 1e-4) * math.log(0.2 / 1e-4)
    assert close(psi([50, 50, 0], [40, 40, 20]), expected)
    other = 2 * (0.4 - 0.5) * math.log(0.4 / 0.5) + (0.2 - 1e-6) * math.log(0.2 / 1e-6)
    assert close(psi([50, 50, 0], [40, 40, 20], eps=1e-6), other)
    assert other > expected


def test_psi_floor_applies_to_every_share_below_eps_not_only_to_zero():
    # The first expected share is 1e-5, below the default floor of 1e-4, but it is not zero.
    expected = (0.5 - 1e-4) * math.log(0.5 / 1e-4) + (0.5 - 0.99999) * math.log(0.5 / 0.99999)
    assert close(psi([1, 99999], [50000, 50000]), expected)


def test_psi_actual_bin_that_empties_is_clipped_too():
    expected = (1.0 - 0.5) * math.log(1.0 / 0.5) + (1e-4 - 0.5) * math.log(1e-4 / 0.5)
    assert close(psi([50, 50], [100, 0]), expected)


def test_psi_a_bin_empty_on_both_sides_contributes_nothing():
    assert close(psi([10, 0, 10], [10, 0, 10]), 0.0)
    assert close(psi([10, 0, 10], [5, 0, 15]), psi([10, 10], [5, 15]))


def test_psi_validation():
    with pytest.raises(ValueError):
        psi([1, 2], [1, 2, 3])
    with pytest.raises(ValueError):
        psi([], [])
    with pytest.raises(ValueError):
        psi([3, -1], [1, 1])
    with pytest.raises(ValueError):
        psi([1, 1], [3, -1])
    with pytest.raises(ValueError):
        psi([0, 0], [1, 1])
    with pytest.raises(ValueError):
        psi([1, 1], [0, 0])


def test_psi_on_quantile_bins_is_small_for_same_data_and_large_for_a_shift():
    ref = [i / 100 for i in range(1000)]
    edges = quantile_edges(ref, 10)
    same = psi(bin_counts(ref, edges), bin_counts(ref, edges))
    shifted = psi(bin_counts(ref, edges), bin_counts([v + 3 for v in ref], edges))
    assert close(same, 0.0, 1e-3)
    assert shifted > 1.0


# ---- KS statistic ------------------------------------------------------------


def test_ks_known_values():
    assert close(ks_statistic([1, 2, 3], [4, 5, 6]), 1.0)
    assert close(ks_statistic([1, 2, 3], [1, 2, 3]), 0.0)
    assert close(ks_statistic([1, 2, 3, 4], [2.5, 3.5]), 0.5)
    assert close(ks_statistic([1], [0, 2, 3, 4]), 0.75)
    assert close(ks_statistic(list(range(100)), list(range(50, 150))), 0.5)


def test_ks_ties_are_taken_in_together():
    assert close(ks_statistic([1, 1, 1, 2], [1, 2, 2, 2]), 0.5)
    assert close(ks_statistic([1, 2], [1, 2]), 0.0)
    assert close(ks_statistic([5, 5, 5], [5, 5]), 0.0)
    assert close(ks_statistic([1, 1, 2, 2], [1, 2, 2, 2]), 0.25)


def test_ks_is_symmetric_and_ignores_the_input_order():
    a = [0.3, 0.9, 0.1, 0.5, 0.7]
    b = [0.2, 0.8, 0.4, 0.95, 0.6, 0.65, 0.05]
    assert close(ks_statistic(a, b), ks_statistic(b, a))
    assert close(ks_statistic(a, b), ks_statistic(sorted(a), sorted(b, reverse=True)))
    assert a == [0.3, 0.9, 0.1, 0.5, 0.7]


def test_ks_shift_in_the_tail_only_and_a_scale_change():
    a = [float(i) for i in range(10)]
    b = [float(i) for i in range(9)] + [100.0]
    assert close(ks_statistic(a, b), 0.1)
    narrow = [4.5 + 0.01 * i for i in range(10)]
    wide = [float(i) for i in range(10)]
    assert close(ks_statistic(narrow, wide), 0.5)


def test_ks_validation():
    with pytest.raises(ValueError):
        ks_statistic([], [1])
    with pytest.raises(ValueError):
        ks_statistic([1], [])


# ---- point-in-time join ------------------------------------------------------

FEATURES = [("u1", 1, "A"), ("u1", 5, "B"), ("u1", 9, "C"), ("u2", 2, "X")]


def test_join_takes_the_latest_row_not_after_the_event():
    events = [("u1", 5), ("u1", 8), ("u1", 0), ("u1", 100), ("u2", 1), ("u3", 5), ("u2", 2)]
    assert point_in_time_join(events, FEATURES) == ["B", "B", None, "C", None, None, "X"]


def test_join_never_returns_a_value_from_the_future():
    assert point_in_time_join([("u1", 4)], FEATURES) == ["A"]
    assert point_in_time_join([("u1", 8.99)], FEATURES) == ["B"]
    assert point_in_time_join([("u1", 9)], FEATURES) == ["C"]
    assert point_in_time_join([("u1", 0.5)], FEATURES) == [None]


def test_join_does_not_depend_on_the_order_of_the_feature_rows():
    shuffled = [FEATURES[2], FEATURES[3], FEATURES[0], FEATURES[1]]
    events = [("u1", 6), ("u2", 7), ("u1", 10)]
    assert point_in_time_join(events, shuffled) == point_in_time_join(events, FEATURES) == ["B", "X", "C"]


def test_join_equal_timestamps_the_later_row_in_the_list_wins():
    rows = [("k", 5, "first"), ("k", 3, "old"), ("k", 5, "second")]
    assert point_in_time_join([("k", 5), ("k", 6), ("k", 4)], rows) == ["second", "second", "old"]


def test_join_ttl_drops_stale_values():
    assert point_in_time_join([("u1", 8)], FEATURES, ttl=3) == ["B"]
    assert point_in_time_join([("u1", 4)], FEATURES, ttl=2) == [None]
    assert point_in_time_join([("u1", 4)], FEATURES, ttl=3) == ["A"]
    assert point_in_time_join([("u1", 100)], FEATURES, ttl=3) == [None]
    assert point_in_time_join([("u1", 5), ("u1", 6)], FEATURES, ttl=0) == ["B", None]
    assert point_in_time_join([("u1", 100)], FEATURES, ttl=None) == ["C"]
    assert point_in_time_join([("u1", 100)], FEATURES, ttl=10 ** 6) == ["C"]


def test_join_ttl_uses_the_chosen_row_not_an_older_fresh_one():
    rows = [("k", 1, "old"), ("k", 10, "new")]
    assert point_in_time_join([("k", 12)], rows, ttl=5) == ["new"]
    assert point_in_time_join([("k", 12)], rows, ttl=1) == [None]


def test_join_edges_and_inputs_are_untouched():
    rows = list(FEATURES)
    events = [("u1", 6)]
    assert point_in_time_join([], rows) == []
    assert point_in_time_join(events, []) == [None]
    point_in_time_join(events, rows)
    assert rows == FEATURES
    assert events == [("u1", 6)]
    with pytest.raises(ValueError):
        point_in_time_join(events, rows, ttl=-1)


def test_join_keeps_keys_apart():
    rows = [("a", 1, 10), ("b", 2, 20), ("a", 3, 30), ("b", 4, 40)]
    events = [("b", 3), ("a", 3), ("b", 1), ("a", 2)]
    assert point_in_time_join(events, rows) == [20, 30, None, 10]


# ---- past rolling mean -------------------------------------------------------


def test_past_rolling_mean_excludes_the_current_value():
    out = past_rolling_mean([1, 2, 3, 4, 5], 2)
    assert out[0] is None
    assert all_close(out[1:], [1, 1.5, 2.5, 3.5])


def test_past_rolling_mean_window_edges():
    assert past_rolling_mean([1, 2, 3, 4, 5], 1)[1:] == [1, 2, 3, 4]
    out = past_rolling_mean([1, 2, 3, 4, 5], 10)
    assert out[0] is None
    assert all_close(out[1:], [1, 1.5, 2, 2.5])
    assert past_rolling_mean([], 3) == []
    assert past_rolling_mean([7], 3) == [None]


def test_past_rolling_mean_does_not_move_when_the_current_value_changes():
    base = past_rolling_mean([1, 2, 3, 4, 5, 6], 3)
    for i in range(6):
        vals = [1, 2, 3, 4, 5, 6]
        vals[i] = 1000
        changed = past_rolling_mean(vals, 3)
        assert changed[i] == base[i]


def test_past_rolling_mean_uses_exactly_the_last_window_values():
    assert close(past_rolling_mean([10, 0, 0, 6, 0], 3)[4], 2.0)
    assert close(past_rolling_mean([10, 0, 0, 6, 0], 3)[3], 10 / 3)
    vals = [1, 2, 3]
    past_rolling_mean(vals, 2)
    assert vals == [1, 2, 3]


def test_past_rolling_mean_validation():
    with pytest.raises(ValueError):
        past_rolling_mean([1, 2], 0)