小伙編深度學習,tensorflow用VGG19訓練,可視化每一層的輸出

一、簡介

VGG網絡在2014年的 ILSVRC localization and classification 兩個問題上分別取得了第一名和第二名。VGG網絡非常深,通常有16-19層,如果自己訓練網絡模型的話很浪費時間和計算資源。因此這裡採用一種方法獲取VGG19模型的模型數據,從而能夠更快速的應用到自己的任務中來,

本文在加載模型數據的同時,還可視化圖片在網絡傳播過程中,每一層的輸出特徵圖。讓我們能夠更直接的觀察網絡傳播的狀況。

運行環境為spyder,Python3.5,tensorflow1.2.1

模型名稱為: imagenet-vgg-verydeep-19.mat 大家可以在網上下載。

二、VGG19模型結構

模型的每一層結構如下圖所示:

小夥編深度學習,tensorflow用VGG19訓練,可視化每一層的輸出

三、代碼

這裡只給出核心的輸出圖像代碼,需要代碼的,可以留言,加入社群得到。

  1. #獲取圖像shape

  2. shape =(1,input_image.shape[0],input_image.shape[1],input_image.shape[2])

  3. #開始會話

  4. with tf.Session()as sess:

  5. image = tf.placeholder('float', shape=shape)

  6. #調用net函數

  7. nets, mean_pixel, all_layers = net(VGG_PATH, image)

  8. #減均值操作(由於VGG網絡圖片傳入前都做了減均值操作,所以這裡也用相同的預處理

  9. input_image_pre = np.array([preprocess(input_image, mean_pixel)])

  10. layers = all_layers # For all layers \n",

  11. # layers = ('relu2_1', 'relu3_1', 'relu4_1')\n",

  12. for i, layer in enumerate(layers):

  13. print("[%d/%d] %s"%(i+1, len(layers), layer))

  14. features = nets[layer].eval(feed_dict={image: input_image_pre})

  15. print(" Type of 'features' is ", type(features))

  16. print(" Shape of 'features' is %s"%(features.shape,))

  17. # Plot response \n",

  18. #畫出每一層

  19. if1:

  20. plt.figure(i+1, figsize=(10,5))

  21. plt.matshow(features[0,:,:,0], cmap=plt.cm.gray, fignum=i+1)

  22. plt.title(""+ layer)

  23. plt.colorbar()

  24. plt.show()

四、程序運行結果

1、print(weights)的結果:

小夥編深度學習,tensorflow用VGG19訓練,可視化每一層的輸出

2、程序運行最終結果:

程序開始兩層的可視化結果:

小夥編深度學習,tensorflow用VGG19訓練,可視化每一層的輸出

中間層數太多,這裡就不展示了。程序最後兩層的可視化結果:

小夥編深度學習,tensorflow用VGG19訓練,可視化每一層的輸出


分享到:


相關文章: