Repository navigation
Expand file tree
/
Copy pathmake_reliability_figure.py
More file actions
96 lines (84 loc) · 3.2 KB
/
Copy pathmake_reliability_figure.py
File metadata and controls
96 lines (84 loc) · 3.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"""Reliability diagram for the calibrated failure probability (held-out).
Visual proof that the isotonic calibration is real: fit on a random half of the 93,435
cross-lab designs, then on the OTHER half bin the predicted P(fail) and plot it against
the observed failure rate. A calibrated model sits on the diagonal. Annotates held-out ECE.
CPU, seconds, no GPU. Writes docs/cisfalcon_calibration.png.
"""
import numpy as np
import pandas as pd
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from sklearn.isotonic import IsotonicRegression
DATA = Path(__file__).parent / "data"
OUT = Path(__file__).parent / "docs" / "cisfalcon_calibration.png"
OUT.parent.mkdir(exist_ok=True)
df = (
pd.read_csv(DATA / "gosai_designed" / "designed_scored.csv")
.rename(columns={"measured_fail": "fail"})[["pred_gap", "fail"]]
.dropna()
)
df["fail"] = df["fail"].astype(int)
rng = np.random.default_rng(0)
perm = rng.permutation(len(df))
half = len(df) // 2
A, B = df.iloc[perm[:half]], df.iloc[perm[half:]]
n_bins = 10
def fit_eval(fit, ev):
"""Isotonic fit on `fit`, binned reliability + ECE evaluated on `ev`."""
iso = IsotonicRegression(increasing=False, out_of_bounds="clip").fit(
fit["pred_gap"].values, fit["fail"].values
)
p = iso.predict(ev["pred_gap"].values)
y = ev["fail"].values.astype(float)
edges = np.linspace(0, 1, n_bins + 1)
idx = np.clip(np.digitize(p, edges[1:-1]), 0, n_bins - 1)
conf, obs, cnt = [], [], []
ece = 0.0
for b in range(n_bins):
m = idx == b
if not m.any():
continue
conf.append(p[m].mean())
obs.append(y[m].mean())
cnt.append(int(m.sum()))
ece += m.mean() * abs(p[m].mean() - y[m].mean())
return np.array(conf), np.array(obs), np.array(cnt), ece
# The prose everywhere else quotes 0.0031, which is the MEAN of the two split directions.
# This panel can only plot one of them, so compute both and title with the mean plus the
# panel's own value. Titling with the panel value alone (0.0029) sent a reader who opened
# the cited figure to check 0.0031 to a different, more favourable number.
conf, obs, cnt, ece = fit_eval(A, B)
_, _, _, ece_rev = fit_eval(B, A)
ece_mean = (ece + ece_rev) / 2
fig, ax = plt.subplots(figsize=(5.2, 5.2), dpi=150)
ax.plot([0, 1], [0, 1], "--", color="#888", lw=1, label="perfect calibration")
sizes = 30 + 300 * (cnt / cnt.max())
ax.scatter(
conf,
obs,
s=sizes,
c="#1a7f5a",
alpha=0.85,
edgecolor="white",
linewidth=0.8,
zorder=3,
label="held-out bins (size = n)",
)
ax.plot(conf, obs, "-", color="#1a7f5a", lw=1.2, alpha=0.6, zorder=2)
ax.set_xlabel("predicted failure probability")
ax.set_ylabel("observed failure rate")
ax.set_xlim(-0.02, 1.02)
ax.set_ylim(-0.02, 1.02)
ax.set_title(
f"CisFalcon failure-risk calibration\n"
f"held-out ECE = {ece_mean:.4f} (mean of both split directions)\n"
f"this panel: fit-A/eval-B, ECE {ece:.4f}, n = {len(B):,} cross-lab designs",
fontsize=9,
)
ax.legend(loc="upper left", fontsize=8, frameon=False)
ax.grid(True, alpha=0.2)
fig.tight_layout()
fig.savefig(OUT, bbox_inches="tight")
print(f"wrote {OUT} | held-out ECE={ece:.4f} | bins={len(conf)}")