A lot of effort in solving any machine learning problem goes into
preparing the data. PyTorch provides many tools to make data loading
easy and hopefully, to make your code more readable. In this tutorial,
we will see how to load and preprocess/augment data from a non trivial
dataset.
To run this tutorial, please make sure the following packages are
installed:
Let’s take a single image name and its annotations from the CSV, in this case row index number 65
for person-7.jpg just as an example. Read it, store the image name in img_name and store its
annotations in an (L, 2) array landmarks where L is the number of landmarks in that row.
Let’s write a simple helper function to show an image and its landmarks
and use it to show a sample.
defshow_landmarks(image,landmarks):"""Show image with landmarks"""plt.imshow(image)plt.scatter(landmarks[:,0],landmarks[:,1],s=10,marker='.',c='r')plt.pause(0.001)# pause a bit so that plots are updatedplt.figure()show_landmarks(io.imread(os.path.join('data/faces/',img_name)),landmarks)plt.show()
Dataset class
torch.utils.data.Dataset is an abstract class representing a
dataset.
Your custom dataset should inherit Dataset and override the following
methods:
__len__ so that len(dataset) returns the size of the dataset.
__getitem__ to support the indexing such that dataset[i] can
be used to get ith sample.
Let’s create a dataset class for our face landmarks dataset. We will
read the csv in __init__ but leave the reading of images to
__getitem__. This is memory efficient because all the images are not
stored in the memory at once but read as required.
Sample of our dataset will be a dict
{'image':image,'landmarks':landmarks}. Our dataset will take an
optional argument transform so that any required processing can be
applied on the sample. We will see the usefulness of transform in the
next section.
classFaceLandmarksDataset(Dataset):"""Face Landmarks dataset."""def__init__(self,csv_file,root_dir,transform=None):""" Arguments: csv_file (string): Path to the csv file with annotations. root_dir (string): Directory with all the images. transform (callable, optional): Optional transform to be applied on a sample. """self
Let’s instantiate this class and iterate through the data samples. We
will print the sizes of first 4 samples and show their landmarks.
One issue we can see from the above is that the samples are not of the
same size. Most neural networks expect the images of a fixed size.
Therefore, we will need to write some preprocessing code.
Let’s create three transforms:
Rescale: to scale the image
RandomCrop: to crop from image randomly. This is data
augmentation.
ToTensor: to convert the numpy images to torch images (we need to
swap axes).
We will write them as callable classes instead of simple functions so
that parameters of the transform need not be passed every time it’s
called. For this, we just need to implement __call__ method and
if required, __init__ method. We can then use a transform like this:
Observe below how these transforms had to be applied both on the image and
landmarks.
classRescale(object):"""Rescale the image in a sample to a given size. Args: output_size (tuple or int): Desired output size. If tuple, output is matched to output_size. If int, smaller of image edges is matched to output_size keeping aspect ratio the same. """def__init__(self,output_size):assertisinstance(output_size,(int,tuple))self.output_size
Compose transforms
Now, we apply the transforms on a sample.
Let’s say we want to rescale the shorter side of the image to 256 and
then randomly crop a square of size 224 from it. i.e, we want to compose
Rescale and RandomCrop transforms.
torchvision.transforms.Compose is a simple callable class which allows us
to do this.
However, we are losing a lot of features by using a simple for loop to
iterate over the data. In particular, we are missing out on:
Batching the data
Shuffling the data
Load the data in parallel using multiprocessing workers.
torch.utils.data.DataLoader is an iterator which provides all these
features. Parameters used below should be clear. One parameter of
interest is collate_fn. You can specify how exactly the samples need
to be batched using collate_fn. However, default collate should work
fine for most use cases.
dataloader=DataLoader(transformed_dataset,batch_size=4,shuffle=True,num_workers=0)# Helper function to show a batchdefshow_landmarks_batch(sample_batched):"""Show image with landmarks for a batch of samples."""images_batch, \
In this tutorial, we have seen how to write and use datasets, transforms
and dataloader. torchvision package provides some common datasets and
transforms. You might not even have to write custom classes. One of the
more generic datasets available in torchvision is ImageFolder.
It assumes that images are organized in the following way:
where ‘ants’, ‘bees’ etc. are class labels. Similarly generic transforms
which operate on PIL.Image like RandomHorizontalFlip, Scale,
are also available. You can use these to write a dataloader like this: