Repository navigation
Expand file tree
/
Copy pathrun_symbols.py
More file actions
141 lines (128 loc) · 4.79 KB
/
Copy pathrun_symbols.py
File metadata and controls
141 lines (128 loc) · 4.79 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
"""Synthetic vector-symbol evaluation + GD&T topological invariant check.
Experiment A: WiSARD (same K=160/n=10 paper hyperparameters) trained on jittered
clean vector symbols (10 classes), tested on held-out jittered variants.
Experiment B: Zhang-Suen skeletonization + topological invariants (Sec. 9.2)
on clean symbols, compared against the paper's Table 9.4 invariant signatures.
"""
import json
import time
import numpy as np
from jesse import ( # noqa: I001
WisardClassifier,
is_complex_invariant,
make_tuple_indices,
skeleton_invariants,
zhang_suen,
)
from symbols import NAMES, make_dataset
def main(out_path: str = "symbols_results.json"):
"""Run the synthetic symbol evaluation (Experiment A) + GD&T invariant check (B)."""
tidx = make_tuple_indices(28, 28, seed=42)
Xtr, ytr, Xte, yte = make_dataset(n_train=400, n_test=100, seed=7)
print(f"symbols: train {Xtr.shape} test {Xte.shape}", flush=True)
clf = WisardClassifier(10, tuple_idx=tidx)
t0 = time.perf_counter()
clf.fit(Xtr, ytr)
t_train = time.perf_counter() - t0
pred = clf.predict_sum(Xte)
acc = float((pred == yte).mean())
pred_lo = clf.predict_logodds(Xte, alpha=0.1)
acc_lo = float((pred_lo == yte).mean())
print(
f"symbols WiSARD: sum acc={acc * 100:.2f}% "
f"logodds(a=0.1) acc={acc_lo * 100:.2f}% train={t_train:.3f}s",
flush=True,
)
cm = np.zeros((10, 10), int)
for t, p in zip(yte, pred):
cm[t, p] += 1
print("confusion (rows=true):")
print(" " + " ".join(f"{n[:5]:>5}" for n in NAMES))
for i, n in enumerate(NAMES):
print(f"{n[:5]:>5} " + " ".join(f"{v:>5}" for v in cm[i]))
# Experiment B: topological invariants vs paper Table 9.4 (Sec. 9.2).
# Uses clean 1px primitives at 112x112 (thick raster strokes produce skeleton
# spurs that are renderer artifacts, not method failures).
print("\nTopological invariants (clean 1px glyphs, Sec. 9.2):")
def bresenham_circle(n, cx, cy, r):
img = np.zeros((n, n), np.uint8)
x, y, d = r, 0, 1 - r
while y <= x:
for px, py in [
(cx + x, cy + y),
(cx - x, cy + y),
(cx + x, cy - y),
(cx - x, cy - y),
(cx + y, cy + x),
(cx - y, cy + x),
(cx + y, cy - x),
(cx - y, cy - x),
]:
if 0 <= px < n and 0 <= py < n:
img[py, px] = 1
y += 1
if d <= 0:
d += 2 * y + 1
else:
x -= 1
d += 2 * (y - x) + 1
return img
_t = np.zeros((112, 112), np.uint8)
_t[30, 20:92] = 1
_t[30:92, 56] = 1
_l = np.zeros((112, 112), np.uint8)
_l[56, 20:92] = 1
_p = np.zeros((112, 112), np.uint8)
_p[20:92, 40] = 1
_p[20:92, 72] = 1
checks = [
(
"circularity (O)",
bresenham_circle(112, 56, 56, 30),
dict(endpoints=0, t_junctions=0, x_junctions=0, holes=1),
),
(
"concentricity",
np.maximum(bresenham_circle(112, 56, 56, 30), bresenham_circle(112, 56, 56, 18)),
dict(endpoints=0, t_junctions=0, x_junctions=0, holes=2),
),
("perpendicularity (T)", _t, dict(endpoints=3, t_junctions=1, holes=0)),
("straightness (-)", _l, dict(endpoints=2, t_junctions=0, holes=0)),
("parallelism (||)", _p, dict(endpoints=4, t_junctions=0, holes=0)),
]
inv_results = {}
complex_rows = []
allok = True
for label, img, expect in checks:
inv = skeleton_invariants(zhang_suen(img))
got = {k: inv[k] for k in expect}
ok = got == expect
allok &= ok
inv_results[label] = inv
# Flag complex rows: exceeded Table 9.4 simple envelope, or compound glyphs
if is_complex_invariant(inv):
complex_rows.append({"label": label, "inv": inv})
print(
f" {label:22s} {got} expected {expect} {'OK' if ok else 'MISMATCH'} "
"[COMPLEX — gd_complex_row]"
)
else:
print(f" {label:22s} {got} expected {expect} {'OK' if ok else 'MISMATCH'}")
print(" all match paper Table 9.4:", allok)
if complex_rows:
print(f" {len(complex_rows)} complex row(s) — see gd_complex_row review items above")
with open(out_path, "w") as f:
json.dump(
{
"acc": acc,
"train_time_s": t_train,
"confusion": cm.tolist(),
"invariants": inv_results,
"complex_rows": complex_rows, # flagged for review with gd_complex_row kind
},
f,
indent=2,
)
print(f"saved {out_path}")
if __name__ == "__main__":
main()