AttributeError: 'Image' object has no attribute 'new' occurs when trying to use Pytorchs AlexNet Lighting preprocessing
I tried to train my model on ImageNet using inception and Alexnet like preprocessing. I used Fast-ai imagenet training script provided script.   Pytorch has support for inception like preprocessing but for AlexNets Lighting, we have to implement it ourselves :

__imagenet_pca = {
    'eigval': torch.Tensor([0.2175, 0.0188, 0.0045]),
    'eigvec': torch.Tensor([
        [-0.5675,  0.7192,  0.4009],
        [-0.5808, -0.0045, -0.8140],
        [-0.5836, -0.6948,  0.4203],
    ])
}

# Lighting data augmentation taken from here - https://github.com/eladhoffer/convNet.pytorch/blob/master/preprocess.py
class Lighting(object):
    """Lighting noise(AlexNet - style PCA - based noise)"""

    def __init__(self, alphastd, eigval, eigvec):
        self.alphastd = alphastd
        self.eigval = eigval
        self.eigvec = eigvec

    def __call__(self, img):
        if self.alphastd == 0:
            return img

        alpha = img.new().resize_(3).normal_(0, self.alphastd)
        rgb = self.eigvec.type_as(img).clone()\
            .mul(alpha.view(1, 3).expand(3, 3))\
            .mul(self.eigval.view(1, 3).expand(3, 3))\
            .sum(1).squeeze()
        return img.add(rgb.view(3, 1, 1).expand_as(img))


which is finally used like this :

train_tfms = transforms.Compose([
        transforms.RandomResizedCrop(size),
        transforms.RandomHorizontalFlip(),
        transforms.ColorJitter(.4,.4,.4),
        transforms.ToTensor(),
        Lighting(0.1, __imagenet_pca['eigval'], __imagenet_pca['eigvec']),
        normalize,
    ])
    train_dataset = datasets.ImageFolder(traindir, train_tfms)
    train_sampler = (torch.utils.data.distributed.DistributedSampler(train_dataset)
                     if args.distributed else None)
    train_loader = torch.utils.data.DataLoader(
        train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None),
        num_workers=args.workers, pin_memory=True, sampler=train_sampler)


However, the problem is, whenever I run the script I get the:


  'AttributeError: 'Image' object has no attribute 'new''


Which complains about this line:

alpha = img.new().resize_(3).normal_(0, self.alphastd)

I am clueless as to why this is happening. I'm using Pytorch 0.4 by the way.

Thanks to @iacolippo's comment, I finally found the cause!  

Unlike the example I wrote here, in my actual script, I had used transforms.ToTensor() after the lighting() method. Doing so resulted in a PIL image being sent as the input for lightining()which expects a Tensor and that's why the error occurs.

So basically the snippet I posted in the question is correct and .ToTensor has to be used prior to calling Lighting().
