Skip to content
BIASED
Back to topic

Optional

Error-rate denominators and privacy arithmetic

Groups are artificial, not demographic data. The fixed Laplace quantile is deterministic and is not a private release. Clipping includes no noise or accountant and is not DP-SGD training. No attack code, sensitive data or legal classification is executed.

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.

Error-rate denominators and privacy arithmetic / Знаменатели ошибок и арифметика приватности

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 3e51bb0cf9033aa0daa14c034244fc6a3b64fbe6. 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/3e51bb0cf9033aa0daa14c034244fc6a3b64fbe6/src/content/notes/mlops/responsible-ml.mdx

First-party fixture: https://github.com/fpakhurov/fpakhurov.com/blob/3e51bb0cf9033aa0daa14c034244fc6a3b64fbe6/scripts/notes/mlops-responsible-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. Floating-point results can differ in their final digits under another interpreter; retain the environment with reproducibility evidence.

Среда сохранённого вывода: Python 3.9.7. Последние знаки результатов с плавающей точкой могут отличаться в другом интерпретаторе; сохраняйте среду вместе с данными воспроизводимости.

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

Groups are artificial, not demographic data. The fixed Laplace quantile is deterministic and is not a private release. Clipping includes no noise or accountant and is not DP-SGD training. No attack code, sensitive data or legal classification is executed.

Группы искусственные, не демографические данные. Фиксированный квантиль Лапласа определён и не является приватным выпуском. В ограничении градиентов нет шума или учёта; это не обучение DP-SGD. Код атак, чувствительные данные и правовая классификация не исполняются.

import itertools
import json
import math
from fractions import Fraction
 
 
 
def fairness():
    matrices = {"A": {"tp": 30, "fn": 10, "fp": 15, "tn": 45},
                "B": {"tp": 15, "fn": 5, "fp": 20, "tn": 60}}
    result = {}
    for group, row in matrices.items():
        total = sum(row.values())
        positives, negatives = row["tp"] + row["fn"], row["fp"] + row["tn"]
        selected = row["tp"] + row["fp"]
        rates = {"base_rate": Fraction(positives, total),
                 "selection": Fraction(selected, total), "tpr": Fraction(row["tp"], positives),
                 "fpr": Fraction(row["fp"], negatives), "ppv": Fraction(row["tp"], selected)}
        expected_ppv = rates["tpr"] * rates["base_rate"] / (
            rates["tpr"] * rates["base_rate"] + rates["fpr"] * (1 - rates["base_rate"]))
        assert expected_ppv == rates["ppv"]
        result[group] = {"counts": row, "rates": {k: str(v) for k, v in rates.items()}}
    assert result['A']['rates']['tpr'] == result['B']['rates']['tpr'] == '3/4'
    assert result['A']['rates']['fpr'] == result['B']['rates']['fpr'] == '1/4'
    assert result['A']['rates']['ppv'] == '2/3' and result['B']['rates']['ppv'] == '3/7'
    return result
 
def proxy():
    rows = [("A", 1), ("A", 1), ("A", 1), ("A", 0),
            ("B", 1), ("B", 0), ("B", 0), ("B", 0)]
    # The decision uses the flag only; the group is used solely for reporting.
    return {group: str(Fraction(sum(flag for g, flag in rows if g == group),
                                sum(g == group for g, flag in rows))) for group in ('A', 'B')}
 
