【发布时间】:2018-03-31 09:47:15
【问题描述】:
最近我为猫狗分类创建了基本的 CNN 模型(非常基础)。如何使用 keras 可视化这些层的输出?我为 keras 使用了 Tensorflow 后端。
【问题讨论】:
标签: python tensorflow keras classification conv-neural-network
最近我为猫狗分类创建了基本的 CNN 模型(非常基础)。如何使用 keras 可视化这些层的输出?我为 keras 使用了 Tensorflow 后端。
【问题讨论】:
标签: python tensorflow keras classification conv-neural-network
您可以定义一个模型来获取您想要查看的每一层的输出并进行预测:
假设你有完整的模型:
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()需要四个维度
因此,将您的 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
访问this链接
【讨论】: