3 回答

TA贡献2036条经验 获得超8个赞
如果你想从你的 Trainloader/Testloader 中选择特定的图像,你应该查看Subsetmaster的功能:
这是一个如何使用它的示例:
testset = ImageFolderWithPaths(root="path/to/your/Image_Data/Test/", transform=transform)
subset_indices = [0] # select your indices here as a list
subset = torch.utils.data.Subset(testset, subset_indices)
testloader_subset = torch.utils.data.DataLoader(subset, batch_size=1, num_workers=0, shuffle=False)
这样您就可以只使用一个图像和标签。但是,您当然可以在subset_indices 中使用多个索引。
如果要使用 DataFolder 中的特定图像,可以使用 dataset.sample 并构建字典以获取要使用的图像的索引。

TA贡献1772条经验 获得超5个赞
如果你DataLoader是这样的:
test_loader = DataLoader(image_datasets['val'], batch_size=batch_size, shuffle=True)
它为您提供了一批 size batch_size,您可以通过直接索引批次来挑选一个随机示例:
for test_images, test_labels in test_loader:
sample_image = test_images[0] # Reshape them according to your needs.
sample_label = test_labels[0]
替代解决方案
您可以使用RandomSampler获取随机样本。
batch_size在您的 DataLoader 中使用1。
直接从您的 DataSet 中获取样本,如下所示:
mnist_test = datasets.MNIST('../MNIST/', train=False, transform=transform)
现在使用这个数据集来采样:
for image, label in mnist_test:
# do something with image and other attributes
(可能是最好的)见这里:
inputs, classes = next(iter(dataloader))

TA贡献1871条经验 获得超8个赞
通过迭代dataset并没有返回“随机”的例子,你应该使用:
# Recovers the original `dataset` from the `dataloader`
dataset = dataloader.dataset
n_samples = len(dataset)
# Get a random sample
random_index = int(numpy.random.random()*n_samples)
single_example = dataset[random_index]
添加回答
举报