1. 程式人生 > >【caffe-windows】 caffe-master 之 卷積核可視化(利用matlab)

【caffe-windows】 caffe-master 之 卷積核可視化(利用matlab)

前期準備,需要兩個東西
1. 模型的描述檔案 deploy.prototxt
2. 模型本身lenet_iter_10000.caffemodel (此處用的examples中的mnist裡的)

第一步:

在建立D:\caffe-master\matlab\demo 下建立 visualizing.m

clc
clear
addpath('..') % 加入+caffe路徑  
caffe.set_mode_cpu() ;% 設定CPU模式  
model = 'D:/caffe-master/examples/mnist/lenet.prototxt'; % 模型描述  
weights = 'D:/caffe-master/examples/mnist/lenet_iter_10000.caffemodel'
; % 引數 net = caffe.Net(model,'test'); % 讀取net weight_partvisual( net, 1,1) % 呼叫部分顯示函式 weight_partvisual( net,layer_num ,channels_num ) % layer_num是第幾個卷積層, channels_num 表示 % 顯示第幾個通道的卷積核,取值範圍為 (0,上一層的特徵圖數)

第二步:

在建立D:\caffe-master\matlab\demo 下建立weight_partvisual.m

function [  ] = weight_partvisual( net,layer_num ,channels_num )  
layers=net.layer_names;  
convlayer=[];  
for i=1:length(layers)  
    if strcmp(layers{i}(1:3),'con')  
        convlayer=[convlayer;layers{i}];  
    end  
end  
w=net.layers(convlayer(layer_num,:)).params(1).get_data();  
b=net.
layers(convlayer(layer_num,:)).params(2).get_data(); w=w-min(w(:)); w=w/max(w(:))*255; weight=w(:,:,channels_num,:);%四維,核長*核寬*核左邊輸入*核右邊輸出(核個數) [kernel_r,kernel_c,input_num,kernel_num]=size(w); map_row=ceil(sqrt(kernel_num));%行數 map_col=map_row;%列數 weight_map=zeros(kernel_r*map_row,kernel_c*map_col); kernelcout_map=1; for i=0:map_row-1 for j=0:map_col-1 if kernelcout_map<=kernel_num weight_map(i*kernel_r+1+i:(i+1)*kernel_r+i,j*kernel_c+1+j:(j+1)*kernel_c+j)=weight(:,:,:,kernelcout_map); kernelcout_map=kernelcout_map+1; end end end figure hAxe=axes('Parent',gcf,... % 設定新的axe, 將'parent' 屬性設定為當前視窗gcf 'Units','pixels',... %設定單位為pixels 'Position',[500 0 605 705]); % 指定axe的位置 left和bottom設定了axe的左下角座標,width和height設定了視窗的寬度和高度 axes(hAxe); imshow(uint8(weight_map)) str1=strcat('weight num:',num2str(kernelcout_map-1)); title(str1) end

執行 visualizing.m

結果如圖:
這裡寫圖片描述

感覺看不出什麼規律來,是否因為mnist影象太小? 而像訓練imagenet時模型輸入是 256*256,因此訓練得到的卷積核看起來有一些規律(類似邊緣)。

PS: 這裡用的是將 權值(w -min(w) / max(w) ) *255
這個原理沒搞明白,如果有清楚的同學告訴我吧,THX~