Pytorch: Can't load data as tensor

Hello.
I loaded images using ImageFolder and DataLoader as below.

transform = transforms.Compose([
    transforms.Scale((64,64)),
    transforms.ToTensor(),
    transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))
])

data_dir = './train_dog'          # this path depends on your computer
dset = datasets.ImageFolder(data_dir, transform)
print len(dset)
train_loader = torch.utils.data.DataLoader(dset, batch_size=128, shuffle=True)

However, it shows an error in training loops

File "gan_scratch.py", line 258, in <module>
    mini_batch = x_.size()[0]
AttributeError: 'list' object has no attribute 'size'

The part of training code is as below.

    for x_ in train_loader:
        # train discriminator D
        D.zero_grad()
        mini_batch = x_.size()[0] #error happens on this line

        y_real_ = torch.ones(mini_batch)
        y_fake_ = torch.zeros(mini_batch)

        x_, y_real_, y_fake_ = Variable(x_.cuda()).float(), Variable(y_real_.cuda()).float(), Variable(y_fake_.cuda()).float()

I thought I loaded images as tensor, but why is it still “list”?

If you read the source code of ImageFolder carefully, you will know that train_loader will generate a batch of image and the corresponding labels. So x_ will be a list(or tuple? I am quite sure). You should use something like

for data, target in train_loader:
     # do something with data and target, which are both Tensor
    # data and target will have a method called size()
1 Like