猿问

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

我试图在每次迭代时打印图像名称。但是,我收到错误 TypeError: 'ToTensor' object is not iterable。请告诉我我要去哪里?非常感谢


from torchvision import datasets

import torch.utils.data

from torch.utils.data import DataLoader

from torchvision import transforms

from dataset2 import CellsDataset

from torchvision import datasets

import torch

import torchvision

import torchvision.transforms as transforms



class ImageFolderWithPaths(datasets.ImageFolder):

    """Custom dataset that includes image file paths. Extends

    torchvision.datasets.ImageFolder

    """


# override the __getitem__ method. this is the method that dataloader calls

def __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 dataloader

data_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 data

for inputs, labels, paths in dataloader:

    # use the above variables freely

   print(inputs, labels, paths)




神不在的星期二
浏览 238回答 1
1回答

MMMHUHU

这是因为transforms.Compose()需要是一个列表(可能也接受了其他一些迭代)。问题在这里:dataset = DataLoader(data_dir, transforms.Compose(transforms.ToTensor()))尝试:transforms = transforms.Compose([transforms.ToTensor()])这将创建一个可调用对象,您可以在其中传递数据。
随时随地看视频慕课网APP

相关分类

Python
我要回答