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

不羁的心 提交于 2020-01-15 05:04:52

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/46828476/how-to-visualize-output-of-intermediate-layers-of-convolutional-neural-network-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!