Optional
A retraining proposal and its evidence
All costs, scalar tasks, label times and predictions are fictional. The schedule assumes instantaneous successful replacement; feedback uses expected counts. This does not train a neural network or release a production model.
- 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 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.
A retraining proposal and its evidence / Предложение переобучения и его данные
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/continual-learning.mdx
First-party fixture: https://github.com/fpakhurov/fpakhurov.com/blob/3e51bb0cf9033aa0daa14c034244fc6a3b64fbe6/scripts/notes/mlops-continual-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 / Входы и границы
All costs, scalar tasks, label times and predictions are fictional. The schedule assumes instantaneous successful replacement; feedback uses expected counts. This does not train a neural network or release a production model.
Все стоимости, скалярные задачи, времена меток и прогнозы вымышлены. Расписание предполагает мгновенную успешную замену; обратная связь использует ожидаемые числа. Нейросеть не обучается и модель в продакшен не выпускается.
import json
import math
from fractions import Fraction
COHORT = [
{"id": "a", "decision": 0, "prediction": 0, "truth": 0, "label_available": 4},
{"id": "b", "decision": 1, "prediction": 1, "truth": 1, "label_available": 2},
{"id": "c", "decision": 2, "prediction": 0, "truth": 1, "label_available": 10},
{"id": "d", "decision": 3, "prediction": 1, "truth": 0, "label_available": 12},
{"id": "e", "decision": 4, "prediction": 0, "truth": 0, "label_available": 5},
{"id": "f", "decision": 5, "prediction": 1, "truth": 1, "label_available": 7},
]
def fraction_text(value):
return str(value)
def renewal_cost():
cost = Fraction(12)
decay = Fraction(3, 4)
candidates = [
{"hours": hours, "average_cost": float(cost / hours + decay * hours / 2)}
for hours in range(1, 13)
]
best = min(candidates, key=lambda row: row["average_cost"])
assert best == {"hours": 6, "average_cost": 4.25}
return {"training_cost": float(cost), "age_cost_rate": float(decay),
"continuous_optimum_hours": math.sqrt(float(2 * cost / decay)),
"integer_candidates": candidates, "best_integer": best}
def forgetting():
settings = {"after_A": Fraction(1), "after_B": Fraction(-2),
"equal_replay": Fraction(-1, 2), "quadratic_anchor": Fraction(0)}
rows = []
for name, weight in settings.items():
loss_a, loss_b = (weight - 1) ** 2, (weight + 2) ** 2
rows.append({"setting": name, "w": fraction_text(weight),
"loss_A": fraction_text(loss_a), "loss_B": fraction_text(loss_b)})
assert rows[2]["loss_A"] == rows[2]["loss_B"] == "9/4"
assert rows[3]["loss_A"] == "1" and rows[3]["loss_B"] == "4"
return rows
def delayed_labels():
rows = []
for cutoff in (6, 12):
observed = [row for row in COHORT if row["label_available"] <= cutoff]
correct = sum(row["prediction"] == row["truth"] for row in observed)
rows.append({"cutoff": cutoff, "observed_ids": [row["id"] for row in observed],
"correct": correct, "observed": len(observed),
"cohort_size": len(COHORT), "accuracy": str(Fraction(correct, len(observed)))})
assert rows[0]["accuracy"] == "1" and rows[1]["accuracy"] == "2/3"
return {"cohort": COHORT, "snapshots": rows}
def exposure_feedback():
share = Fraction(4, 5)
path = [str(share)]
for _ in range(3):
share = share ** 2 / (share ** 2 + (1 - share) ** 2)
path.append(str(share))
assert path == ["4/5", "16/17", "256/257", "65536/65537"]
return {"equal_click_probability": "1/2", "expected_exposure_share": path}
def paired_gate():
rows = []
for index in range(12):
truth = index % 2
baseline = truth if index < 7 else 1 - truth
candidate = 1 - truth if index == 6 else truth
rows.append({"id": index, "truth": truth, "baseline": baseline,
"candidate": candidate, "critical": index == 6})
gains = sum(r["baseline"] != r["truth"] and r["candidate"] == r["truth"] for r in rows)
losses = sum(r["baseline"] == r["truth"] and r["candidate"] != r["truth"] for r in rows)
discordant = gains + losses
tail = Fraction(sum(math.comb(discordant, k) for k in range(max(gains, losses), discordant + 1)),
2 ** discordant)
p_value = min(Fraction(1), 2 * tail)
critical_pass = all(r["candidate"] == r["truth"] for r in rows if r["critical"])
assert (gains, losses, p_value, critical_pass) == (5, 1, Fraction(7, 32), False)
return {"rows": rows, "baseline_correct": 7, "candidate_correct": 11,
"gains": gains, "losses": losses, "two_sided_p": str(p_value),
"critical_gate_pass": critical_pass}result = dict(renewal_cost=renewal_cost(),forgetting=forgetting(),delayed_labels=delayed_labels(),exposure_feedback=exposure_feedback(),paired_gate=paired_gate())
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.
Проверьте идентичности, поведение на границах и отдельные арифметические ожидания. Проверки устанавливают только заданный пример.
# Independent exact arithmetic and exhaustive six-direction null paths.
from itertools import product
costs={h:Fraction(12,h)+Fraction(3,4)*h/2 for h in range(1,13)}
assert min(costs,key=costs.get)==6 and costs[6]==Fraction(17,4)
assert (Fraction(-1,2)-1)**2==(Fraction(-1,2)+2)**2==Fraction(9,4)
assert [r["observed"] for r in result["delayed_labels"]["snapshots"]]==[3,6]
assert [r["accuracy"] for r in result["delayed_labels"]["snapshots"]]==["1","2/3"]
paths=list(product((0,1),repeat=6))
extreme=sum(sum(bits)<=1 or sum(bits)>=5 for bits in paths)
assert Fraction(extreme,len(paths))==Fraction(7,32)
assert Fraction(result["paired_gate"]["two_sided_p"])==Fraction(7,32)
assert result["paired_gate"]["critical_gate_pass"] is False
assert result["exposure_feedback"]["expected_exposure_share"]==["4/5","16/17","256/257","65536/65537"]
print("Self-checks passed: schedule, task losses, label maturity, 14/64 null paths and critical failure.")Change one assumption / Измените предположение
Change the label cutoff while keeping the same decision cohort. Then change the cost model separately. Explain why a cheaper retraining interval is not evidence that a new candidate passes its critical cases.
Измените срок меток при неизменной когорте решений. Затем отдельно измените модель стоимости. Объясните, почему более дешёвый интервал не доказывает прохождение критических примеров кандидатом.