Skip to content

Instantly share code, notes, and snippets.

@NISH1001
Created January 12, 2019 14:42
Show Gist options
  • Save NISH1001/7287b01aaa531aec08ab21359f7d3342 to your computer and use it in GitHub Desktop.
Save NISH1001/7287b01aaa531aec08ab21359f7d3342 to your computer and use it in GitHub Desktop.
visualize activation at different layers in CNN in Keras

First get list of all the layers (after activation).

from keras.models import Model
layer_outputs = [layer.output for layer in model.layers]

Predict image and get corresponding activation in each layer

activation_model = Model(inputs=model.input, outputs=layer_outputs)
activations = activation_model.predict(image)

Plot Activation

def display_activation(activations, col_size, row_size, act_index): 
    activation = activations[act_index]
    activation_index=0
    fig, ax = plt.subplots(row_size, col_size, figsize=(row_size*2.5,col_size*1.5))
    for row in range(0,row_size):
        for col in range(0,col_size):
            ax[row][col].imshow(activation[0, :, :, activation_index], cmap='gray')
            activation_index += 1

Here, act_index represent the layer whose activation we are going to visualize.

Display

Plot activation of layer at index 5.

display_activation(activations, 4, 4, 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment