Skip to content
BIASED
Back to topic

Optional

Discrepancies and exact permutation tails

These are invented small samples, not learner data. The exhaustive permutation calculation assumes exchangeability of the pooled labels. PSI is a discrepancy, not a p-value; the tiny expected category counts do not justify an asymptotic Pearson p-value.

Version
v2
Minutes
~20
Evidence
Self-check in the notebook

Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.

Download .ipynb

Download the notebook and run it locally. Its environment requirements are listed inside.

Notebook contents

Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.

Discrepancies and exact permutation tails / Расхождения и точный перестановочный хвост

Optional practice; Python standard library only. The core lesson does not require running code. No downloads, network, accounts, models, user data or actual deployments.

Необязательная практика; только стандартная библиотека Python. Для основной темы запуск кода не требуется. Без загрузок, сети, аккаунтов, моделей, пользовательских данных или реальных деплоев.

Authored for the Fedor Pakhurov project with Codex assistance. Case functions and fictional inputs come from the independently reviewed first-party note and fixture at published revision 82b6cb07167b37710c6a786a3a41878a4e928483. New packaging and exact-arithmetic self-checks are added here. No exclusive copyright guarantee is asserted.

Note: https://github.com/fpakhurov/fpakhurov.com/blob/82b6cb07167b37710c6a786a3a41878a4e928483/src/content/notes/mlops/monitoring-and-drift.mdx

Fixture: https://github.com/fpakhurov/fpakhurov.com/blob/82b6cb07167b37710c6a786a3a41878a4e928483/scripts/notes/mlops-renewal-cases.py

The note retains primary conceptual citations; no external source-specific dataset, model output, figure or code is included.

Inputs and limits / Входы и границы

These are invented small samples, not learner data. The exhaustive permutation calculation assumes exchangeability of the pooled labels. PSI is a discrepancy, not a p-value; the tiny expected category counts do not justify an asymptotic Pearson p-value.

Это придуманные маленькие выборки, не данные учеников. Полный перестановочный расчёт предполагает обменность меток объединённой выборки. PSI — расхождение, не p-value; маленькие ожидаемые частоты не обосновывают асимптотический p-value Пирсона.

import hashlib
import itertools
import json
import math
 
def monitoring():
    p, q = [0.6, 0.3, 0.1], [0.2, 0.3, 0.5]
    psi = sum((b - a) * math.log(b / a) for a, b in zip(p, q))
    reference, current = [0, 1, 1, 2, 3], [1, 2, 3, 4, 5]
    def ks(left, right):
        return max(abs(sum(x <= t for x in left) / len(left) -
                       sum(x <= t for x in right) / len(right))
                   for t in set(left + right))
    observed = ks(reference, current)
    pooled = reference + current
    extreme = 0
    for indices in itertools.combinations(range(10), 5):
        selected = set(indices)
        left = [value for i, value in enumerate(pooled) if i in selected]
        right = [value for i, value in enumerate(pooled) if i not in selected]
        extreme += ks(left, right) >= observed - 1e-12
    return {"reference_bin_fractions": p, "current_bin_fractions": q, "psi": psi,
            "chi_square_against_fixed_reference": sum((10*b-10*a)**2/(10*a) for a,b in zip(p,q)),
            "ks_reference": reference, "ks_current": current, "ks_statistic": observed,
            "permutations": math.comb(10, 5), "extreme_permutations": extreme,
            "permutation_p_value": extreme / math.comb(10, 5),
            "linear_mmd_squared": (sum(reference)/5 - sum(current)/5)**2,
            "unchanged_mean_counterexample_mmd": ((-1+1)/2-(-2+2)/2)**2,
            "false_alarm_probability_20_independent_tests": 1 - 0.95**20}
result = monitoring()
print(json.dumps(result, indent=2, allow_nan=False))

Check independently / Независимая проверка

The checks below use conservation, exact arithmetic or boundary cases in addition to the case function. Passing them establishes these declared examples, not production reliability.

Ниже проверяются сохранение, точная арифметика или граничные случаи сверх функции примера. Их прохождение устанавливает эти заданные примеры, а не надёжность продакшена.

from fractions import Fraction as F
pooled = [0,1,1,2,3,1,2,3,4,5]
def integer_distance(indices):
    chosen = set(indices)
    return max(abs(sum(x<=t for i,x in enumerate(pooled) if i in chosen) -
                   sum(x<=t for i,x in enumerate(pooled) if i not in chosen)) for t in set(pooled))
observed = integer_distance(range(5))
tail = sum(integer_distance(indices)>=observed for indices in itertools.combinations(range(10),5))
assert (observed,tail) == (2,204)
assert math.isclose(result["permutation_p_value"],float(F(204,252)))
assert math.isclose(result["psi"],0.4*math.log(15))
assert math.isclose(result["chi_square_against_fixed_reference"],float(F(56,3)))
assert math.isclose(result["linear_mmd_squared"],float(F(64,25)))
print("Self-checks passed: integer ECDF tail 204/252; PSI and discrepancy arithmetic agree.")

Change one assumption / Измените одно предположение

Compare the two symmetric samples [-1,1] and [-2,2]. Explain why linear-kernel MMD is zero although their spreads differ. Then distinguish per-window tests from a repeated alerting policy.

Сравните симметричные выборки [-1,1] и [-2,2]. Объясните нулевой MMD с линейным ядром при разных разбросах. Затем различите тест в одном окне и политику повторных сигналов.