Перейти к содержимому
BIASED
К теме

По желанию

Восстановить доступные исторические признаки

У пяти придуманных строк разные часы события и доступности. Отбор предполагает корректный смысл часов и отвергает конфликтующие допустимые ключи. Сервис хранилища признаков и измерение реальной accuracy не используются.

Версия
v2
Минут
~20
Проверка
Самопроверка в ноутбуке

Пока нет автопроверки на платформе: сравните вывод ячеек с ожидаемыми числами в ноутбуке. Это не долг и не влияет на процент освоения.

Скачать .ipynb

Скачайте ноутбук и запустите его локально. Требования к окружению указаны внутри.

Содержимое ноутбука

Можно прочитать с телефона. Код ниже не выполнялся в браузере; для запуска скачайте ноутбук.

Reconstruct available historical features / Восстановить доступные исторические признаки

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/features-and-skew.mdx

First-party fixture: https://github.com/fpakhurov/fpakhurov.com/blob/840854d82dc3f9e208c0ed88a92180ccde4e3803/scripts/notes/mlops-features-registry-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 / Входы и границы

Five invented rows have distinct event and availability clocks. The selector assumes their meanings are correct and rejects conflicting eligible clock keys. No feature-store service or real accuracy measurement is involved.

У пяти придуманных строк разные часы события и доступности. Отбор предполагает корректный смысл часов и отвергает конфликтующие допустимые ключи. Сервис хранилища признаков и измерение реальной accuracy не используются.

import hashlib
import json
import math
from pathlib import Path
 
def point_in_time(rows,card,prediction_hour,ttl=None,require_available=True):
    candidates=[r for r in rows if r['card']==card and r['event_hour']<=prediction_hour
                and (not require_available or r['available_hour']<=prediction_hour)
                and (ttl is None or prediction_hour-r['event_hour']<=ttl)]
    seen = {}
    for row in candidates:
        key = (row['event_hour'], row['available_hour'])
        if key in seen and seen[key] != row['contrast']:
            raise ValueError('Conflicting values for the same feature clock key')
        seen[key] = row['contrast']
    if not candidates:return None
    return max(candidates,key=lambda r:(r['event_hour'],r['available_hour']))['contrast']
 
def features():
    rows=[dict(card=card,event_hour=e,available_hour=a,contrast=c)
          for card,e,a,c in [('A',8,8,.2),('A',8,20,.9),('A',25,25,.4),
                             ('B',7,7,.7),('B',9,15,.1)]]
    decisions=[('A',10),('B',10),('A',30)]
    correct=[point_in_time(rows,*item) for item in decisions]
    event_only=[point_in_time(rows,*item,require_available=False) for item in decisions]
    latest=[point_in_time(rows,card,100) for card,_ in decisions]
    stale=[point_in_time(rows,*item,ttl=4) for item in decisions]
    assert correct==[.2,.7,.4] and event_only==[.9,.1,.4] and latest==[.4,.1,.4]
    assert stale==[.2,.7,None]
    assert point_in_time(rows + [dict(rows[0])], 'A', 10) == .2
    try:
        point_in_time(rows + [{**rows[0], 'contrast': .3}], 'A', 10)
    except ValueError:
        pass
    else:
        raise AssertionError('Ambiguous clock-key ties must be rejected')
    future_conflict = {**rows[2], 'contrast': .6}
    assert point_in_time(rows + [future_conflict], 'A', 10) == .2
    changes=sum((a<.5)!=(b<.5) for a,b in zip(correct,event_only))
    assert changes==2
    return {'feature_rows':rows,'decisions':[dict(card=c,hour=h) for c,h in decisions],
            'available_point_in_time':correct,'event_time_only':event_only,'latest_now':latest,
            'ttl_four_hours':stale,'event_time_only_decision_disagreements':changes,
            'training_mean':sum(correct)/len(correct),'centered_features':[x-sum(correct)/len(correct) for x in correct]}
result = features()
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
rows = result["feature_rows"]
assert point_in_time(rows,"A",19) == .2
assert point_in_time(rows,"A",20) == .9
assert point_in_time(rows,"A",30,ttl=4) is None
assert point_in_time(rows,"A",30,ttl=5) == .4
conflict = {**rows[0],"contrast":.3}
for ordered in [rows+[conflict],list(reversed(rows+[conflict]))]:
    try: point_in_time(ordered,"A",10)
    except ValueError: pass
    else: raise AssertionError("Ambiguous eligible clock key was accepted")
assert math.isclose(result["training_mean"],float(F(13,30)))
assert result["event_time_only_decision_disagreements"] == 2
print("Self-checks passed: availability boundary, inclusive TTL, tie conflicts and mean 13/30.")

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

Move a correction’s availability time across the prediction. Keep its event time fixed. Then change TTL and inspect when a missing result is the correct historical answer.

Сдвиньте доступность исправления через момент прогноза при неизменном времени события. Затем измените TTL и проследите, когда пропуск является корректным историческим ответом.