This code snippet demonstrates how to use plt.subplot in Python's Matplotlib library to visualize image predictions. It iterates through a validation generator, predicts the class label for each image, and then displays a grid of images with their predicted and actual labels.

plt.figure(figsize=(20, 20))
i = 1
for images, labels in iter(validation_generator):
    # Get Random Image and label
    image, label = get_random_data([images, labels])
    pred_label = class_names[np.argmax(loaded_model.predict(image[np.newaxis, ...]))]
    # Plot it
    plt.subplot(5, 5, i)
    show_image(image, image_title=f'Class : {class_names[int(label)]}, Pred : {pred_label}')
    # Make sure to end the Loop
    i += 1
    if i >= 26: break

plt.tight_layout()
plt.show()

Key elements:

  • plt.figure(figsize=(20, 20)): Creates a Matplotlib figure with a specified size.
  • plt.subplot(5, 5, i): Creates a subplot grid with 5 rows and 5 columns, placing the current image at index i.
  • show_image(image, image_title=f'Class : {class_names[int(label)]}, Pred : {pred_label}'): A custom function (not included here) to display the image along with its predicted and actual class labels.
  • plt.tight_layout(): Adjusts the spacing between subplots to prevent overlapping.
  • plt.show(): Displays the created figure.

This code provides a foundation for visualizing predictions from a deep learning model. You can modify it to suit your specific needs by adjusting the number of subplots, customizing the display, and using different data sources.

Python Matplotlib: Visualizing Image Predictions with plt.subplot

原文地址: https://www.cveoy.top/t/topic/o8Rl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录