Datasets:
Tasks:
Image Classification
Modalities:
Image
Formats:
imagefolder
Languages:
English
Size:
< 1K
License:
| from __future__ import annotations | |
| import gzip | |
| import struct | |
| from pathlib import Path | |
| import numpy as np | |
| def load_mnist(path: str | Path, kind: str = "train") -> tuple[np.ndarray, np.ndarray]: | |
| """Load UFO-MNIST IDX gzip files. | |
| Parameters | |
| ---------- | |
| path: | |
| Directory containing `*-images-idx3-ubyte.gz` and `*-labels-idx1-ubyte.gz`. | |
| kind: | |
| Either `train` or `t10k`. | |
| """ | |
| path = Path(path) | |
| labels_path = path / f"{kind}-labels-idx1-ubyte.gz" | |
| images_path = path / f"{kind}-images-idx3-ubyte.gz" | |
| with gzip.open(labels_path, "rb") as handle: | |
| magic, count = struct.unpack(">II", handle.read(8)) | |
| if magic != 2049: | |
| raise ValueError(f"Invalid label file magic number: {magic}") | |
| labels = np.frombuffer(handle.read(), dtype=np.uint8) | |
| if labels.shape[0] != count: | |
| raise ValueError(f"Expected {count} labels, found {labels.shape[0]}") | |
| with gzip.open(images_path, "rb") as handle: | |
| magic, count, rows, cols = struct.unpack(">IIII", handle.read(16)) | |
| if magic != 2051: | |
| raise ValueError(f"Invalid image file magic number: {magic}") | |
| images = np.frombuffer(handle.read(), dtype=np.uint8).reshape(count, rows * cols) | |
| if images.shape[0] != labels.shape[0]: | |
| raise ValueError("Image and label counts differ") | |
| return images, labels | |