Afrid
Afrid

Reputation: 69

How to visualize output of intermediate layers of convolutional neural network in keras?

recently I created basic CNN model for cats and dogs classification (very basic). How can I visualize the output of these layers using keras? I used Tensorflow backend for keras.

Upvotes: 3

Views: 5315

Answers (2)

sushant097
sushant097

Reputation: 3746

The Keras provide CNN intermediate output visualization with simple technique by two ways:

I have assume that you have already build the model in keras as model= Sequential() and CNN layer implementation.

First read the image and reshape it to as Conv2d() needs four dimensions So, reshape your input_image to 4D [batch_size, img_height, img_width, number_of_channels] eg:

import cv2
import numpy as np
img = cv2.imread('resize.png',0)
img = np.reshape(img, (1,800,64,1)) # (n_images, x_shape, y_shape, n_channels)
img.shape # ((1,800,64,1)) consider gray level image

First Way:

from keras.models import Model
layer_name = 'Conv1'
intermediate_layer_model = Model(inputs=model.input,
                                          outputs=model.get_layer(layer_name).output)
intermediate_output = intermediate_layer_model.predict(img)

Then plot it using matplotlib as:

import matplotlib.pyplot as plt
import numpy as np ## to reshape
%matplotlib inline
temp = intermediate_output.reshape(800,64,2) # 2 feature
plt.imshow(temp[:,:,2],cmap='gray') 
# note that output should be reshape in 3 dimension


Second Way:

You can create the function using keras backend and pass the layer level as numeric value as shown below:

from keras import backend as K

# with a Sequential model
get_3rd_layer_output = K.function([model.layers[0].input],
                                  [model.layers[2].output])
layer_output = get_3rd_layer_output([img])[0] ## pass as input image

Visit this link

Upvotes: 2

Daniel Möller
Daniel Möller

Reputation: 86630

You can define a model that takes the output of every layer you want to see and make a prediction:

Suppose you have your complete model:

cnnModel = #a model you have defined with layers

And suppose you want the outputs of the layers of indices 1, 5 and 8.
Create a new model from this one, using the outputs of these layers.

from keras.models import Model

desiredLayers = [1,5,8]
desiredOutputs = [cnnModel.layers[i].output for i in desiredLayers] 

#alternatively, you can use cnnModel.get_layer('layername').output for that    

newModel = Model(cnnModel.inputs, desiredOutputs)

Make predictions with this model:

print(newModel.predict(inputData))

Now, "visualizing" these results may be tricky, since they may have way more channels than a regular image.

Upvotes: 6

Related Questions