File size: 2,667 Bytes
0832232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Inspection outputs for generated datasets."""

from __future__ import annotations

import json
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw

from .labels import CLASS_NAMES


def inspect_dataset(dataset_dir: Path, samples_per_class: int = 16) -> dict[str, object]:
    npz_path = dataset_dir / "ufo_mnist_28x28.npz"
    data = np.load(npz_path)
    summary = {
        "train_images_shape": list(data["train_images"].shape),
        "test_images_shape": list(data["test_images"].shape),
        "train_dtype": str(data["train_images"].dtype),
        "test_dtype": str(data["test_images"].dtype),
        "train_counts": _counts(data["train_labels"]),
        "test_counts": _counts(data["test_labels"]),
        "nearest_centroid_accuracy": _nearest_centroid_accuracy(data),
    }
    (dataset_dir / "summary.json").write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    _contact_sheet(data["train_images"], data["train_labels"], dataset_dir / "contact_sheet_train.png", samples_per_class)
    _contact_sheet(data["test_images"], data["test_labels"], dataset_dir / "contact_sheet_test.png", samples_per_class)
    return summary


def _counts(labels: np.ndarray) -> dict[str, int]:
    return {CLASS_NAMES[index]: int((labels == index).sum()) for index in range(len(CLASS_NAMES))}


def _nearest_centroid_accuracy(data: np.lib.npyio.NpzFile) -> float:
    train_x = data["train_images"].reshape(data["train_images"].shape[0], -1).astype(np.float32)
    test_x = data["test_images"].reshape(data["test_images"].shape[0], -1).astype(np.float32)
    train_y = data["train_labels"]
    test_y = data["test_labels"]
    centroids = np.stack([train_x[train_y == label].mean(axis=0) for label in range(len(CLASS_NAMES))])
    dists = ((test_x[:, None, :] - centroids[None, :, :]) ** 2).mean(axis=2)
    pred = dists.argmin(axis=1)
    return float((pred == test_y).mean())


def _contact_sheet(images: np.ndarray, labels: np.ndarray, output: Path, samples_per_class: int) -> None:
    cell = 34
    label_h = 14
    cols = samples_per_class
    rows = len(CLASS_NAMES)
    sheet = Image.new("L", (cols * cell, rows * (cell + label_h)), 20)
    draw = ImageDraw.Draw(sheet)
    for label, name in enumerate(CLASS_NAMES):
        indices = np.where(labels == label)[0][:samples_per_class]
        y0 = label * (cell + label_h)
        draw.text((2, y0), f"{label} {name}", fill=230)
        for col, idx in enumerate(indices):
            tile = Image.fromarray(images[idx]).resize((28, 28), Image.Resampling.NEAREST)
            sheet.paste(tile, (col * cell + 3, y0 + label_h + 3))
    sheet.save(output)