File size: 5,460 Bytes
ef987bb | 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 | #!/usr/bin/env python3
"""Deterministic single-hidden-layer MLP for the bundled IDX exercise."""
import csv
import json
import math
import random
import struct
from pathlib import Path
ROOT = Path(__file__).resolve().parent
HIDDEN = 16
def read_idx():
raw_images = (ROOT / "train-images-idx3-ubyte").read_bytes()
raw_labels = (ROOT / "train-labels-idx1-ubyte").read_bytes()
magic, count, rows, cols = struct.unpack_from(">IIII", raw_images)
label_magic, label_count = struct.unpack_from(">II", raw_labels)
assert magic == 2051 and label_magic == 2049 and count == label_count
assert rows * cols == 64 and len(raw_images) == 16 + count * 64
assert len(raw_labels) == 8 + count
images = [[pixel / 255 for pixel in raw_images[16 + i * 64:16 + (i + 1) * 64]]
for i in range(count)]
labels = list(raw_labels[8:])
assert set(labels) <= {0, 1}
return images, labels
def init_model():
rng = random.Random(45)
return {
"w1": [[rng.uniform(-0.15, 0.15) for _ in range(64)] for _ in range(HIDDEN)],
"b1": [0.01] * HIDDEN,
"w2": [[rng.uniform(-0.15, 0.15) for _ in range(HIDDEN)] for _ in range(2)],
"b2": [0.0, 0.0],
}
def forward(model, x):
hidden = [max(0.0, sum(a * b for a, b in zip(row, x)) + bias)
for row, bias in zip(model["w1"], model["b1"])]
logits = [sum(a * b for a, b in zip(row, hidden)) + bias
for row, bias in zip(model["w2"], model["b2"])]
return hidden, logits
def train(model, images, labels, train_indices):
rng = random.Random(1)
for _ in range(180):
order = list(train_indices)
rng.shuffle(order)
for index in order:
x, target = images[index], labels[index]
hidden, logits = forward(model, x)
shift = max(logits)
exps = [math.exp(value - shift) for value in logits]
probs = [value / sum(exps) for value in exps]
delta2 = [probs[k] - (1.0 if k == target else 0.0) for k in range(2)]
old_w2 = [row[:] for row in model["w2"]]
delta1 = [sum(delta2[k] * old_w2[k][j] for k in range(2))
if hidden[j] > 0 else 0.0 for j in range(HIDDEN)]
rate = 0.08
for k in range(2):
for j in range(HIDDEN):
model["w2"][k][j] -= rate * delta2[k] * hidden[j]
model["b2"][k] -= rate * delta2[k]
for j in range(HIDDEN):
for i in range(64):
model["w1"][j][i] -= rate * delta1[j] * x[i]
model["b1"][j] -= rate * delta1[j]
def sample_svg(x):
cells = []
for i, value in enumerate(x):
shade = 255 - round(value * 255)
cells.append(f'<rect x="{i % 8 * 8}" y="{i // 8 * 8}" width="8" height="8" fill="rgb({shade},{shade},{shade})"/>')
return '<svg width="128" height="128" viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg">' + ''.join(cells) + '</svg>'
def metrics(pairs):
accuracy = sum(truth == pred for truth, pred in pairs) / len(pairs)
f1s = []
for label in (0, 1):
tp = sum(truth == label and pred == label for truth, pred in pairs)
fp = sum(truth != label and pred == label for truth, pred in pairs)
fn = sum(truth == label and pred != label for truth, pred in pairs)
f1s.append(2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0.0)
return accuracy, sum(f1s) / 2
def main():
images, labels = read_idx()
indices = list(range(len(images)))
random.Random(1).shuffle(indices)
split = int(0.8 * len(indices))
train_indices, validation_indices = indices[:split], indices[split:]
model = init_model()
train(model, images, labels, train_indices)
(ROOT / "model.json").write_text(json.dumps(model, allow_nan=False), encoding="utf-8")
predictions = []
for index in validation_indices:
_, logits = forward(model, images[index])
predictions.append((index, labels[index], int(logits[1] > logits[0])))
with (ROOT / "predictions.csv").open("w", newline="", encoding="utf-8") as handle:
writer = csv.writer(handle)
writer.writerow(["index", "true_label", "predicted_label"])
writer.writerows(predictions)
accuracy, macro_f1 = metrics([(truth, pred) for _, truth, pred in predictions])
previews = ''.join(
f'<figure>{sample_svg(images[index])}<figcaption>index {index}, label {labels[index]}</figcaption></figure>'
for index in indices[:4]
)
report = (
'<!doctype html><html lang="en"><meta charset="utf-8"><title>Tiny MNIST MLP report</title>'
'<style>body{font:16px system-ui;max-width:850px;margin:2rem auto;padding:1rem}'
'.samples{display:flex;flex-wrap:wrap;gap:1rem}figure{margin:0}svg{image-rendering:pixelated;border:1px solid #aaa}</style>'
'<h1>Tiny MNIST MLP classification</h1><p>seed=1; normalized pixels to [0,1]; '
f'train={len(train_indices)}; validation={len(validation_indices)}; 80/20 split.</p>'
'<p>MLP structure: 64 inputs → 16 ReLU hidden units → 2 output logits; '
'cross-entropy, backpropagation, 180 epochs.</p>'
f'<p>accuracy={accuracy:.6f}; macro F1={macro_f1:.6f}</p>'
f'<section class="samples">{previews}</section></html>'
)
(ROOT / "report.html").write_text(report, encoding="utf-8")
if __name__ == "__main__":
main()
|