Skip to content
BIASED
Back to topic

Optional

Exposure, stopping and the comparison population

Counts and rankings are fictional; no service or experiment is contacted. Normal approximations have stated fixed-sample assumptions. The exact fair-outcome enumeration illustrates a particular stopping design, not a general deployment guarantee.

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.

Exposure, stopping and the comparison population / Воздействие, остановки и совокупность сравнения

Optional practice. Python standard library only. The phone lesson does not require running code. No external dataset, account, model, paid API or production action.

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

Authored for the Fedor Pakhurov project with Codex assistance. Selected functions and fictional inputs come from the completely reviewed, published first-party revision 840854d82dc3f9e208c0ed88a92180ccde4e3803. Notebook packaging and additional self-checks are newly authored. No guarantee of exclusive copyright is asserted.

Reviewed note: https://github.com/fpakhurov/fpakhurov.com/blob/840854d82dc3f9e208c0ed88a92180ccde4e3803/src/content/notes/mlops/rolling-out-models.mdx

First-party fixture: https://github.com/fpakhurov/fpakhurov.com/blob/840854d82dc3f9e208c0ed88a92180ccde4e3803/scripts/notes/mlops-rollout-cases.py

The note retains primary scientific references. No external source-specific code, figure, dataset or model result is reproduced in this notebook. Saved output environment: Python 3.9.7. Other interpreter versions can change final floating-point digits and hashes containing those computed values. Record the execution environment when comparing artifact identity.

Среда сохранённого вывода: Python 3.9.7. Другие версии интерпретатора могут менять последние знаки чисел с плавающей точкой и хеши, содержащие вычисленные значения. Записывайте среду исполнения при сравнении идентичности артефактов.

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

Counts and rankings are fictional; no service or experiment is contacted. Normal approximations have stated fixed-sample assumptions. The exact fair-outcome enumeration illustrates a particular stopping design, not a general deployment guarantee.

Числа и ранжирования вымышлены; сервисы и эксперименты не вызываются. Нормальные приближения имеют заданные условия фиксированной выборки. Точный расчёт честных исходов иллюстрирует конкретные остановки, не общую гарантию деплоя.

from collections import defaultdict
from fractions import Fraction
import json
import math
from pathlib import Path
from statistics import NormalDist
 
def planning():
    baseline, alternative = .4, .44
    pooled = (baseline + alternative) / 2
    effect = alternative - baseline
    z_alpha = NormalDist().inv_cdf(.975)
    z_power = NormalDist().inv_cdf(.8)
    # Equal-variance normal approximation; independent Bernoulli units.
    samples = {str(q):math.ceil((z_alpha + z_power)**2 * pooled*(1-pooled)
                               / (effect**2*q*(1-q))) for q in [.5,.2,.1]}
    return dict(baseline=baseline, alternative=alternative, absolute_effect=effect,
                alpha_two_sided=.05, power=.8, planning_probability=pooled,
                total_sample_approximation=samples)
 
def comparison(success_a, count_a, success_b, count_b):
    a, b = success_a/count_a, success_b/count_b
    difference = b-a
    se = math.sqrt(a*(1-a)/count_a + b*(1-b)/count_b)
    pooled = (success_a+success_b)/(count_a+count_b)
    null_se = math.sqrt(pooled*(1-pooled)*(1/count_a+1/count_b))
    z = difference/null_se
    interval = [difference - NormalDist().inv_cdf(.975)*se,
                difference + NormalDist().inv_cdf(.975)*se]
    return dict(successes=[success_a,success_b],counts=[count_a,count_b],rates=[a,b],
                difference=difference,standard_error=se,interval_95_normal=interval,
                pooled_null_z=z,two_sided_normal_p=math.erfc(abs(z)/math.sqrt(2)),
                one_sided_lower_95=difference-NormalDist().inv_cdf(.95)*se)
 
def tail(n,k):
    return Fraction(sum(math.comb(n,j) for j in range(k,n+1)),2**n)
 
