Skip to content
BIASED
Back to topic

Optional

Find a forbidden identifier dependency

The score is a hand-specified test double, not a learned probability. Numeric blur is finite in [0,1], missing is 0/1, IDs are strings; this is not a general raw-record schema validator. The optional bug adds a filename-dependent term. The gradient and serialization checks establish arithmetic, not model quality.

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.

Find a forbidden identifier dependency / Найти запрещённую зависимость от ID

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/testing-ml-systems.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 / Входы и границы

The score is a hand-specified test double, not a learned probability. Numeric blur is finite in [0,1], missing is 0/1, IDs are strings; this is not a general raw-record schema validator. The optional bug adds a filename-dependent term. The gradient and serialization checks establish arithmetic, not model quality.

Оценка — заданный вручную тестовый предиктор, не обученная вероятность. Числовой blur конечен в [0,1], missing — 0/1, ID — строки; это не общий валидатор сырых записей. Необязательный дефект добавляет зависимость от имени. Проверки градиента и сериализации устанавливают арифметику, а не качество модели.

import hashlib
import itertools
import json
import math
 
def score(blur, missing, document_id="", buggy=False):
    if not math.isfinite(blur) or not 0 <= blur <= 1 or missing not in (0, 1):
        raise ValueError("Input outside fixture schema")
    value = 0.1 + 0.8 * blur + 0.1 * missing
    if buggy and document_id.endswith("-export"):
        value += 0.25
    return min(1.0, value)
 
def testing():
    assert math.isclose(score(0, 0), 0.1)
    assert math.isclose(score(1, 1), 1.0)
    blurs = [0.1, 0.3, 0.45, 0.55, 0.7, 0.9]
    changes = sum((score(b, 0, "card", True) >= 0.6) !=
                  (score(b, 0, "card-export", True) >= 0.6) for b in blurs)
    assert changes == 2
    assert all(score(b, 0) <= score(min(1, b + 0.05), 0) for b in blurs)
    assert all(score(b, 0, "card") == score(b, 0, "card-export") for b in blurs)
    rejected = 0
    for b in [-0.01, 1.01, float("nan"), float("inf")]:
        try:
            score(b, 0)
        except ValueError:
            rejected += 1
    assert rejected == 4
    inputs, labels = [0.0, 1.0], [0.0, 1.0]
    weight, bias = 0.0, 0.0
    errors = [weight * x + bias - y for x, y in zip(inputs, labels)]
    loss_before = sum(e * e for e in errors) / 2
    weight -= 0.1 * sum(e * x for e, x in zip(errors, inputs))
    bias -= 0.1 * sum(errors)
    loss_after = sum((weight*x+bias-y)**2 for x,y in zip(inputs,labels)) / 2
    assert math.isclose(loss_after, 0.325) and loss_after < loss_before
    artifact = json.loads(json.dumps({"weight": weight, "bias": bias}))
    assert [artifact["weight"]*x+artifact["bias"] for x in inputs] == [weight*x+bias for x in inputs]
    return {"blur_values": blurs, "threshold": 0.6, "buggy_identifier_decision_changes": changes,
            "compared_pairs": len(blurs), "repaired_changes": 0,
            "invalid_inputs_rejected": rejected, "monotonicity_checks": len(blurs),
            "boundary_scores": [score(0, 0), score(1, 1)],
            "gradient_check_loss_before": loss_before, "gradient_check_loss_after": loss_after,
            "json_roundtrip_predictions": [weight*x+bias for x in inputs]}
result = testing()
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
blurs = [F(1,10),F(3,10),F(45,100),F(55,100),F(7,10),F(9,10)]
base = [min(F(1), F(1,10)+F(4,5)*b) for b in blurs]
bug = [min(F(1), x+F(1,4)) for x in base]
changed = [i for i,(a,b) in enumerate(zip(base,bug)) if (a>=F(3,5)) != (b>=F(3,5))]
assert changed == [2,3]
assert F(1,2) * (F(1,10)**2 + (F(1,5)-1)**2) == F(13,40)
assert math.isclose(result["gradient_check_loss_after"], float(F(13,40)))
assert result["repaired_changes"] == 0
print("Self-checks passed: exact score arithmetic isolates two rename failures and loss 13/40.")

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

Inspect which two blur values cross threshold 0.6 after the forbidden rename. Then choose a threshold where no decision changes and explain why the score-level invariance test remains useful.

Найдите два blur, пересекающих порог 0.6 после запрещённого переименования. Затем выберите порог без изменившихся решений и объясните, почему инвариантность самих оценок всё равно полезна.