"""Render the counts, cohort heatmaps, and held-out error-tree results.""" import json from pathlib import Path import matplotlib.pyplot as plt from matplotlib.colors import Normalize import numpy as np ROOT = Path(__file__).parent DATA = json.loads((ROOT / "diagnostics.json").read_text()) MODELS = ( ("amount_rule", "Отбор по сумме"), ("logistic_regression", "Логистическая регрессия"), ("random_forest", "Случайный лес"), ) def save(fig, name): fig.savefig(ROOT / name, dpi=172, facecolor="white", bbox_inches="tight", pad_inches=.24) plt.close(fig) def matrices(): fig, axes = plt.subplots(1, 3, figsize=(11, 3.3), layout="constrained") for ax, (key, title) in zip(axes, MODELS): matrix = np.array(DATA["models"][key]["whole_test"]["matrix_actual_rows_selected_columns"]) normalized = matrix / matrix.sum(axis=1, keepdims=True) ax.imshow(normalized, cmap="Blues", vmin=0, vmax=1) ax.set(xticks=[0, 1], xticklabels=["Вне очереди", "В очереди"], yticks=[0, 1], yticklabels=["Без метки", "С меткой"], title=title) for row, col in np.ndindex(matrix.shape): rate = normalized[row, col] count = f"{matrix[row, col]:,}".replace(",", " ") ax.text(col, row, f"{count}\n{rate:.1%}".replace(".", ","), ha="center", va="center", color="white" if rate > .55 else "#152739", fontsize=10) save(fig, "matrices.png") def heatmaps(): forest = DATA["models"]["random_forest"] rows = forest["heatmap"] all_missed = forest["whole_test"]["misses"] fig, axes = plt.subplots(1, 2, figsize=(10.4, 3.5), layout="constrained") for ax, label, title in zip(axes, ["miss_rate_among_positives", "miss_coverage_of_all_misses"], ["Доля пропусков среди подтверждённых", f"Распределение {all_missed} пропусков"]): data = np.array([[cell[label] for cell in row["cells"]] for row in rows], dtype=float) view = ax.imshow(np.ma.masked_invalid(data), cmap="YlOrBr", norm=Normalize(0, 1), aspect="auto") ax.set(xticks=[0, 1, 2], xticklabels=["Нижние 50%", "Средние 45%", "Верхние 5%"], yticks=[0, 1], yticklabels=[item["hours"] for item in rows], title=title) ax.set_xlabel("Диапазон суммы по границам обучения") ax.set_ylabel("Часы с начала записи") for a, b in np.ndindex(data.shape): cell = rows[a]["cells"][b] denominator = cell["positives"] if label == "miss_rate_among_positives" else all_missed displayed = f"{cell['misses']}/{denominator}\n{data[a, b]:.1%}".replace(".", ",") if denominator else "нет данных" ax.text(b, a, displayed, ha="center", va="center", color="white" if data[a, b] > .6 else "#332315", fontsize=11) fig.colorbar(view, ax=ax, fraction=.04, pad=.03) save(fig, "heatmaps.png") def tree_plot(): leaves = DATA["error_tree"]["leaves"] fig, ax = plt.subplots(figsize=(11, 4.4)) ax.set_axis_off() def draw(group, depth, offset, width, incoming=None): x, y = offset + width / 2, 1 - depth * .34 total = sum(item["test"]["sample_count"] for item in group) misses = sum(item["test"]["errors"] for item in group) next_rule = [item["rules"][depth] for item in group if len(item["rules"]) > depth] tested = f"{misses}/{total} пропусков" if next_rule: name, limit, _ = next_rule[0] text = f"{incoming or 'Все с меткой'}\n{name}, порог {limit:.3f}\n{tested}" else: text = f"{incoming}\nЛист {group[0]['node']}\n{tested}" ax.text(x, y, text.replace(".", ","), ha="center", va="center", fontsize=11, bbox={"facecolor":"#e8f1ec" if next_rule else "#f6f9f7", "edgecolor":"#69877b", "pad":6}) if next_rule: for i, operator in enumerate(("<=", ">")): sub = [item for item in group if item["rules"][depth][2] == operator] start = offset + i * width / 2 child_x = start + width / 4 ax.plot([x, child_x], [y - .07, y - .27], color="#668275", linewidth=1.2, zorder=0) bound = f"{next_rule[0][1]:.3f}".replace(".", ",") draw(sub, depth + 1, start, width / 2, f"{name} {'≤' if i == 0 else '>'} {bound}") draw(leaves, 0, 0, 1) ax.set_xlim(0, 1) ax.set_ylim(.16, 1.10) save(fig, "error-tree.png") if __name__ == "__main__": matrices() heatmaps() tree_plot()