По желанию
Проверьте протокол оценки
Изучите полные вымышленные входы, повторите расчёты стандартной библиотекой и проверьте инварианты. Необязательная практика на компьютере.
- Версия
- v1
- Минут
- ~15
- Проверка
- Самопроверка в ноутбуке
Пока нет автопроверки на платформе: сравните вывод ячеек с ожидаемыми числами в ноутбуке. Это не долг и не влияет на процент освоения.
Скачайте ноутбук и запустите его локально. Требования к окружению указаны внутри.
Содержимое ноутбука
Можно прочитать с телефона. Код ниже не выполнялся в браузере; для запуска скачайте ноутбук.
Corpora and evaluation / Корпусы и оценка качества
Optional practice. The lesson and its phone questions are complete without running code. / Необязательная практика: урок и задания на телефоне самостоятельны.
All inputs and calculations were authored for the Fedor Pakhurov project with Codex assistance. The example is fictional and contains no external corpus, model, or copied third-party implementation. Selected first-party functions are retained from the published reviewed fixture. This notebook adds packaging and explicit self-checks; it does not claim operational quality.
Все входы вымышлены; расчёты созданы для проекта Фёдора Пахурова с помощью Codex. Внешних корпусов, моделей и сторонних реализаций здесь нет. Функции взяты из указанной опубликованной проверенной версии; добавлены оформление и самопроверки.
Saved outputs use Python 3.9.7; standard library only, no network or file writes. Floating last digits and Unicode database values can differ across runtimes. / Сохранённый запуск: Python 3.9.7, только стандартная библиотека, без сети и записи файлов. Последние разряды и версия Unicode могут зависеть от среды.
import json
import math
import re
import unicodedata
from collections import Counter
from fractions import Fraction
TICKETS = [
("lamp broken after pickup", 1),
("tripod broken at hinge", 1),
("microphone broken cable", 1),
("lamp sparks at switch", 1),
("replace broken carrying case", 0),
("is a broken seal acceptable", 0),
("extend the tripod booking", 0),
("return microphone tomorrow", 0),
("where is the pickup desk", 0),
("reserve a spare lamp", 0),
("change my collection time", 0),
("confirm the return receipt", 0),
]
def fraction_text(value):
return str(Fraction(value))
def confusion(truth, predictions):
if len(truth) != len(predictions) or not truth:
raise ValueError("Aligned nonempty vectors required")
if any(value not in (0, 1) for value in [*truth, *predictions]):
raise ValueError("Binary labels required")
tp = sum(y == 1 and p == 1 for y, p in zip(truth, predictions))
fp = sum(y == 0 and p == 1 for y, p in zip(truth, predictions))
fn = sum(y == 1 and p == 0 for y, p in zip(truth, predictions))
tn = sum(y == 0 and p == 0 for y, p in zip(truth, predictions))
return tp, fp, fn, tn
def evaluation():
truth = [label for _, label in TICKETS]
predictions = [int("broken" in text.split()) for text, _ in TICKETS]
tp, fp, fn, tn = confusion(truth, predictions)
assert (tp, fp, fn, tn) == (3, 2, 1, 6)
accuracy = Fraction(tp + tn, len(truth))
precision, recall = Fraction(tp, tp + fp), Fraction(tp, tp + fn)
f1 = Fraction(2 * tp, 2 * tp + fp + fn)
f1_negative = Fraction(2 * tn, 2 * tn + fp + fn)
# Artificial replicas share each underlying issue. The split policies are fixed here.
pairs = [(group, copy) for group in range(6) for copy in range(2)]
row_train = [i for i, (_, copy) in enumerate(pairs) if copy == 0]
row_test = [i for i, (_, copy) in enumerate(pairs) if copy == 1]
group_train = [i for i, (group, _) in enumerate(pairs) if group < 4]
group_test = [i for i, (group, _) in enumerate(pairs) if group >= 4]
def overlap(train, test):
return sorted({pairs[i][0] for i in train} & {pairs[i][0] for i in test})
assert overlap(row_train, row_test) == list(range(6))
assert overlap(group_train, group_test) == []
gold_spans = {(0, 4, "ITEM"), (14, 20, "DATE")}
predicted_spans = {(0, 4, "ITEM"), (15, 20, "DATE")}
correct_spans = len(gold_spans & predicted_spans)
span_f1 = Fraction(2 * correct_spans, len(gold_spans) + len(predicted_spans))
assert span_f1 == Fraction(1, 2)
return {"tickets": [{"text": text, "gold_inspection": label, "rule_prediction": pred}
for (text, label), pred in zip(TICKETS, predictions)],
"confusion": {"tp": tp, "fp": fp, "fn": fn, "tn": tn},
"accuracy": fraction_text(accuracy), "precision": fraction_text(precision),
"recall": fraction_text(recall), "f1": fraction_text(f1),
"negative_f1": fraction_text(f1_negative), "macro_f1": fraction_text((f1 + f1_negative) / 2),
"always_no_inspection_accuracy": fraction_text(Fraction(8, 12)),
"row_split_shared_groups": overlap(row_train, row_test),
"group_split_shared_groups": overlap(group_train, group_test),
"strict_span_f1": fraction_text(span_f1)}
result = evaluation()
print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True))
assert result['macro_f1'] == '11/15'
assert result['strict_span_f1'] == '1/2'
assert result['group_split_shared_groups'] == []
print('All local checks passed; this is a constructed example, not a benchmark.')