Basic: Deep learning with PyTorch#
If you followed through the guide, you may have noticed that bioimageloader
has many
classes whose interfaces are similar to those of PyTorch, a
popular python library for deep learning. It is true that bioimageloader
followed
the design of PyTorch’s data module, and especially so for bioimageloader.ConcatDataset
and bioimageloader.BatchDataloader
. The benefit is that all bioimageloader
datasets are compatible with PyTorch.
For example, you can replace bioimageloader.BatchDataloader
with its
equivalent DataLoader
from PyTorch, while keeping the same transformation API from albumentations. In fact,
albumentations
is a part of the PyTorch ecosystem
Note that you may want to convert image arrays to Tensor which PyTorch can handle, using ToTensorV2 from albumentations library. Find a full example guide here.
1import albumentations as A
2from albumentations.pytorch import ToTensorV2 # PyTorch helper
3from bioimageloader.collections import DSB2018
4from torch.utils.data import DataLoader # PyTorch
5
6transforms_totensor = A.Compose([
7 A.RandomCrop(width=256, height=256),
8 A.HorizontalFlip(p=0.5),
9 A.RandomBrightnessContrast(p=0.2),
10 ToTensorV2(), # convert numpy ndarray to torch Tensor
11])
12# construct dset with transforms
13dsb2018 = DSB2018('./data/DSB2018', transforms=transforms_totensor)
14batch_loader = Dataloader(dsb2018,
15 batch_size=16,
16 drop_last=True,
17 num_workers=8)
18# iterate transformed images
19data: dict[str, numpy.ndarray]
20for data in dsb2018:
21 image = data['image'] # torch.Tensor, (b, c, h, w)
22 mask = data['mask'] # torch.Tensor, (b, h, w)
23 # these assertions will not throw AssertionError
24 assert image.shape[0] == 16 and mask.shape[0] == 16
25 assert image.shape[1] == 3 # notice Tensor convention shape (b, c, h, w)
26 assert image.shape[2] == 256 and image.shape[3] == 256
27 assert mask.shape[1] == 256 and mask.shape[2] == 256
28 do_something(image, mask)