How to add noise to inputs as a function of input

If you would like to apply the same random noise to the corresponding image tensor, you could initialize a noise tensor in your Dataset's __init__ function with the same length as the number of images, and add it to each tensor after the transformation.

class MyDataset(Dataset):
    def __init__(self, image_paths, targets, transform=None):
        self.image_paths = image_paths
        self.targets = targets
        self.transform = transform
        self.noise = torch.randn(len(self.image_paths), 3, 224, 224)
        
    def __getitem__(self, index):
        x = Image.open(self.image_paths[index])
        y = self.targets[index]
        if transform is not None:
            x = self.transform(x)
        x = x + self.noise[index]
        return x, y
    
    def __len__(self):
        return len(self.image_paths)
1 Like