Skip to content

Instantly share code, notes, and snippets.

@hemendrarajawat
Last active August 20, 2022 10:00
Show Gist options
  • Save hemendrarajawat/e6593a3ed339c12af7cae53cf29ad274 to your computer and use it in GitHub Desktop.
Save hemendrarajawat/e6593a3ed339c12af7cae53cf29ad274 to your computer and use it in GitHub Desktop.
ML-Utils
import math
import matplotlib.pyplot as plt
def plot_grid_images(images, labels, columns=5, image_size=None, figsize=(8, 8), cmap='gray', title=None, file_name=None):
fig = plt.figure(figsize=figsize)
fig.tight_layout(h_pad=3)
rows = math.ceil(len(images)/columns)
for image, label, position in zip(images, labels, range(1, len(labels)+1)):
fig.add_subplot(rows, columns, position)
if image_size is not None:
image = image.reshape(image_size)
plt.imshow(image, cmap=cmap, interpolation='nearest')
plt.axis('off')
plt.title(label)
if title is not None:
fig.suptitle(title, fontsize=14)
if file_name is not None:
plt.savefig(file_name)
plt.show()
return file_name
def show_examples(generator, no_labels=False, title=None, class_indices_exist=True, no_images_to_show=9, columns=3):
images_to_show = []
images_labels = []
images_shape = None
if no_labels:
for images in generator:
images_shape = images.shape[1:]
images_to_show.extend(images)
if len(images_to_show) >= no_images_to_show:
break
images_labels = [None for _ in range(no_images_to_show)]
else:
if class_indices_exist:
class_indices = {index: label for label, index in generator.class_indices.items()}
for images, labels in generator:
images_shape = images.shape[1:]
images_to_show.extend(images)
if not class_indices_exist:
images_labels.extend(labels)
else:
images_labels.extend([class_indices[index] for index in labels])
if len(images_to_show) >= no_images_to_show:
break
print('IMAGE SHAPE: ', images_shape)
plot_grid_images(images_to_show[:no_images_to_show], images_labels[:no_images_to_show], title=title, columns=columns)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment