为了账号安全,请及时绑定邮箱和手机立即绑定

PyTorch TypeError:“ToTensor”对象不可迭代

PyTorch TypeError:“ToTensor”对象不可迭代

神不在的星期二 2023-02-22 15:37:52
我试图在每次迭代时打印图像名称。但是,我收到错误 TypeError: 'ToTensor' object is not iterable。请告诉我我要去哪里?非常感谢from torchvision import datasetsimport torch.utils.datafrom torch.utils.data import DataLoaderfrom torchvision import transformsfrom dataset2 import CellsDatasetfrom torchvision import datasetsimport torchimport torchvisionimport torchvision.transforms as transformsclass ImageFolderWithPaths(datasets.ImageFolder):    """Custom dataset that includes image file paths. Extends    torchvision.datasets.ImageFolder    """# override the __getitem__ method. this is the method that dataloader callsdef __getitem__(self, index):    # this is what ImageFolder normally returns     original_tuple = super(ImageFolderWithPaths, self).__getitem__(index)    # the image file path    path = self.imgs[index][0]    # make a new tuple that includes original and the path    tuple_with_path = (original_tuple + (path,))    return tuple_with_path# EXAMPLE USAGE:# instantiate the dataset and dataloaderdata_dir = "/Users/nubstech/Documents/GitHub/CellCountingDirectCount/Eddata/"dataset = ImageFolderWithPaths(data_dir) # our custom dataset#dataloader = DataLoader(dataset)transform = transforms.Compose([    # you can add other transformations in this list    transforms.ToTensor()])dataset = DataLoader(data_dir, transforms.Compose(transforms.ToTensor()))dataloader = torch.utils.DataLoader(dataset)# iterate over datafor inputs, labels, paths in dataloader:    # use the above variables freely   print(inputs, labels, paths)
查看完整描述

1 回答

?
MMMHUHU

TA贡献1834条经验 获得超8个赞

这是因为transforms.Compose()需要是一个列表(可能也接受了其他一些迭代)。问题在这里:

dataset = DataLoader(data_dir, transforms.Compose(transforms.ToTensor()))

尝试:

transforms = transforms.Compose([transforms.ToTensor()])

这将创建一个可调用对象,您可以在其中传递数据。


查看完整回答
反对 回复 2023-02-22
  • 1 回答
  • 0 关注
  • 236 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信