Download ex03.py from perrabyte/horizonwalker: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/datasets/perrabyte/horizonwalker/resolve/main/ex03.py
- Command line
-
hf download hf://datasets/perrabyte/horizonwalker/ex03.py
-
curl -L -o ex03.py https://huggingface.co/datasets/perrabyte/horizonwalker/resolve/main/ex03.py
10.5 kB
| """Gentle untangling: walk misclassified MNIST samples across the decision | |
| boundary incrementally, along a monotone-margin path. 784-dim, c00.py geometry. | |
| For each misclassified x0 (true label y): | |
| - m(x) = z2[y] - max_{k != y} z2[k] (negative when misclassified) | |
| - step x <- clip(x + eta * grad_m / ||grad_m||, 0, 1) | |
| - stop at m > eps, R_max from x0, or max_steps | |
| Report the path; compare to a single linearized "flip" (one jump). | |
| """ | |
| import numpy as np, time, collections | |
| # ββ 784-dim MNIST loader (same fallback chain) ββββββββββββββββββββ | |
| def load_mnist_784(): | |
| try: | |
| from keras.datasets import mnist | |
| (Xtr, ytr), (Xte, yte) = mnist.load_data() | |
| return (Xtr.reshape(-1,784).astype(np.float32)/255.0, ytr.astype(np.int64), | |
| Xte.reshape(-1,784).astype(np.float32)/255.0, yte.astype(np.int64), "keras") | |
| except Exception: pass | |
| try: | |
| import torchvision | |
| dtr = torchvision.datasets.MNIST('../mnist_data', train=True, download=True) | |
| dte = torchvision.datasets.MNIST('../mnist_data', train=False, download=True) | |
| return (dtr.data.numpy().reshape(-1,784).astype(np.float32)/255.0, dtr.targets.numpy().astype(np.int64), | |
| dte.data.numpy().reshape(-1,784).astype(np.float32)/255.0, dte.targets.numpy().astype(np.int64), "torchvision") | |
| except Exception: pass | |
| try: | |
| from sklearn.datasets import fetch_openml | |
| X, y = fetch_openml('mnist_784', version=1, return_X_y=True, as_frame=False) | |
| X = X.astype(np.float32)/255.0; y = y.astype(np.int64) | |
| return X[:60000], y[:60000], X[60000:], y[60000:], "sklearn-openml" | |
| except Exception as e: | |
| print(f"[loader] openml failed: {e}") | |
| raise RuntimeError("no MNIST available") | |
| # ββ c00.py MLP: same geometry, same four i.i.d. lrs βββββββββββββββ | |
| class MLP: | |
| def __init__(self, d_in, d_hid, d_out, seed=0): | |
| rng = np.random.default_rng(seed) | |
| self.W1 = (rng.standard_normal((d_in, d_hid)) * 0.01).astype(np.float32) | |
| self.b1 = np.zeros((1, d_hid), np.float32) | |
| self.W2 = (rng.standard_normal((d_hid, d_out)) * 0.01).astype(np.float32) | |
| self.b2 = np.zeros((1, d_out), np.float32) | |
| self.lr = rng.random(4).astype(np.float32) | |
| def fwd(self, X): | |
| z1 = X @ self.W1 + self.b1 | |
| a1 = np.maximum(0, z1) | |
| z2 = a1 @ self.W2 + self.b2 | |
| return z1, a1, z2 | |
| def predict(self, X): | |
| return self.fwd(X)[2].argmax(axis=1) | |
| def update(self, X, Y1h): | |
| z1, a1, z2 = self.fwd(X) | |
| e = np.exp(z2 - z2.max(axis=1, keepdims=True)) | |
| yp = e / e.sum(axis=1, keepdims=True) | |
| B = X.shape[0] | |
| dz2 = (yp - Y1h) / B | |
| dW2 = a1.T @ dz2 | |
| db2 = dz2.sum(axis=0, keepdims=True) | |
| dz1 = (dz2 @ self.W2.T) * (z1 > 0) | |
| dW1 = X.T @ dz1 | |
| db1 = dz1.sum(axis=0, keepdims=True) | |
| lr = self.lr | |
| self.W1 -= lr[0]*dW1; self.b1 -= lr[1]*db1 | |
| self.W2 -= lr[2]*dW2; self.b2 -= lr[3]*db2 | |
| # ββ margin and its input-space gradient βββββββββββββββββββββββββββ | |
| def margin_grad(f, X, y): | |
| """X: (B,D), y: (B,). Returns m: (B,), dX: (B,D).""" | |
| z1, a1, z2 = f.fwd(X) | |
| B = X.shape[0]; ar = np.arange(B) | |
| z2c = z2.copy(); z2c[ar, y] = -np.inf | |
| k = z2c.argmax(axis=1) | |
| m = z2[ar, y] - z2[ar, k] | |
| g = np.zeros_like(z2); g[ar, y] = 1.0; g[ar, k] = -1.0 | |
| da1 = g @ f.W2.T | |
| dz1 = da1 * (z1 > 0) | |
| dX = dz1 @ f.W1.T | |
| return m, dX | |
| # ββ incremental path ββββββββββββββββββββββββββββββββββββββββββββββ | |
| def walk(f, x0, y, step=0.05, R_max=3.0, max_steps=600, eps=0.02): | |
| x = x0.astype(np.float32).copy() | |
| path = [x.copy()]; margins = [] | |
| m, dX = margin_grad(f, x[None], np.array([y])) | |
| m = float(m[0]); margins.append(m) | |
| if m >= 0: | |
| return path, margins, 'already' | |
| for _ in range(max_steps): | |
| g = dX[0] / (np.linalg.norm(dX[0]) + 1e-12) | |
| x_new = np.clip(x + step * g, 0.0, 1.0) | |
| if np.linalg.norm(x_new - x0) > R_max: | |
| return path, margins, 'R_max' | |
| x = x_new; path.append(x.copy()) | |
| m, dX = margin_grad(f, x[None], np.array([y])) | |
| m = float(m[0]); margins.append(m) | |
| if m > eps: | |
| return path, margins, 'crossed' | |
| return path, margins, 'max_steps' | |
| def path_metrics(path, margins, x0): | |
| P = np.array(path) | |
| if len(P) < 2: | |
| return dict(steps=0, total=0.0, straight=0.0, straightness=0.0, | |
| max_step=0.0, max_jump=0.0, monotone=1.0, n_near=0) | |
| d = np.diff(P, axis=0) | |
| L2s = np.linalg.norm(d, axis=1) | |
| total = float(L2s.sum()) | |
| straight = float(np.linalg.norm(P[-1] - P[0])) | |
| dm = np.diff(margins) | |
| return dict(steps=len(P)-1, total=total, straight=straight, | |
| straightness=straight/(total+1e-12), | |
| max_step=float(L2s.max()), | |
| max_jump=float(np.abs(dm).max()) if len(dm) else 0.0, | |
| monotone=float(np.mean(dm >= -1e-6)) if len(dm) else 1.0, | |
| n_near=int(sum(1 for m in margins if abs(m) < 0.1))) | |
| # ββ main ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def main(): | |
| np.random.seed(0) | |
| X_tr, y_tr, X_te, y_te, src = load_mnist_784() | |
| print(f"source : {src}") | |
| print(f"train shape : {X_tr.shape} test: {X_te.shape}") | |
| print(f"topology : {X_tr.shape[1]} -> 100 -> 10 (c00.py)") | |
| print(f"minibatch : 100") | |
| Y_tr = np.eye(10, dtype=np.float32)[y_tr] | |
| f = MLP(784, 100, 10, seed=0) | |
| print(f"lr vector : {np.round(f.lr, 3)} (4 i.i.d. U(0,1))") | |
| print() | |
| EPOCHS, B = 100, 100 | |
| n = len(X_tr); spe = n // B | |
| print(f"{'epoch':>5} | {'test_acc':>8} | {'misclassified':>13} | {'time':>5}") | |
| print("-" * 47) | |
| for ep in range(1, EPOCHS+1): | |
| t0 = time.time() | |
| order = np.random.permutation(n) | |
| for b in range(spe): | |
| idx = order[b*B:(b+1)*B] | |
| f.update(X_tr[idx] + 0.01 * np.random.randn(100,784), Y_tr[idx]) | |
| pred = f.predict(X_te) | |
| acc = float(np.mean(pred == y_te)) | |
| nm = int(np.sum(pred != y_te)) | |
| print(f"{ep:5d} | {acc:8.4f} | {nm:13d} | {time.time()-t0:4.1f}s") | |
| pred = f.predict(X_te) | |
| wrong_idx = np.where(pred != y_te)[0] | |
| print(f"\nmisclassified test samples: {len(wrong_idx)} / {len(X_te)} " | |
| f"({100*len(wrong_idx)/len(X_te):.1f}%)") | |
| np.random.shuffle(wrong_idx) | |
| SAMPLE_N = min(300, len(wrong_idx)) | |
| test_idx = wrong_idx[:SAMPLE_N] | |
| results = [] | |
| t0 = time.time() | |
| for ii, i in enumerate(test_idx): | |
| path, margins, status = walk(f, X_te[i], int(y_te[i]), | |
| step=0.05, R_max=3.0, max_steps=600, eps=0.02) | |
| met = path_metrics(path, margins, X_te[i]) | |
| met.update(idx=int(i), true=int(y_te[i]), status=status, | |
| m0=margins[0], m1=margins[-1]) | |
| results.append(met) | |
| print(f"walked {len(test_idx)} samples in {time.time()-t0:.1f}s") | |
| stat = collections.Counter(r['status'] for r in results) | |
| print("\n=== walk status ===") | |
| for k in ('crossed', 'R_max', 'max_steps', 'already'): | |
| if stat.get(k): | |
| print(f" {k:>9}: {stat[k]:>4} ({100*stat[k]/len(results):.0f}%)") | |
| crossed = [r for r in results if r['status'] == 'crossed'] | |
| if crossed: | |
| steps = np.array([r['steps'] for r in crossed]) | |
| total = np.array([r['total'] for r in crossed]) | |
| straight = np.array([r['straightness'] for r in crossed]) | |
| mjump = np.array([r['max_jump'] for r in crossed]) | |
| mono = np.array([r['monotone'] for r in crossed]) | |
| near = np.array([r['n_near'] for r in crossed]) | |
| print("\n=== crossed: gentleness metrics (n=%d) ===" % len(crossed)) | |
| print(f" steps to cross : mean {steps.mean():5.1f} median {np.median(steps):5.0f} max {steps.max():5d}") | |
| print(f" total displacement: mean {total.mean():5.2f} median {np.median(total):5.2f} max {total.max():5.2f}") | |
| print(f" straightness : mean {straight.mean():5.2f} median {np.median(straight):5.2f}") | |
| print(f" max |dmargin|/step: mean {mjump.mean():5.3f} max {mjump.max():5.3f}") | |
| print(f" monotone fraction : mean {mono.mean():5.2f} (1.0 = every step raised margin)") | |
| print(f" steps near |m|<0.1: mean {near.mean():5.1f}") | |
| print("\n=== example incremental paths (margin per step) ===") | |
| for r in crossed[:4]: | |
| i = r['idx'] | |
| path, margins, status = walk(f, X_te[i], int(y_te[i]), | |
| step=0.05, R_max=3.0, max_steps=600, eps=0.02) | |
| traj = margins[:18] | |
| print(f"\nsample {i:>4} true={r['true']} {status} " | |
| f"steps={len(margins)-1} total={r['total']:.2f} straightness={r['straightness']:.2f}") | |
| print(" m: " + " ".join(f"{m:+.2f}" for m in traj) | |
| + (" ..." if len(margins) > 18 else "")) | |
| dm = np.diff(margins) | |
| if len(dm): | |
| print(" Ξ: " + " ".join(f"{d:+.2f}" for d in dm[:17]) | |
| + (" ..." if len(dm) > 17 else "")) | |
| print("\n=== 'flip' (1 jump) vs 'path' (many steps) ===") | |
| for r in crossed[:2]: | |
| i = r['idx']; y = int(y_te[i]); x0 = X_te[i] | |
| m0, dX0 = margin_grad(f, x0[None], np.array([y])) | |
| m0 = float(m0[0]); g = dX0[0] | |
| gnorm2 = float(np.dot(g, g)) + 1e-12 | |
| # single linearized jump: m(x + s g) β m0 + s||g||Β² = 0 | |
| s_flip = -m0 / gnorm2 # m0 < 0 β s_flip > 0 | |
| x_flip = np.clip(x0 + s_flip * g, 0.0, 1.0) | |
| m_flip, _ = margin_grad(f, x_flip[None], np.array([y])) | |
| m_flip = float(m_flip[0]) | |
| tag = "" | |
| if m_flip < 0: tag = " (undershoot: still wrong side)" | |
| elif np.linalg.norm(x_flip - x0) > 1.5: tag = " (overshoot: large jump)" | |
| print(f" sample {i:>4} true={y}") | |
| print(f" start margin : {m0:+.4f}") | |
| print(f" FLIP (1 jump) : Ξx={np.linalg.norm(x_flip-x0):.3f} β margin {m_flip:+.4f}{tag}") | |
| print(f" PATH ({r['steps']} steps) : total Ξx={r['total']:.3f}, " | |
| f"straightness={r['straightness']:.2f}, monotone={r['monotone']:.2f}") | |
| if __name__ == "__main__": | |
| main() | |