datasets.ImageFolder generates the same label for different classes

My code and output:

import torch
from torch import nn

import matplotlib.pyplot as plt
import numpy as np
import torchvision
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision.transforms as transforms

NUM_OF_CLASSES = 29
batch_size = 32

TestTransform = transforms.Compose(
    [
    transforms.Resize(224),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
    ]
)

RASBAND_set = torchvision.datasets.ImageFolder('../input/asl-alphabet-test', transform=TestTransform)
loader = torch.utils.data.DataLoader(RASBAND_set, batch_size=batch_size, shuffle=True)

# function to show an image
def imshow(img):
    img = img / 2 + 0.5     # unnormalize
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
    plt.show()

# get some random test images
dataiter = iter(loader)
images, labels = dataiter.next()

# show images
imshow(torchvision.utils.make_grid(images))
# print labels
print(' '.join(f'{labels[j]}' for j in range(batch_size)))

Output:
image

20 26 15 26 21 28 26 8 26 26 26 26 26 18 2 19 11 3 8 26 26 26 18 26 26 14 1 6 26 26 6 26

The dataset I used: ASL Alphabet Test | Kaggle

For a reason, a lot of images get the label ‘26’ when they are clearly not in the same class. I checked the folder structure, and it should be sufficient for ImageFolder. What could be the problem?

Based on your description it seems you are concerned about the image to class mapping in the `ImageFolder.
If so, you could check this mapping manually via:

print(RASBAND_set.imgs)

which would return the a list containing image path and their label tuples.