【问题标题】:How to visualize output of intermediate layers of convolutional neural network in keras?如何在keras中可视化卷积神经网络中间层的输出?
【发布时间】:2018-03-31 09:47:15
【问题描述】:

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

【问题讨论】:

    标签: python tensorflow keras classification conv-neural-network


    【解决方案1】:

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

    假设你有完整的模型:

    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))
    

    现在,“可视化”这些结果可能会很棘手,因为它们的通道可能比普通图像多得多。

    【讨论】:

    • 谢谢,这会有所帮助。正如你所说,这真的很棘手。他们有更多的渠道。任何建议。
    • 也许将每个通道都视为 rgb 图像?
    • 谢谢,它有效。现在我可以看到过滤器是如何工作的了。
    • :) -- 如果您认为您的问题已得到解答,请将其标记为正确答案。
    • (现在我注意到了,我想说的是:perhas将每个通道视为灰度图像)
    【解决方案2】:

    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链接

    【讨论】:

      猜你喜欢
      • 2018-01-24
      • 2017-05-20
      • 2019-09-09
      • 2018-01-26
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      • 2020-08-16
      • 1970-01-01
      相关资源
      最近更新 更多