|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import urllib.request |
| 4 | +from typing import Tuple |
| 5 | + |
| 6 | +import torch |
| 7 | +from torch import Tensor |
| 8 | +from torch.utils.data import Dataset |
| 9 | + |
| 10 | + |
| 11 | +class MNIST(Dataset): |
| 12 | + """ |
| 13 | + Customized `MNIST <http://yann.lecun.com/exdb/mnist/>`_ dataset for testing Pytorch Lightning |
| 14 | + without the torchvision dependency. |
| 15 | +
|
| 16 | + Part of the code was copied from |
| 17 | + https://github.com/pytorch/vision/blob/build/v0.5.0/torchvision/datasets/mnist.py |
| 18 | +
|
| 19 | + Args: |
| 20 | + root: Root directory of dataset where ``MNIST/processed/training.pt`` |
| 21 | + and ``MNIST/processed/test.pt`` exist. |
| 22 | + train: If ``True``, creates dataset from ``training.pt``, |
| 23 | + otherwise from ``test.pt``. |
| 24 | + normalize: mean and std deviation of the MNIST dataset. |
| 25 | + download: If true, downloads the dataset from the internet and |
| 26 | + puts it in root directory. If dataset is already downloaded, it is not |
| 27 | + downloaded again. |
| 28 | + """ |
| 29 | + |
| 30 | + RESOURCES = ( |
| 31 | + "https://pl-public-data.s3.amazonaws.com/MNIST/processed/training.pt", |
| 32 | + "https://pl-public-data.s3.amazonaws.com/MNIST/processed/test.pt", |
| 33 | + ) |
| 34 | + |
| 35 | + TRAIN_FILE_NAME = 'training.pt' |
| 36 | + TEST_FILE_NAME = 'test.pt' |
| 37 | + |
| 38 | + def __init__(self, root: str, train: bool = True, normalize: tuple = (0.5, 1.0), download: bool = False): |
| 39 | + super(MNIST, self).__init__() |
| 40 | + self.root = root |
| 41 | + self.train = train # training set or test set |
| 42 | + self.normalize = normalize |
| 43 | + |
| 44 | + if download: |
| 45 | + self.download() |
| 46 | + |
| 47 | + if not self._check_exists(): |
| 48 | + raise RuntimeError('Dataset not found.') |
| 49 | + |
| 50 | + data_file = self.TRAIN_FILE_NAME if self.train else self.TEST_FILE_NAME |
| 51 | + self.data, self.targets = torch.load(os.path.join(self.processed_folder, data_file)) |
| 52 | + |
| 53 | + def __getitem__(self, idx: int) -> Tuple[Tensor, int]: |
| 54 | + img = self.data[idx].float().unsqueeze(0) |
| 55 | + target = int(self.targets[idx]) |
| 56 | + |
| 57 | + if self.normalize is not None: |
| 58 | + img = normalize_tensor(img, mean=self.normalize[0], std=self.normalize[1]) |
| 59 | + |
| 60 | + return img, target |
| 61 | + |
| 62 | + def __len__(self) -> int: |
| 63 | + return len(self.data) |
| 64 | + |
| 65 | + @property |
| 66 | + def processed_folder(self) -> str: |
| 67 | + return os.path.join(self.root, 'MNIST', 'processed') |
| 68 | + |
| 69 | + def _check_exists(self) -> bool: |
| 70 | + train_file = os.path.join(self.processed_folder, self.TRAIN_FILE_NAME) |
| 71 | + test_file = os.path.join(self.processed_folder, self.TEST_FILE_NAME) |
| 72 | + return os.path.isfile(train_file) and os.path.isfile(test_file) |
| 73 | + |
| 74 | + def download(self) -> None: |
| 75 | + """Download the MNIST data if it doesn't exist in processed_folder already.""" |
| 76 | + |
| 77 | + if self._check_exists(): |
| 78 | + return |
| 79 | + |
| 80 | + os.makedirs(self.processed_folder, exist_ok=True) |
| 81 | + |
| 82 | + for url in self.RESOURCES: |
| 83 | + logging.info(f'Downloading {url}') |
| 84 | + fpath = os.path.join(self.processed_folder, os.path.basename(url)) |
| 85 | + urllib.request.urlretrieve(url, fpath) |
| 86 | + |
| 87 | + |
| 88 | +def normalize_tensor(tensor: Tensor, mean: float = 0.0, std: float = 1.0) -> Tensor: |
| 89 | + tensor = tensor.clone() |
| 90 | + mean = torch.as_tensor(mean, dtype=tensor.dtype, device=tensor.device) |
| 91 | + std = torch.as_tensor(std, dtype=tensor.dtype, device=tensor.device) |
| 92 | + tensor.sub_(mean).div_(std) |
| 93 | + return tensor |
| 94 | + |
| 95 | + |
| 96 | +class TestingMNIST(MNIST): |
| 97 | + |
| 98 | + def __init__(self, root, train=True, normalize=(0.5, 1.0), download=False, num_samples=8000): |
| 99 | + super().__init__( |
| 100 | + root, |
| 101 | + train=train, |
| 102 | + normalize=normalize, |
| 103 | + download=download |
| 104 | + ) |
| 105 | + # take just a subset of MNIST dataset |
| 106 | + self.data = self.data[:num_samples] |
| 107 | + self.targets = self.targets[:num_samples] |
0 commit comments