Skip to content

Instantly share code, notes, and snippets.

@Eligijus112
Created May 27, 2020 06:35
Show Gist options
  • Save Eligijus112/33def67567c844bcc1f26a3e1327d3c5 to your computer and use it in GitHub Desktop.
Save Eligijus112/33def67567c844bcc1f26a3e1327d3c5 to your computer and use it in GitHub Desktop.
Convolution visualizer
# Extracting the trained layers from the model
successive_outputs = [layer.output for layer in model.layers[1:]]
visualization_model = tf.keras.models.Model(inputs = model.input, outputs = successive_outputs)
# Getting an image from the training set
image = training_images[1]
# Intermediate representations for this image
successive_feature_maps = visualization_model.predict(image.reshape(1, 28, 28, 1))
# Getting the names of the layers
layer_names = [layer.name for layer in model.layers]
plt.figure(figsize=(22, 3))
# Visualizing the convoluted layer
for layer_name, feature_map in zip(layer_names, successive_feature_maps):
if layer_name in ['conv2d']:
n_features = feature_map.shape[-1]
# The feature map has shape (1, size, size, n_features)
size = feature_map.shape[1]
# We will tile our images in this matrix
display_grid = np.zeros((size, size * n_features))
for i in range(n_features):
# Postprocess the feature to make it visually palatable
x = feature_map[0, :, :, i]
x -= x.mean()
x /= x.std()
x *= 64
x += 128
x = np.clip(x, 0, 255).astype('uint8')
# We'll tile each filter into this big horizontal grid
display_grid[:, i * size : (i + 1) * size] = x
# Display the grid
scale = 20. / n_features
plt.title(layer_name)
plt.grid(False)
plt.imshow(display_grid, aspect='auto', cmap='viridis')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment