2020-10-13 11:18:07 +00:00
|
|
|
# Copyright The PyTorch Lightning team.
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
2020-03-30 22:25:37 +00:00
|
|
|
import logging
|
|
|
|
import os
|
2020-07-27 23:07:09 +00:00
|
|
|
import random
|
|
|
|
import time
|
2020-08-06 14:58:51 +00:00
|
|
|
import urllib.request
|
2021-01-15 08:01:57 +00:00
|
|
|
from typing import Optional, Sequence, Tuple
|
2020-03-30 22:25:37 +00:00
|
|
|
|
|
|
|
import torch
|
|
|
|
from torch import Tensor
|
|
|
|
from torch.utils.data import Dataset
|
|
|
|
|
|
|
|
|
|
|
|
class MNIST(Dataset):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Customized `MNIST <http://yann.lecun.com/exdb/mnist/>`_ dataset for testing Pytorch Lightning without the
|
|
|
|
torchvision dependency.
|
2020-03-30 22:25:37 +00:00
|
|
|
|
|
|
|
Part of the code was copied from
|
|
|
|
https://github.com/pytorch/vision/blob/build/v0.5.0/torchvision/datasets/mnist.py
|
|
|
|
|
|
|
|
Args:
|
|
|
|
root: Root directory of dataset where ``MNIST/processed/training.pt``
|
|
|
|
and ``MNIST/processed/test.pt`` exist.
|
|
|
|
train: If ``True``, creates dataset from ``training.pt``,
|
|
|
|
otherwise from ``test.pt``.
|
|
|
|
normalize: mean and std deviation of the MNIST dataset.
|
|
|
|
download: If true, downloads the dataset from the internet and
|
|
|
|
puts it in root directory. If dataset is already downloaded, it is not
|
|
|
|
downloaded again.
|
2020-04-02 16:28:44 +00:00
|
|
|
|
|
|
|
Examples:
|
2021-03-20 18:58:59 +00:00
|
|
|
>>> dataset = MNIST(".", download=True)
|
2020-04-02 16:28:44 +00:00
|
|
|
>>> len(dataset)
|
|
|
|
60000
|
|
|
|
>>> torch.bincount(dataset.targets)
|
|
|
|
tensor([5923, 6742, 5958, 6131, 5842, 5421, 5918, 6265, 5851, 5949])
|
2020-03-30 22:25:37 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
RESOURCES = (
|
|
|
|
"https://pl-public-data.s3.amazonaws.com/MNIST/processed/training.pt",
|
|
|
|
"https://pl-public-data.s3.amazonaws.com/MNIST/processed/test.pt",
|
|
|
|
)
|
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
TRAIN_FILE_NAME = "training.pt"
|
|
|
|
TEST_FILE_NAME = "test.pt"
|
|
|
|
cache_folder_name = "complete"
|
2020-03-30 22:25:37 +00:00
|
|
|
|
2020-12-17 11:03:45 +00:00
|
|
|
def __init__(
|
2021-07-26 11:37:35 +00:00
|
|
|
self, root: str, train: bool = True, normalize: tuple = (0.1307, 0.3081), download: bool = True, **kwargs
|
2020-12-17 11:03:45 +00:00
|
|
|
):
|
2020-04-02 16:28:44 +00:00
|
|
|
super().__init__()
|
2020-03-30 22:25:37 +00:00
|
|
|
self.root = root
|
|
|
|
self.train = train # training set or test set
|
|
|
|
self.normalize = normalize
|
|
|
|
|
2020-04-02 16:28:44 +00:00
|
|
|
self.prepare_data(download)
|
2020-03-30 22:25:37 +00:00
|
|
|
|
|
|
|
data_file = self.TRAIN_FILE_NAME if self.train else self.TEST_FILE_NAME
|
2021-02-18 03:35:38 +00:00
|
|
|
self.data, self.targets = self._try_load(os.path.join(self.cached_folder_path, data_file))
|
2020-03-30 22:25:37 +00:00
|
|
|
|
|
|
|
def __getitem__(self, idx: int) -> Tuple[Tensor, int]:
|
|
|
|
img = self.data[idx].float().unsqueeze(0)
|
|
|
|
target = int(self.targets[idx])
|
|
|
|
|
2021-02-18 03:35:38 +00:00
|
|
|
if self.normalize is not None and len(self.normalize) == 2:
|
|
|
|
img = self.normalize_tensor(img, *self.normalize)
|
2020-03-30 22:25:37 +00:00
|
|
|
|
|
|
|
return img, target
|
|
|
|
|
|
|
|
def __len__(self) -> int:
|
|
|
|
return len(self.data)
|
|
|
|
|
|
|
|
@property
|
2020-04-02 16:28:44 +00:00
|
|
|
def cached_folder_path(self) -> str:
|
2021-07-26 11:37:35 +00:00
|
|
|
return os.path.join(self.root, "MNIST", self.cache_folder_name)
|
2020-03-30 22:25:37 +00:00
|
|
|
|
2020-04-02 16:28:44 +00:00
|
|
|
def _check_exists(self, data_folder: str) -> bool:
|
|
|
|
existing = True
|
|
|
|
for fname in (self.TRAIN_FILE_NAME, self.TEST_FILE_NAME):
|
|
|
|
existing = existing and os.path.isfile(os.path.join(data_folder, fname))
|
|
|
|
return existing
|
2020-03-30 22:25:37 +00:00
|
|
|
|
2021-02-18 03:35:38 +00:00
|
|
|
def prepare_data(self, download: bool = True):
|
|
|
|
if download and not self._check_exists(self.cached_folder_path):
|
2020-04-02 16:28:44 +00:00
|
|
|
self._download(self.cached_folder_path)
|
2021-02-18 03:35:38 +00:00
|
|
|
if not self._check_exists(self.cached_folder_path):
|
2021-07-26 11:37:35 +00:00
|
|
|
raise RuntimeError("Dataset not found.")
|
2020-04-02 16:28:44 +00:00
|
|
|
|
|
|
|
def _download(self, data_folder: str) -> None:
|
2021-06-14 16:16:42 +00:00
|
|
|
os.makedirs(data_folder, exist_ok=True)
|
2020-03-30 22:25:37 +00:00
|
|
|
for url in self.RESOURCES:
|
2021-07-26 11:37:35 +00:00
|
|
|
logging.info(f"Downloading {url}")
|
2020-04-02 16:28:44 +00:00
|
|
|
fpath = os.path.join(data_folder, os.path.basename(url))
|
2020-03-30 22:25:37 +00:00
|
|
|
urllib.request.urlretrieve(url, fpath)
|
|
|
|
|
2021-02-18 03:35:38 +00:00
|
|
|
@staticmethod
|
2021-07-26 11:37:35 +00:00
|
|
|
def _try_load(path_data, trials: int = 30, delta: float = 1.0):
|
2021-02-18 03:35:38 +00:00
|
|
|
"""Resolving loading from the same time from multiple concurrent processes."""
|
|
|
|
res, exception = None, None
|
|
|
|
assert trials, "at least some trial has to be set"
|
2021-07-26 11:37:35 +00:00
|
|
|
assert os.path.isfile(path_data), f"missing file: {path_data}"
|
2021-02-18 03:35:38 +00:00
|
|
|
for _ in range(trials):
|
|
|
|
try:
|
|
|
|
res = torch.load(path_data)
|
|
|
|
# todo: specify the possible exception
|
|
|
|
except Exception as e:
|
|
|
|
exception = e
|
|
|
|
time.sleep(delta * random.random())
|
|
|
|
else:
|
|
|
|
break
|
|
|
|
if exception is not None:
|
|
|
|
# raise the caught exception
|
|
|
|
raise exception
|
|
|
|
return res
|
2020-03-30 22:25:37 +00:00
|
|
|
|
2021-02-18 03:35:38 +00:00
|
|
|
@staticmethod
|
|
|
|
def normalize_tensor(tensor: Tensor, mean: float = 0.0, std: float = 1.0) -> Tensor:
|
|
|
|
mean = torch.as_tensor(mean, dtype=tensor.dtype, device=tensor.device)
|
|
|
|
std = torch.as_tensor(std, dtype=tensor.dtype, device=tensor.device)
|
|
|
|
return tensor.sub(mean).div(std)
|
2020-03-30 22:25:37 +00:00
|
|
|
|
|
|
|
|
2020-04-16 02:16:40 +00:00
|
|
|
class TrialMNIST(MNIST):
|
2021-09-06 12:49:09 +00:00
|
|
|
"""Constrained MNIST dataset.
|
2020-04-02 16:28:44 +00:00
|
|
|
|
|
|
|
Args:
|
|
|
|
num_samples: number of examples per selected class/digit
|
|
|
|
digits: list selected MNIST digits/classes
|
2021-02-18 03:35:38 +00:00
|
|
|
kwargs: Same as MNIST
|
2020-04-02 16:28:44 +00:00
|
|
|
|
|
|
|
Examples:
|
2021-03-20 18:58:59 +00:00
|
|
|
>>> dataset = TrialMNIST(".", download=True)
|
2020-04-02 16:28:44 +00:00
|
|
|
>>> len(dataset)
|
|
|
|
300
|
|
|
|
>>> sorted(set([d.item() for d in dataset.targets]))
|
|
|
|
[0, 1, 2]
|
|
|
|
>>> torch.bincount(dataset.targets)
|
|
|
|
tensor([100, 100, 100])
|
|
|
|
"""
|
|
|
|
|
2021-03-20 18:58:59 +00:00
|
|
|
def __init__(self, root: str, num_samples: int = 100, digits: Optional[Sequence] = (0, 1, 2), **kwargs):
|
2020-04-02 16:28:44 +00:00
|
|
|
# number of examples per class
|
|
|
|
self.num_samples = num_samples
|
|
|
|
# take just a subset of MNIST dataset
|
2021-02-18 03:35:38 +00:00
|
|
|
self.digits = sorted(digits) if digits else list(range(10))
|
2020-04-02 16:28:44 +00:00
|
|
|
|
2021-02-18 03:35:38 +00:00
|
|
|
self.cache_folder_name = f"digits-{'-'.join(str(d) for d in self.digits)}_nb-{self.num_samples}"
|
2020-03-30 22:25:37 +00:00
|
|
|
|
2021-03-20 18:58:59 +00:00
|
|
|
super().__init__(root, normalize=(0.5, 1.0), **kwargs)
|
2020-04-02 16:28:44 +00:00
|
|
|
|
|
|
|
@staticmethod
|
2021-02-06 13:22:10 +00:00
|
|
|
def _prepare_subset(full_data: torch.Tensor, full_targets: torch.Tensor, num_samples: int, digits: Sequence):
|
2020-04-02 16:28:44 +00:00
|
|
|
classes = {d: 0 for d in digits}
|
|
|
|
indexes = []
|
|
|
|
for idx, target in enumerate(full_targets):
|
|
|
|
label = target.item()
|
2021-07-26 11:37:35 +00:00
|
|
|
if classes.get(label, float("inf")) >= num_samples:
|
2020-04-02 16:28:44 +00:00
|
|
|
continue
|
|
|
|
indexes.append(idx)
|
|
|
|
classes[label] += 1
|
|
|
|
if all(classes[k] >= num_samples for k in classes):
|
|
|
|
break
|
|
|
|
data = full_data[indexes]
|
|
|
|
targets = full_targets[indexes]
|
|
|
|
return data, targets
|
|
|
|
|
2021-02-18 03:35:38 +00:00
|
|
|
def _download(self, data_folder: str) -> None:
|
|
|
|
super()._download(data_folder)
|
2020-04-02 16:28:44 +00:00
|
|
|
for fname in (self.TRAIN_FILE_NAME, self.TEST_FILE_NAME):
|
2021-02-18 03:35:38 +00:00
|
|
|
path_fname = os.path.join(self.cached_folder_path, fname)
|
2021-07-26 11:37:35 +00:00
|
|
|
assert os.path.isfile(path_fname), f"Missing cached file: {path_fname}"
|
2021-02-18 03:35:38 +00:00
|
|
|
data, targets = self._try_load(path_fname)
|
2020-04-02 16:28:44 +00:00
|
|
|
data, targets = self._prepare_subset(data, targets, self.num_samples, self.digits)
|
|
|
|
torch.save((data, targets), os.path.join(self.cached_folder_path, fname))
|
2020-06-15 21:05:58 +00:00
|
|
|
|
|
|
|
|
|
|
|
class AverageDataset(Dataset):
|
|
|
|
def __init__(self, dataset_len=300, sequence_len=100):
|
|
|
|
self.dataset_len = dataset_len
|
|
|
|
self.sequence_len = sequence_len
|
|
|
|
self.input_seq = torch.randn(dataset_len, sequence_len, 10)
|
|
|
|
top, bottom = self.input_seq.chunk(2, -1)
|
|
|
|
self.output_seq = top + bottom.roll(shifts=1, dims=-1)
|
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return self.dataset_len
|
|
|
|
|
|
|
|
def __getitem__(self, item):
|
|
|
|
return self.input_seq[item], self.output_seq[item]
|
2021-02-08 10:52:02 +00:00
|
|
|
|
|
|
|
|
|
|
|
class SklearnDataset(Dataset):
|
|
|
|
def __init__(self, x, y, x_type, y_type):
|
|
|
|
self.x = x
|
|
|
|
self.y = y
|
|
|
|
self._x_type = x_type
|
|
|
|
self._y_type = y_type
|
|
|
|
|
|
|
|
def __getitem__(self, idx):
|
|
|
|
return torch.tensor(self.x[idx], dtype=self._x_type), torch.tensor(self.y[idx], dtype=self._y_type)
|
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return len(self.y)
|