Image Datasets

Image datasets

ImageDataset base class


source

ImageDataset

 ImageDataset ()

Base class for image datasets providing visualization of (image, label) samples


source

ImageDataset.show_idx

 ImageDataset.show_idx (index:int)

display image from data point index of a image dataset

Type Details
index int Index of the (image,label) sample to visualize

source

ImageDataset.show_grid

 ImageDataset.show_grid (imgs:List[torch.Tensor], save_path=None)

display list of mnist-like images (C,H,W)

Type Default Details
imgs typing.List[torch.Tensor] python list of images dim (C,H,W)
save_path NoneType None path where image can be saved

source

ImageDataset.show_grid

 ImageDataset.show_grid (imgs:List[torch.Tensor], save_path=None)

display list of mnist-like images (C,H,W)

Type Default Details
imgs typing.List[torch.Tensor] python list of images dim (C,H,W)
save_path NoneType None path where image can be saved

MNIST

MNIST dataset


source

MNISTDataset

 MNISTDataset (data_dir:str='~/Data', train=True, transform:<module'torchv
               ision.transforms.transforms'from'/opt/hostedtoolcache/Pytho
               n/3.9.18/x64/lib/python3.9/site-
               packages/torchvision/transforms/transforms.py'>=ToTensor())

MNIST digit dataset

Type Default Details
data_dir str ~/Data path where data is saved
train bool True train or test dataset
transform torchvision.transforms.transforms ToTensor() data formatting

source

MNISTDataset.train_dev_split

 MNISTDataset.train_dev_split (ratio:float, seed:int=42)
Type Default Details
ratio float percentage of train/dev split,
seed int 42 rand generator seed
Returns tuple train and set mnnist datasets

Usage

Setup MNIST dataset. Download data if not found in specified location.

# define test set (train=False)
test = MNISTDataset('../data/image', train=False)

# output ( (C,H,W), int)
print(test.ds, test.ds[0][0].dtype, type(test.ds[0][1]))
print(f"Number of samples in the dataset: {len(test)}")

# get item helper
X, y = test[0]
print(X.shape, y, X.type(), type(y))

# display each digit
test.show_idx(0)

# split data
train, dev = test.train_dev_split(0.8)
Dataset MNIST
    Number of datapoints: 10000
    Root location: ../data/image
    Split: Test
    StandardTransform
Transform: ToTensor() torch.float32 <class 'int'>
Number of samples in the dataset: 10000
torch.Size([1, 28, 28]) 7 torch.FloatTensor <class 'int'>

Instantiate from config file

It is convenient to keep setup of specific dataset for an experiment in a config file for reproductibility

# instantiate dataset from yaml config file
cfg = OmegaConf.load("../config/data/image/mnist.yaml")
print(cfg.dataset)
test = instantiate(cfg.dataset)
type(test)

# output ( (B,C, H,W), int)
print(test.ds, test.ds[0][0].dtype, type(test.ds[0][1]))
print(f"Number of samples in the dataset: {len(test)}")

# get item helper
X, y = test[0]
print(X.shape, y, X.type(), type(y))

# display each digit
test.show_idx(0)

# split data
train, dev = test.train_dev_split(0.8)
{'_target_': 'nimrod.image.datasets.MNISTDataset', 'data_dir': '../data/image', 'train': False, 'transform': {'_target_': 'torchvision.transforms.ToTensor'}}
Dataset MNIST
    Number of datapoints: 10000
    Root location: ../data/image
    Split: Test
    StandardTransform
Transform: ToTensor() torch.float32 <class 'int'>
Number of samples in the dataset: 10000
torch.Size([1, 28, 28]) 7 torch.FloatTensor <class 'int'>

MNIST DataModule


source

MNISTDataModule

 MNISTDataModule (data_dir:str='~/Data/',
                  train_val_test_split:List[float]=[0.8, 0.1, 0.1],
                  batch_size:int=64, num_workers:int=0,
                  pin_memory:bool=False, persistent_workers:bool=False)

A DataModule standardizes the training, val, test splits, data preparation and transforms. The main advantage is consistent data splits, data preparation and transforms across models.

Example::

import lightning.pytorch as L
import torch.utils.data as data
from pytorch_lightning.demos.boring_classes import RandomDataset

class MyDataModule(L.LightningDataModule):
    def prepare_data(self):
        # download, IO, etc. Useful with shared filesystems
        # only called on 1 GPU/TPU in distributed
        ...

    def setup(self, stage):
        # make assignments here (val/train/test split)
        # called on every process in DDP
        dataset = RandomDataset(1, 100)
        self.train, self.val, self.test = data.random_split(
            dataset, [80, 10, 10], generator=torch.Generator().manual_seed(42)
        )

    def train_dataloader(self):
        return data.DataLoader(self.train)

    def val_dataloader(self):
        return data.DataLoader(self.val)

    def test_dataloader(self):
        return data.DataLoader(self.test)

    def teardown(self):
        # clean up state after the trainer stops, delete files...
        # called on every process in DDP
        ...
Type Default Details
data_dir str ~/Data/ path to source data dir
train_val_test_split typing.List[float] [0.8, 0.1, 0.1] train val test %
batch_size int 64 size of compute batch
num_workers int 0 num_workers equal 0 means that it’s the main process that will do the data loading when needed, num_workers equal 1 is the same as any n, but you’ll only have a single worker, so it might be slow
pin_memory bool False If you load your samples in the Dataset on CPU and would like to push it during training to the GPU, you can speed up the host to device transfer by enabling pin_memory. This lets your DataLoader allocate the samples in page-locked memory, which speeds-up the transfer
persistent_workers bool False

Usage

# init
dm = MNISTDataModule(
    data_dir="../data/image",train_val_test_split=[0.8, 0.1, 0.1],
    batch_size = 64,
    num_workers = 0, # main process
    pin_memory= False,
    persistent_workers=False
)

# download or reference data from dir
dm.prepare_data()

# define train, eval, test subsets
dm.setup()

# access data batches via dataloader
test_dl = dm.test_dataloader()
X,Y = next(iter(test_dl))
print("X dim(B,C,W,H): ", X.shape, "Y: dim(B)", Y.shape)

# access data points directly by index
print(len(dm.data_test[0]), print(dm.data_test[0][0].shape))
imgs = [dm.data_test[i][0] for i in range(5)]

# display image samples
ImageDataset.show_grid(imgs)

# labels are ints
lbls = [dm.data_test[i][1] for i in range(5)]
print(lbls)
X dim(B,C,W,H):  torch.Size([64, 1, 28, 28]) Y: dim(B) torch.Size([64])
torch.Size([1, 28, 28])
2 None
[0, 3, 6, 9, 7]

Config

cfg = OmegaConf.load("../config/data/image/mnist.yaml")
print(cfg.datamodule)
dm = instantiate(cfg.datamodule)
dm.prepare_data()
dm.setup()
test_dl = dm.test_dataloader()
len(dm.data_test[0])
imgs = [dm.data_test[i][0] for i in range(5)]
ImageDataset.show_grid(imgs)
print(type(dm))
{'_target_': 'nimrod.image.datasets.MNISTDataModule', 'data_dir': '../data/image', 'train_val_test_split': [0.8, 0.1, 0.1], 'batch_size': 64, 'num_workers': 0, 'pin_memory': False, 'persistent_workers': False}
<class 'nimrod.image.datasets.MNISTDataModule'>