How to add `target labels` with `ImageFolder images` for `DataLoader tensor`

I am loading some images from a folder using ImageFolder and then using transform to convert into tensor.

Then I load the labels from another CSV file and converted into tensor.

Finally, I want to combine these 2 tensors and want to use them for the DataLoader. But getting the error AttributeError: 'ImageFolder' object has no attribute 'size'


train_data_dir = '/home/dataset/'
train_labels = pd.read_csv('/home/HousePrice.csv')
transform = transforms.Compose([
    transforms.Resize((256, 256)),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

train_data_tensor = datasets.ImageFolder(train_data_dir, transform=transform)
train_labels_tensor = torch.tensor(train_labels.values)

train_tensor = TensorDataset(train_data_tensor, train_labels_tensor)
train_dataloader =, batch_size=1, shuffle=True)

return train_dataloader

How can I add the target labels with my images and make a single tensor to use in the DataLoader

1 Like

ImageFolder already creates the data-target mapping internally and loads each sample lazily in its __getitem__.
I think the cleanest approach would be to write a custom Dataset by reusing parts of DatasetFolder and add your target tensor manually to your custom class.