繁体   English   中英

如何在keras中可视化卷积神经网络中间层的输出?

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

最近我为猫狗分类创建了基本的CNN模型(非常基础)。 如何使用keras可视化这些图层的输出? 我使用Tensorflow后端进行keras。

您可以定义一个模型,该模型获取您要查看的每个图层的输出并进行预测:

假设你有完整的模型:

cnnModel = #a model you have defined with layers

并且假设您想要索引1,5和8的层的输出。
使用这些图层的输出从此创建新模型。

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)

使用此模型进行预测:

print(newModel.predict(inputData))

现在,“可视化”这些结果可能很棘手,因为它们可能比常规图像拥有更多的通道。

Keras通过两种方式提供CNN中间输出可视化和简单技术:

我假设您已经在keras中构建模型,如model= Sequential()CNN layer实现。

首先读取图像并将其重新Conv2d()Conv2d()需要四个维度所以, 将input_image重塑为4D [batch_size,img_height,img_width,number_of_channels],例如:

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

第一种方式:

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)

然后使用matplotlib绘制它:

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


第二种方式:

您可以使用keras后端创建函数,并将图层级别作为数值传递,如下所示:

 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 

访问链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM