AttributeError:尝试使用Pytorchs AlexNet照明预处理时,出现“Image”对象没有属性“new”

2024-09-22 16:23:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用inception和{}之类的预处理,在ImageNet上训练我的模型。我使用了Fast-ai imagenet training script提供的脚本。Pytorch支持inception类似的预处理,但是对于AlexNetsLighting,我们必须自己实现它:

__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))

最后是这样使用的:

^{pr2}$

但是,问题是,每当我运行脚本时,都会得到:

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

它抱怨这条线:

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

我不知道为什么会发生这种事。顺便说一下,我使用的是Pythorc0.4。在


Tags: selfalpha脚本viewimgnewtorchlighting
1条回答
网友
1楼 · 发布于 2024-09-22 16:23:31

多亏了@iacolipo的评论,我终于找到了原因!在

与我在这里编写的示例不同,在我的实际脚本中,我在lighting()方法之后使用了transforms.ToTensor()。这样做会导致一个PIL图像作为lightining()的输入而被发送,这就是为什么会出现错误。在

因此,基本上我在问题中发布的片段是正确的,.ToTensor必须在调用Lighting()之前使用。在

相关问题 更多 >