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

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

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

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

2. 通过建立Keras的函数。

 1 from keras import backend as K
 2 from keras.models import load_model
 3 from matplotlib import pyplot as plt
 4 import cv2
 5 import numpy as np
 6 
 7 def main():
 8     model = load_model('../Project/weights.best_10-0.90.hdf5')
 9 
10     images=cv2.imread("../Project/1.jpg")
11     # cv2.imshow("Image", images)
12     cv2.waitKey(0)
13 
14     # Turn the image into an array.
15     # 根据载入的训练好的模型的配置,将图像统一尺寸
16     image_arr = cv2.resize(images, (70, 70))
17 
18     image_arr = np.expand_dims(image_arr, axis=0)
19 
20     # 第一个 model.layers[0],不修改,表示输入数据;
21     # 第二个model.layers[ ],修改为需要输出的层数的编号[]
22     layer_1 = K.function([model.layers[0].input], [model.layers[1].output])
23 
24     # 只修改inpu_image
25     f1 = layer_1([image_arr])[0]
26 
27     # 第一层卷积后的特征图展示,输出是(1,66,66,32),(样本个数,特征图尺寸长,特征图尺寸宽,特征图个数)
28     for _ in range(16):
29                 show_img = f1[:, :, :, _]
30                 show_img.shape = [66, 66]
31                 plt.subplot(4, 4, _ + 1)
32                 # plt.imshow(show_img, cmap='black')
33                 plt.imshow(show_img, cmap='gray')
34                 plt.axis('off')
35     plt.show()
36 
37 if __name__ == '__main__':
38     main()

特征图可视化结果:

猜你喜欢

转载自www.cnblogs.com/tectal/p/9426971.html
今日推荐