transforms.Compose and transforms.Lambda are just empty wrapper?

I am writing my own transforms for data augmentation. for example

def my_transform_1(x, params=default_values):
     #do something
     return x

def my_transform_2(x, params=default_values):
     #do something
     return x

Following the documentation, i should have use the following code in the Dataset:

   train_dataset = MyCustomtDataset(...,
                                    transform=transforms.Compose([
                                        transforms.Lambda(lambda x: my_transform_1(x)),
                                        transforms.Lambda(lambda x: my_transform_2(x)),
                                    ],
                                    ....)

However, my code still works if I use:

   train_dataset = MyCustomtDataset(...,
                                    transform=[
                                        lambda x: my_transform_1(x),
                                        lambda x: my_transform_2(x),
                                    ],
                                    ....)
   #note: 
   MyCustomtDataset(Dataset):
       ...
        def __getitem__(self, index): 
            img = self.images[index]
            if self.transform is not None:
                 for t in self.transform:
                     img = t(img)   #taking care of multiple transform here

What is the use of transforms.Compose and transforms.Lambda? I look at their code, but found that they are just empty wrapper? Is my code ok?

class Lambda(object):
    '''Applies a lambda as a transform.'''

    def __init__(self, lambd):
        assert isinstance(lambd, types.LambdaType)
        self.lambd = lambd

    def __call__(self, img):
        return self.lambd(img)

class Compose(object):
    '''Composes several transforms together.'''
 
    def __init__(self, transforms):
        self.transforms = transforms

    def __call__(self, img):
        for t in self.transforms:
            img = t(img)
        return img

1 Like

Yep, they are empty wrappers much like torch.utils.data.DataSet.

They are around to make composing and creating new transforms trivial.

BTW, There is no requirement pass transform as an argument to class MyCustomtDataset(torch.utils.data.DataSet). Only requirement is that __getitem__ and __len__ have to be implemented.

2 Likes