caffe特徵層可視化

#參考1:https://blog.csdn.net/sushiqian/article/details/78614133
#參考2:https://blog.csdn.net/thy_2014/article/details/51659300
#
coding=utf-8 import numpy as np import matplotlib.pyplot as plt import os import sys sys.path.append("/home/wit/caffe/python") sys.path.append("/home/wit/caffe/python/caffe") import caffe deploy_file_name = '/home/wit/wjx/MobileNetSSD_deploy.prototxt' model_file_name = '/home/wit/wjx/mobilenet_iter_25000.caffemodel' test_img = "/home/wit/wjx/src.jpg" #編寫一個函數,用於顯示各層的參數,padsize用於設置圖片間隔空隙,padval用於調整亮度 def show_data(data, padsize=1, padval=0, name = 'conv0'): #歸一化 data -= data.min() data /= data.max() #根據data中圖片數量data.shape[0],計算最後輸出時每行每列圖片數n n = int(np.ceil(np.sqrt(data.shape[0]))) # padding = ((圖片個數維度的padding),(圖片高的padding), (圖片寬的padding), ....) padding = ((0, n ** 2 - data.shape[0]), (0, padsize), (0, padsize)) + ((0, 0),) * (data.ndim - 3) data = np.pad(data, padding, mode='constant', constant_values=(padval, padval)) # 先將padding後的data分紅n*n張圖像 data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1))) # 再將(n, W, n, H)變換成(n*w, n*H) data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:]) plt.set_cmap('gray') plt.imshow(data) plt.imsave(name+'.jpg',data) if __name__ == '__main__': deploy_file = deploy_file_name model_file = model_file_name #若是是用了GPU #caffe.set_mode_gpu() #初始化caffe net = caffe.Net(deploy_file, model_file, caffe.TEST) #數據輸入預處理 # 'data'對應於deploy文件: # input: "data" transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape}) # python讀取的圖片文件格式爲H×W×K,需轉化爲K×H×W transformer.set_transpose('data', (2, 0, 1)) # python中將圖片存儲爲[0, 1] # 若是模型輸入用的是0~255的原始格式,則須要作如下轉換 transformer.set_raw_scale('data', 255) # caffe中圖片是BGR格式,而原始格式是RGB,因此要轉化 transformer.set_channel_swap('data', (2, 1, 0)) # 將輸入圖片格式轉化爲合適格式(與deploy文件相同) net.blobs['data'].reshape(1, 3, 300, 300) #讀取圖片 #參數color: True(default)是彩色圖,False是灰度圖 img = caffe.io.load_image(test_img,color=True) # 數據輸入、預處理 net.blobs['data'].data[...] = transformer.preprocess('data', img) # 前向迭代,即分類 out = net.forward() # 輸出結果爲各個可能分類的機率分佈(deploy中最後一層) predicts = out['detection_out'] print "Prob:" print predicts #最可能分類 predict = predicts.argmax() print "Result:" print predict for layer_name, blob in net.blobs.iteritems(): print layer_name + '\t' + str(blob.data.shape) #---------------------------- 顯示特徵圖 ------------------------------- feature = net.blobs['conv1'].data print(feature.shape) feature = feature.reshape(64,150,150) show_data(feature, padsize=2, padval=0, name='conv1')
相關文章
相關標籤/搜索