Display number of images per class using Pytorch
I am using Pytorch with FashionMNIST dataset I would like to display 8 image sample from each of the 10 classes. However, I did not figure how to split the training test into train_labels since I need to loop on the labels(class) and print 8 of each class.
any idea how I can achieve this?
classes = ('T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot')

# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
                              #  transforms.Lambda(lambda x: x.repeat(3,1,1)),
                                transforms.Normalize((0.5, ), (0.5,))])
# Download and load the training data
trainset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True)
# Download and load the test data
testset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=False, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=True)


print('Training set size:', len(trainset))
print('Test set size:',len(testset))


If I understand you correctly you want to group your dataset by labels then display them.
You can start by constructing a dictionnary to store examples by label:
examples = {i: [] for i in range(len(classes))}

Then iterate over the trainset and append to the list using the label's index:
for x, i in trainset:
    examples[i].append(x)

However, this will go over the whole set. If you'd like to early stop and avoid gathering more than 8 per-class you can do so by adding conditions:
n_examples = 8
for x, i in trainset:
    if all([len(ex) == n_examples for ex in examples.values()])
        break
    if len(examples[i]) &lt; n_examples:
        examples[i].append(x)

Only thing left is to display with torchvision.transforms.ToPILImage:
transforms.ToPILImage()(examples[3][0])

If you want to show more than one, you could use two consecutive torch.cat, one on dim=1 (by rows) then on dim=2 (by columns) to create a grid.
grid = torch.cat([torch.cat(examples[i], dim=1) for i in range(len(classes))], dim=2)
transforms.ToPILImage()(grid)

Possible result:

