Keras中间层输出的两种方式,及特征图可视化

训练好的模型,想要输入中间层的特征图,有两种方式:

1. 通过model.get_layer的方式。创建新的模型,输出为你要的层的名字。

创建模型,debug状态可以看到模型中,base_model/layers,图中红框即为layer名字,根据你想输出的层填写。最后网络feed数据后,输出的就是中间层结果。

2. 通过建立Keras的函数。

from keras import backend as K
model = load_model('data/checkpoints/inception.026-1.07.hdf5') #replaced by your model name
layer_1 = K.function([model.layers[0].input], [model.layers[1].output])#第一个 model.layers[0],不修改,表示输入数据;第二个model.layers[you wanted],修改为你需要输出的层数的编号
f1 = layer_1([input_image])[0]#只修改inpu_image
#第一层卷积后的特征图展示,输出是(1,149,149,32),(样本个数,特征图尺寸长,特征图尺寸宽,特征图个数)
for _ in range(32):
            show_img = f1[:, :, :, _]
            show_img.shape = [149, 149]
            plt.subplot(4, 8, _ + 1)
            plt.imshow(show_img, cmap='gray')
            plt.axis('off')
plt.show()

特征图可视化结果:

 

 

附方法二完整代码(本例中训练好的模型和代码的百度网盘地址:链接:https://pan.baidu.com/s/1KdXNNFpsl2TggxNzOMk2dA 密码:8m70)

 

"""
Classify a few images through our CNN.
"""
import numpy as np
from processor import process_image
from keras.models import load_model
from keras import backend as K
import matplotlib.pyplot as plt
import cv2

def main():
    model = load_model('data/checkpoints/inception.026-1.07.hdf5') #replaced by your model name
    # Get all our test images.
    image='v_ApplyLipstick_g01_c01-0105.jpg'
    images=cv2.imread('v_ApplyLipstick_g01_c01-0105.jpg')
    cv2.imshow("Image", images)
    cv2.waitKey(0)
    # Turn the image into an array.
    image_arr = process_image(image, (299, 299, 3))# 根据载入的训练好的模型的配置,将图像统一尺寸
    image_arr = np.expand_dims(image_arr, axis=0)

# 设置可视化的层
    layer_1 = K.function([model.layers[0].input], [model.layers[1].output])
    f1 = layer_1([image_arr])[0]
    for _ in range(32):
        show_img = f1[:, :, :, _]
        show_img.shape = [149, 149]
        plt.subplot(4, 8, _ + 1)
        plt.subplot(4, 8, _ + 1)
        plt.imshow(show_img, cmap='gray')
        plt.axis('off')
    plt.show()
    # conv layer: 299
    layer_1 = K.function([model.layers[0].input], [model.layers[299].output])
    f1 = layer_1([image_arr])[0]
    for _ in range(81):
        show_img = f1[:, :, :, _]
        show_img.shape = [8, 8]
        plt.subplot(9, 9, _ + 1)
        plt.imshow(show_img, cmap='gray')
        plt.axis('off')
    plt.show()
    print('This is the end !')

if __name__ == '__main__':
    main()

 

 

 

  • 21
    点赞
  • 73
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 28
    评论
评论 28
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Briwisdom

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值