Last active
July 10, 2019 22:51
-
-
Save oezguensi/9bc1c1923c997e3cd49684285e2e6ef4 to your computer and use it in GitHub Desktop.
Visualize the layer activations of a Convolutional Neural Network to better understand the models behavior.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from keras.models import Model | |
conv_layers = [layer for layer in my_model.layers if 'Conv' in type(layer).__name__] | |
layer_outputs = [layer.output for layer in conv_layers] | |
activation_model = Model(inputs=my_model.input, outputs=layer_outputs) | |
activations = activation_model.predict(np.expand_dims(img, axis=0)) | |
ncols = 5 | |
layer_activationss = [[np.squeeze(layer) for layer in np.split( | |
np.squeeze(activation), activation.shape[-1], axis=2)] for activation in activations] | |
for layer, (layer_activations, layer) in enumerate(zip(layer_activationss, conv_layers)): | |
nrows = int(np.ceil(len(layer_activations) / ncols)) | |
fig, ax = plt.subplots(nrows, ncols, figsize=(20, nrows * 4)) | |
for i in range(nrows): | |
for j in range(ncols): | |
if i * j + j < len(layer_activations): | |
ax[i, j].imshow(layer_activations[i * j + j], cmap='jet') | |
ax[i, j].axes.get_xaxis().set_visible(False) | |
ax[i, j].axes.get_yaxis().set_visible(False) | |
print('Visualizing layer {}: {} with {} feature maps'.format( | |
layer, type(layer).__name__, len(layer_activations))) | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment