Images do not line up with labels after shuffling (ImageFolder)

I am training an image classifier and have a directory of local images. After loading via ImageFolder and shuffling, I go to print an image but the corresponding label is incorrect

Local file directory:

root
| class1
|- 1.png
|- 2.png
| class2
|- 1.png
|- 2.png
| …

Data loader:

dataset = datasets.ImageFolder(train_dir, transform=train_transform)
dataloader = torch.utils.data.DataLoader(trainset, batch_size = batch_size, shuffle=True)

Image printer:

for images, labels in dataloader:
print(labels[5])
plt.imshow(images[5].permute(1, 2, 0))
plt.show()

The image prints but the output label is incorrect

It works as intended without shuffle=True but I need the randomization for better testing

Your DataLoader doesn’t use the specified dataset but an undefined trainset so make sure the right data is used.

Thanks for your response - I renamed trainset to dataset when I was writing this question but missed that one - the naming is consistent in my actual code when I attempt to run it

I found the solution. It turns out ‘for images, labels in dataloader’ returns the index as labels rather than the classname. To get the class, do classes[labels.numpy()[0]]

I was confused because the classnames given to me were already numeric (ie, 1, 2, 3) rather than strings (ex ‘cat’, ‘dog’) so I confused the indexes as being the class names

All the best if anyone else encounters this (especially fellow SYDE 572 students!)