|
import os |
|
import random |
|
import typing as tp |
|
from pathlib import Path |
|
|
|
import numpy as np |
|
import pandas as pd |
|
import typer |
|
from datasets.load import load_dataset |
|
from tqdm import tqdm |
|
|
|
np.random.seed(42) |
|
random.seed(420) |
|
|
|
|
|
def main(viz: bool = False): |
|
|
|
dataset = load_dataset("mnist") |
|
dataset.set_format("np") |
|
X_train = dataset["train"]["image"] |
|
y_train = dataset["train"]["label"].astype(np.uint8) |
|
X_test = dataset["test"]["image"] |
|
y_test = dataset["test"]["label"].astype(np.uint8) |
|
|
|
Xs_train = to_sparse(X_train) |
|
Xs_test = to_sparse(X_test) |
|
|
|
max_length = max(x.shape[0] for x in Xs_train + Xs_test) |
|
|
|
X_train = shuffle_and_pad(Xs_train, max_length, "train").astype(np.uint8) |
|
X_test = shuffle_and_pad(Xs_test, max_length, "test").astype(np.uint8) |
|
|
|
data_path = Path("data") |
|
np.save(data_path / "X_train.npy", X_train) |
|
np.save(data_path / "y_train.npy", y_train) |
|
np.save(data_path / "X_test.npy", X_test) |
|
np.save(data_path / "y_test.npy", y_test) |
|
|
|
|
|
def shuffle_and_pad(Xs, k, name): |
|
|
|
samples = [] |
|
|
|
for x in tqdm(Xs, desc=f"Padding {name}_{k}"): |
|
N = len(x) |
|
|
|
np.random.shuffle(x) |
|
|
|
if N < k: |
|
x = np.pad(x, [(0, k - N), (0, 0)]) |
|
|
|
samples.append(x) |
|
|
|
samples = np.stack(samples, axis=0).astype(np.uint8) |
|
|
|
return samples |
|
|
|
|
|
def to_sparse(X: np.ndarray) -> tp.List[np.ndarray]: |
|
|
|
N = len(X) |
|
w, h = X.shape[1:] |
|
|
|
xx, yy = np.meshgrid(np.arange(w), np.arange(h)[::-1]) |
|
|
|
xx = xx[None] |
|
|
|
xx = np.tile(xx, [N, 1, 1]) |
|
|
|
yy = yy[None] |
|
yy = np.tile(yy, [N, 1, 1]) |
|
|
|
X = np.stack([xx, yy, X], axis=-1) |
|
X = X.reshape(N, -1, 3) |
|
|
|
return [Xi[Xi[:, 2] > 0] for Xi in X] |
|
|
|
|
|
if __name__ == "__main__": |
|
typer.run(main) |
|
|