If your DataLoader
is something like this:
test_loader = DataLoader(image_datasets['val'], batch_size=batch_size, shuffle=True)
it is giving you a batch of size batch_size
, and you can pick out a single random example by directly indexing the batch:
for test_images, test_labels in test_loader:
sample_image = test_images[0] # Reshape them according to your needs.
sample_label = test_labels[0]
Alternative solutions
-
You can use RandomSampler to obtain random samples.
-
Use a
batch_size
of 1 in your DataLoader. -
Directly take samples from your DataSet like so:
mnist_test = datasets.MNIST('../MNIST/', train=False, transform=transform)
Now use this dataset to take samples:
for image, label in mnist_test: # do something with image and other attributes
-
(Probably the best) See here:
inputs, classes = next(iter(dataloader))