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

特征图可视化结果:




附方法二完整代码(如果需要本例中训练好的模型,请回复):

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


猜你喜欢

转载自blog.csdn.net/u010420283/article/details/80303231