def peeking(looks,alpha):
    states={(0,False):1}
    thresholds={n:next((k for k in range(n+1) if tail(n,k)<=alpha),n+1) for n in looks}
    for n in range(1,max(looks)+1):
        updated=defaultdict(int)
        for (heads,hit),paths in states.items():
            for bit in [0,1]:
                new_heads=heads+bit
                crossed=hit or (n in looks and new_heads>=thresholds[n])
                updated[(new_heads,crossed)]+=paths
        states=updated
    all_paths=2**max(looks)
    assert sum(states.values())==all_paths
    false_paths=sum(count for (heads,hit),count in states.items() if hit)
    return dict(looks=looks,per_look_alpha=str(alpha),thresholds=thresholds,
                false_paths=false_paths,total_paths=all_paths,
                probability=str(Fraction(false_paths,all_paths)),fraction=false_paths/all_paths)
 
def assignment_check():
    observed=[2900,1900]
    expected=[2400,2400]
    statistic=sum((a-b)**2/b for a,b in zip(observed,expected))
    return dict(observed=observed,expected=expected,chi_square=statistic,
                approximate_df1_tail=math.erfc(math.sqrt(statistic/2)))
 
def interleave():
    rankings={'A':['quartz','cedar','reed','linen','plum'], 'B':['linen','quartz','spruce','reed','amber']}
    # Fixed illustrative coin outcomes at tied team sizes: B, then A.
    order=['B','A','A','B']
    selected=[]
    used=set()
    for team in order:
        doc=next(doc for doc in rankings[team] if doc not in used)
        selected.append(dict(document=doc,team=team))
        used.add(doc)
    assert selected==[dict(document='linen',team='B'),dict(document='quartz',team='A'),
                      dict(document='cedar',team='A'),dict(document='spruce',team='B')]
    clicks=['cedar']
    credited={team:sum(row['team']==team and row['document'] in clicks for row in selected) for team in rankings}
    return dict(rankings=rankings,illustrative_pick_order=order,slate=selected,clicks=clicks,credit=credited)
 
def mixture():
    rows=[dict(group='easy',baseline_success=16,baseline_count=20,candidate_success=60,candidate_count=80),
          dict(group='hard',baseline_success=24,baseline_count=80,candidate_success=5,candidate_count=20)]
    differences=[Fraction(r['candidate_success'],r['candidate_count'])-Fraction(r['baseline_success'],r['baseline_count']) for r in rows]
    pooled=Fraction(65,100)-Fraction(40,100)
    standardized=sum(differences)/2
    assert differences==[Fraction(-1,20)]*2 and pooled==Fraction(1,4) and standardized==Fraction(-1,20)
    return dict(rows=rows,within_group_differences=list(map(str,differences)),
                naive_total_difference=str(pooled),equal_group_standardized_difference=str(standardized))
result = dict(planning=planning(),improvement=comparison(960,2400,1048,2400),cheaper=comparison(960,2400,948,2400),fixed=peeking([20],Fraction(1,20)),repeated=peeking([4,8,12,16,20],Fraction(1,20)),corrected=peeking([4,8,12,16,20],Fraction(1,100)),assignment=assignment_check(),interleaving=interleave(),mixture=mixture())
print(json.dumps(result,indent=2,allow_nan=False))

Independent checks / Независимые проверки

Check identities, boundary behavior and separate arithmetic expectations. These checks establish only the stated fixture.

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

fixed_tail = sum(math.comb(20,k) for k in range(15,21))
assert fixed_tail == result["fixed"]["false_paths"] == 21700
assert result["repeated"]["false_paths"] == 68504
assert result["corrected"]["false_paths"] == 11102
assert result["corrected"]["fraction"] <= 5*.01
assert result["planning"]["total_sample_approximation"] == {"0.5":4780,"0.2":7469,"0.1":13278}
assert result["cheaper"]["one_sided_lower_95"] < -.02
assert result["interleaving"]["credit"] == {"A":1,"B":0}
assert Fraction(result["mixture"]["equal_group_standardized_difference"]) == Fraction(-1,20)
print("Self-checks passed: fixed exact tail, repeated-look counts, planning, margin and mixture.")

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

Keep the per-look threshold fixed and add looks. Compare the exact false-rejection probability. Then change group weights while holding within-group success rates fixed to distinguish mixture effects from treatment effects.

Сохраните порог одной проверки и добавьте моменты просмотра. Сравните точную вероятность ложного отклонения. Затем измените веса групп при прежних внутригрупповых долях, различая эффект состава и воздействия.