Predicts image and retrieve id image from dataset

I’m a beginner using PyTorch models
I need to know the name or id image prediction and store the results inside CSV file (id or name image and predictions)

def visualize_model(model, num_images=10):

was_training =


images_so_far = 0

fig = plt.figure()

with torch.no_grad():

    for i, (inputs, labels) in enumerate(dataloaders['val']):

        inputs =

        labels =

        outputs = model(inputs)

        _, preds = torch.max(outputs, 1)


        for j in range(inputs.size()[0]):


            images_so_far += 1

            ax = plt.subplot(num_images//2, 2, images_so_far)


            ax.set_title('predicted: {}'.format(class_names[preds[j]]))


            if images_so_far == num_images:




the code prints the image and predicts, is there a way to retrieve the name or id image?

sorry I am a beginner in vision

I assume you are referring to the image name (or path), not the class name.
If so, you could create a custom Dataset as described here and return the image name in the __getitem__ additionally to the data and target tensors. Inside the DataLoader loop you would then have 3 values and could print the image name as well:

for i, (inputs, labels, name) in enumerate(dataloaders['val']):