Download task_029/solution/code/solve.py from Lego-X/UXInteract: direct link, hf CLI and curl.
- Browser
- Download file 5.46 kB
-
https://huggingface.co/datasets/Lego-X/UXInteract/resolve/main/task_029/solution/code/solve.py
- Command line
-
hf download hf://datasets/Lego-X/UXInteract/task_029/solution/code/solve.py
-
curl -L -o solve.py https://huggingface.co/datasets/Lego-X/UXInteract/resolve/main/task_029/solution/code/solve.py
5.46 kB
| #!/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() | |