|
| 1 | +import os |
| 2 | +import gzip |
| 3 | +import shutil |
| 4 | +import urllib.request |
| 5 | +import numpy as np |
| 6 | + |
| 7 | + |
| 8 | +class MNISTDataset: |
| 9 | + @staticmethod |
| 10 | + def load_mnist_img(path): |
| 11 | + try: |
| 12 | + with open(path, "rb") as fi: |
| 13 | + _ = int.from_bytes(fi.read(4), "big") # magic number |
| 14 | + n_images = int.from_bytes(fi.read(4), "big") |
| 15 | + h = int.from_bytes(fi.read(4), "big") |
| 16 | + w = int.from_bytes(fi.read(4), "big") |
| 17 | + buffer = fi.read() |
| 18 | + images = np.frombuffer(buffer, dtype=np.uint8).reshape(n_images, h, w) |
| 19 | + except Exception as e: |
| 20 | + print(f"Could not read MNIST image file at {path}") |
| 21 | + print(e) |
| 22 | + exit(1) |
| 23 | + return images |
| 24 | + |
| 25 | + @staticmethod |
| 26 | + def load_mnist_lbl(path): |
| 27 | + try: |
| 28 | + with open(path, "rb") as fi: |
| 29 | + _ = int.from_bytes(fi.read(4), "big") |
| 30 | + n_labels = int.from_bytes(fi.read(4), "big") |
| 31 | + buffer = fi.read() |
| 32 | + labels = np.frombuffer(buffer, dtype=np.uint8) |
| 33 | + except Exception as e: |
| 34 | + print(f"Could not read MNIST label file at {path}") |
| 35 | + print(e) |
| 36 | + exit(1) |
| 37 | + return labels |
| 38 | + |
| 39 | + @staticmethod |
| 40 | + def _download_and_extract(root): |
| 41 | + """ |
| 42 | + Downloads and extracts the MNIST dataset files if they don't exist. |
| 43 | + """ |
| 44 | + mnist_path = os.path.join(root, "MNIST") |
| 45 | + os.makedirs(mnist_path, exist_ok=True) |
| 46 | + |
| 47 | + urls = [ |
| 48 | + "https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-images-idx3-ubyte.gz", |
| 49 | + "https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz", |
| 50 | + "https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-images-idx3-ubyte.gz", |
| 51 | + "https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-labels-idx1-ubyte.gz", |
| 52 | + ] |
| 53 | + |
| 54 | + for url in urls: |
| 55 | + filename = url.split("/")[-1] |
| 56 | + gz_path = os.path.join(mnist_path, filename) |
| 57 | + uncompressed_path = os.path.join(mnist_path, filename[:-3]) |
| 58 | + |
| 59 | + if not os.path.exists(uncompressed_path): |
| 60 | + print(f"Downloading {url}") |
| 61 | + urllib.request.urlretrieve(url, gz_path) |
| 62 | + |
| 63 | + print(f"Extracting {gz_path}") |
| 64 | + with gzip.open(gz_path, 'rb') as f_in: |
| 65 | + with open(uncompressed_path, 'wb') as f_out: |
| 66 | + shutil.copyfileobj(f_in, f_out) |
| 67 | + os.remove(gz_path) |
| 68 | + |
| 69 | + ''' |
| 70 | + dataset_dir |
| 71 | + ├── MNIST |
| 72 | + ├── train-images.idx3-ubyte (train images file) |
| 73 | + ├── train-labels.idx1-ubyte |
| 74 | + ├── t10k-images.idx3-ubyte (val images file) |
| 75 | + ├── t10k-labels.idx1-ubyte |
| 76 | + ''' |
| 77 | + |
| 78 | + def __init__(self, root, download=True, train=True): |
| 79 | + if download and not os.path.exists(os.path.join(root, "MNIST")): |
| 80 | + self._download_and_extract(root) |
| 81 | + |
| 82 | + if train: |
| 83 | + img_dir = os.path.join(root, "MNIST", "train-images-idx3-ubyte") |
| 84 | + lbl_dir = os.path.join(root, "MNIST", "train-labels-idx1-ubyte") |
| 85 | + else: |
| 86 | + img_dir = os.path.join(root, "MNIST", "t10k-images-idx3-ubyte") |
| 87 | + lbl_dir = os.path.join(root, "MNIST", "t10k-labels-idx1-ubyte") |
| 88 | + |
| 89 | + images = self.load_mnist_img(img_dir) |
| 90 | + labels = self.load_mnist_lbl(lbl_dir) |
| 91 | + |
| 92 | + self.data = [(image, label) for image, label in zip(images, labels)] |
| 93 | + |
| 94 | + def __len__(self): |
| 95 | + return len(self.data) |
| 96 | + |
| 97 | + def __getitem__(self, index): |
| 98 | + return self.data[index] |
0 commit comments