def privacy_arithmetic():
    epsilon = .7
    scale = 1 / epsilon
    illustrative_u = .8
    noise_quantile = -scale * math.log(2 * (1 - illustrative_u))
    release_arithmetic = 7 + noise_quantile
    # Exhaustively check a tiny count domain, not the privacy of floating sampling.
    sensitivity = 0
    for bits in itertools.product((0, 1), repeat=5):
        for index in range(5):
            changed = bits[:index] + (1 - bits[index],) + bits[index + 1:]
            sensitivity = max(sensitivity, abs(sum(bits) - sum(changed)))
    assert sensitivity == 1
    # The paper proof is analytic; these points only check the displayed formula.
    log_ratios = [(abs(z - 8) - abs(z - 7)) / scale for z in (-20, 7, 7.5, 8, 20)]
    assert all(abs(value) <= epsilon + 1e-12 for value in log_ratios)
    assert math.isclose(release_arithmetic, 8.308986759820222)
    return {"epsilon": epsilon, "count_sensitivity": sensitivity, "count_scale": scale,
            "fixed_n_mean_sensitivity": .01, "fixed_n_mean_scale": .01 / epsilon,
            "illustrative_uniform_quantile": illustrative_u, "noise_quantile": noise_quantile,
            "count_plus_quantile": release_arithmetic,
            "pointwise_log_density_ratios_for_counts_7_8": log_ratios,
            "basic_composition_epsilon": str(Fraction(1, 5) + Fraction(3, 10)),
            "warning": "Fixed quantile is not a random private release; no production sampler/accountant implemented"}
 
def clipping():
    gradients = [(3, 4), (-6, 8), (0, 2)]
    bound = 5
    clipped = []
    for gradient in gradients:
        norm = math.sqrt(sum(value * value for value in gradient))
        clipped.append([value / max(1, norm / bound) for value in gradient])
    raw_mean = [sum(g[i] for g in gradients) / len(gradients) for i in (0, 1)]
    clipped_mean = [sum(g[i] for g in clipped) / len(clipped) for i in (0, 1)]
    assert clipped == [[3., 4.], [-3., 4.], [0., 2.]]
    assert math.sqrt(sum(v*v for v in raw_mean)) < bound
    assert raw_mean != clipped_mean
    return {"per_example_gradients": gradients, "norm_bound": bound,
            "clipped_gradients": clipped, "raw_mean": raw_mean,
            "clipped_mean": clipped_mean,
            "warning": "Clipping arithmetic only; no noise, DP-SGD training or privacy guarantee"}
result = dict(fairness=fairness(),proxy_selection=proxy(),privacy_arithmetic=privacy_arithmetic(),clipping=clipping())
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.

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

from decimal import Decimal,localcontext
A=result["fairness"]["A"]["rates"];B=result["fairness"]["B"]["rates"]
assert Fraction(A["tpr"])==Fraction(B["tpr"])==Fraction(3,4)
assert Fraction(A["fpr"])==Fraction(B["fpr"])==Fraction(1,4)
assert Fraction(A["ppv"])==Fraction(2,3)!=Fraction(B["ppv"])
t,f=Fraction(3,4),Fraction(1,4)
ppv=lambda p:t*p/(t*p+f*(1-p))
assert ppv(Fraction(2,5))==Fraction(2,3)
assert ppv(Fraction(1,5))==Fraction(3,7)
assert Fraction(1,5)+Fraction(3,10)==Fraction(1,2)
with localcontext() as context:
    context.prec=50
    quantile=-(Decimal(1)/Decimal('0.7'))*(2*(1-Decimal('0.8'))).ln()
    assert abs(float(quantile)-result["privacy_arithmetic"]["noise_quantile"])<1e-12
assert result["clipping"]["clipped_gradients"]==[[3.,4.],[-3.,4.],[0.,2.]]
assert math.isclose(result["clipping"]["clipped_mean"][1],float(Fraction(10,3)))
assert result["clipping"]["raw_mean"]!=result["clipping"]["clipped_mean"]
print("Self-checks passed: rate denominators, Bayes identity, composition, quantile and clipping.")

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

Change a base rate while keeping positive TPR and FPR fixed, and recompute PPV. Separately compare per-example clipping with clipping only the mean. Do not use the fixed-quantile demonstration to release private data.

Измените базовую долю при фиксированных положительных TPR и FPR и пересчитайте PPV. Отдельно сравните ограничение по примерам с ограничением только среднего. Не используйте фиксированный квантиль для раскрытия частных данных.