По желанию
Ошибки схемы, хвостовая вероятность и байты
Восемь придуманных строк задают обязательную схему. Отдельный биномиальный пример предполагает независимые записи и известный фиксированный эталон; внешних данных и фреймворка валидации нет.
- Версия
- v2
- Минут
- ~20
- Проверка
- Самопроверка в ноутбуке
Пока нет автопроверки на платформе: сравните вывод ячеек с ожидаемыми числами в ноутбуке. Это не долг и не влияет на процент освоения.
Скачайте ноутбук и запустите его локально. Требования к окружению указаны внутри.
Содержимое ноутбука
Можно прочитать с телефона. Код ниже не выполнялся в браузере; для запуска скачайте ноутбук.
Schema failures, a tail probability and byte identity / Ошибки схемы, хвостовая вероятность и байты
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.
First-party fixture: https://github.com/fpakhurov/fpakhurov.com/blob/840854d82dc3f9e208c0ed88a92180ccde4e3803/scripts/notes/mlops-data-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 / Входы и границы
Eight invented rows define the hard schema. The separate binomial example assumes independent records and a fixed known reference; no external data or validation framework is used.
Восемь придуманных строк задают обязательную схему. Отдельный биномиальный пример предполагает независимые записи и известный фиксированный эталон; внешних данных и фреймворка валидации нет.
from collections import Counter
import hashlib
import json
import math
import os
from pathlib import Path
import tempfile
def encoded(value):
return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
def sha(value):
return hashlib.sha256(encoded(value)).hexdigest()
def validate(rows):
def valid_id(value):
return isinstance(value, str) and bool(value.strip())
counts = Counter(row.get("id") for row in rows
if isinstance(row, dict) and valid_id(row.get("id")))
failures = []
for index, row in enumerate(rows):
if not isinstance(row, dict):
failures.append({"row": index, "id": None, "reasons": ["invalid_record"]})
continue
reasons = []
identifier = row.get("id")
if not valid_id(identifier):
reasons.append("invalid_id")
contrast = row.get("contrast")
if contrast is None:
reasons.append("missing_contrast")
elif (isinstance(contrast, bool) or not isinstance(contrast, (int, float))
or not 0 <= contrast <= 1 or not math.isfinite(contrast)):
reasons.append("invalid_contrast")
width = row.get("width")
if not isinstance(width, int) or isinstance(width, bool) or width <= 0:
reasons.append("invalid_width")
if row.get("format") not in ("png", "jpg"):
reasons.append("unsupported_format")
if valid_id(identifier) and counts[identifier] > 1:
reasons.append("duplicate_id")
if reasons:
failures.append({"row": index, "id": identifier, "reasons": reasons})
return failures
def quality():
rows = [dict(id=i, contrast=c, width=w, format=f) for i,c,w,f in [
("c01", .8, 640, "png"), ("c02", .7, 640, "jpg"), ("c03", .25, 480, "png"),
("c04", None, 640, "jpg"), ("c05", .6, 0, "png"), ("c06", 1.1, 640, "png"),
("c07", .9, 640, "gif"), ("c07", .4, 640, "jpg")]]
failures=validate(rows)
counts=dict(Counter(reason for row in failures for reason in row["reasons"]))
assert len(failures)==5 and sum(counts.values())==6
# Adversarial schema checks are separate from the unchanged eight-row lesson.
valid = dict(id="edge", contrast=.5, width=640, format="png")
for value in [None, "", " ", [], 7]:
assert "invalid_id" in validate([{**valid, "id": value}])[0]["reasons"]
for value in [True, False, float("nan"), float("inf"), "0.5", 10**1000]:
assert "invalid_contrast" in validate([{**valid, "contrast": value}])[0]["reasons"]
for field, reason in [("id", "invalid_id"), ("contrast", "missing_contrast"),
("width", "invalid_width"), ("format", "unsupported_format")]:
incomplete = dict(valid)
del incomplete[field]
assert reason in validate([incomplete])[0]["reasons"]
assert validate([None])[0]["reasons"] == ["invalid_record"]
assert "invalid_width" in validate([{**valid, "width": True}])[0]["reasons"]
assert not validate([valid])
a=[{"id":"c01","contrast":.8},{"id":"c02","contrast":.7}]
same_content=list(reversed(a))
canonical=lambda values: sorted(values,key=lambda row:row["id"])
modified=[{"id":"c01","contrast":.81},{"id":"c02","contrast":.7}]
assert sha(canonical(a))==sha(canonical(same_content))!=sha(canonical(modified))
p=.75
tail=sum(math.comb(40,k)*p**k*(1-p)**(40-k) for k in range(21))
assert 0<tail<.01
return {"rows":rows,"row_failures":failures,"reason_counts":counts,"rejected_rows":5,
"remaining_rows":3,"batch_publish_pass":not failures,
"reference_format_fraction_png":.75,"current_png_count":20,"current_count":40,
"linfinity_discrepancy":.25,"one_sided_binomial_probability_at_most_20":tail,
"binomial_assumption":"40 independent records, fixed true PNG probability .75; one predeclared direction",
"canonical_original_sha256":sha(canonical(a)),"canonical_changed_sha256":sha(canonical(modified)),
"raw_order_changes_bytes":sha(a)!=sha(same_content),"canonical_order_same_bytes":True}result = quality()
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 fractions import Fraction as F
expected = sum(F(math.comb(40,k))*F(3,4)**k*F(1,4)**(40-k) for k in range(21))
assert expected == F(346013372707911438797,604462909807314587353088)
assert math.isclose(result["one_sided_binomial_probability_at_most_20"],float(expected))
assert result["rejected_rows"] == 5 and sum(result["reason_counts"].values()) == 6
valid = dict(id="check",contrast=0,width=1,format="png")
assert validate([valid]) == []
assert "invalid_contrast" in validate([{**valid,"contrast":True}])[0]["reasons"]
assert "invalid_width" in validate([{**valid,"width":False}])[0]["reasons"]
assert validate([None])[0]["reasons"] == ["invalid_record"]
print("Self-checks passed: exact directional tail, row/reason counts and schema boundaries.")Change one assumption / Измените предположение
Give one row two failures and distinguish the number of reasons from the number of rejected rows. Then change only row order under the explicitly order-insensitive format.
Задайте одной строке два нарушения и различите число причин и отклонённых строк. Затем измените только порядок при явно незначимом порядке формата.