#!/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'') return '' + ''.join(cells) + '' 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'
{sample_svg(images[index])}
index {index}, label {labels[index]}
' for index in indices[:4] ) report = ( 'Tiny MNIST MLP report' '' '

Tiny MNIST MLP classification

seed=1; normalized pixels to [0,1]; ' f'train={len(train_indices)}; validation={len(validation_indices)}; 80/20 split.

' '

MLP structure: 64 inputs → 16 ReLU hidden units → 2 output logits; ' 'cross-entropy, backpropagation, 180 epochs.

' f'

accuracy={accuracy:.6f}; macro F1={macro_f1:.6f}

' f'
{previews}
' ) (ROOT / "report.html").write_text(report, encoding="utf-8") if __name__ == "__main__": main()