File size: 1,752 Bytes
48ff69c
 
8b74b04
 
48ff69c
 
 
 
 
8b74b04
48ff69c
 
 
 
 
 
 
 
 
 
8b74b04
48ff69c
8b74b04
48ff69c
8b74b04
 
48ff69c
8b74b04
48ff69c
8b74b04
 
48ff69c
 
 
 
 
 
 
 
8b74b04
48ff69c
 
 
8b74b04
48ff69c
 
 
 
 
8b74b04
48ff69c
 
 
8b74b04
48ff69c
 
 
 
8b74b04
48ff69c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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)