正如问题所示,我试图将images
转换为张量。
X, y = train_sequence[idx] images = Variable(torch.from_numpy(X)).to(device) # [batch, channel, H, W]masks = Variable(torch.from_numpy(y)).to(device) print(type(images)) ## Output: <class 'torch.Tensor'>images = transforms.Normalize((0.5, 0.5, 0.5, 0.5, 0.5), (0.5, 0.5, 0.5,0.5, 0.5))(images)masks = transforms.Normalize((0.5), (0.5))(masks)
但我在---> 19 images = transforms.Normalize((0.5, 0.5, 0.5, 0.5, 0.5), (0.5, 0.5, 0.5,0.5, 0.5))(images)
处得到了错误
TypeError: tensor is not a torch image.
回答:
这是因为目前,torchvison.transforms.Normalize
仅支持具有2或3个通道的图像,且不包含批次维度,即(C, H, W)
。因此,不应传入一个4D张量,像这样会起作用:
image = torch.ones(3, 64, 64)image = transforms.Noramalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))(image)
另外,由于0.5
值代表图像通道的均值和标准差,通常应该只有3个通道(你不会“标准化”批次维度,只标准化空间维度),所以不要使用长度为5的tuple
,而是使用(0.5, 0.5, 0.5)
。