1. 程式人生 > >Keras視覺化神經網路的中間層結果

Keras視覺化神經網路的中間層結果

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

複製程式碼

特徵圖視覺化結果: