使用Pytorch显示每个类的图像数

使用Pytorch显示每个类的图像数,pytorch,tensor,pytorch-dataloader,Pytorch,Tensor,Pytorch Dataloader,我使用Pytorch和FashionList数据集,我想显示10个类中每个类的8个图像样本。但是,我没有考虑如何将培训测试拆分为train_标签,因为我需要循环标签(类)并打印每个类的8个标签。 你知道我怎样才能做到这一点吗 classes = ('T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot') # Define a transfor

我使用Pytorch和FashionList数据集,我想显示10个类中每个类的8个图像样本。但是,我没有考虑如何将培训测试拆分为train_标签,因为我需要循环标签(类)并打印每个类的8个标签。 你知道我怎样才能做到这一点吗

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))

如果我理解正确,您希望按标签对数据集进行分组,然后显示它们

您可以从构建词汇表开始,以按标签存储示例:

examples = {i: [] for i in range(len(classes))}
然后迭代列车集,并使用标签索引将其附加到列表中:

for x, i in trainset:
    examples[i].append(x)
然而,这将覆盖整个场景。如果您希望提前停止并避免每个类收集的数据超过8个,可以通过添加条件来实现:

n_examples = 8
for x, i in trainset:
    if all([len(ex) == n_examples for ex in examples.values()])
        break
    if len(examples[i]) < n_examples:
        examples[i].append(x)
如果要显示多个网格,可以使用两个连续的网格,一个在
dim=1上(按行),然后在
dim=2上(按列)创建网格

grid = torch.cat([torch.cat(examples[i], dim=1) for i in range(len(classes))], dim=2)
transforms.ToPILImage()(grid)
可能的结果:


谢谢你的帮助,我最近发现了,这可能是一个更快的选择。
grid = torch.cat([torch.cat(examples[i], dim=1) for i in range(len(classes))], dim=2)
transforms.ToPILImage()(grid)