1. 程式人生 > >caffe學習筆記14-caffe視覺化特徵與權重

caffe學習筆記14-caffe視覺化特徵與權重

test_visual.m :

clear;

clc;
close all;
addpath('matlab');
caffe.set_mode_cpu();
model = '/home/nielsen/caffe-new/examples/nielsen_googlenet/caffemodel/deploy_hash3_three_48.prototxt';  %定義測試的網路結構
weights = '/home/nielsen/caffe-new/examples/nielsen_googlenet/caffemodel/final/nielsen_googlenet_cifar10_hash3_three_48_iter_75000.caffemodel'; %模型權重
net = caffe.Net(model, weights, 'test');
%fprintf('Load net done. Net layers : ');
%net.layer_names     %列印權重層名字
%fprintf('Net blobs : '); 
%net.blob_names     %列印特徵圖層名字
fprintf('Now preparing data...\n');
im = imread('/home/nielsen/caffe-new/examples/images/cat.jpg'); %需要提取特徵和權重的圖片路徑
figure;imshow(im);title('Original Image');
% d = load('/home/nielsen/caffe-new/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat'); %均值檔案,.mat格式
% mean_data = d.mean_data;
d =  caffe.io.read_mean('/home/nielsen/caffe-new/data/cifar10/cifar10_train_mean.binaryproto');
mean_data = d;
IMAGE_DIM = 256;
CROPPED_DIM = 224;
% Convert an image returned by Matlab's imread to im_data in caffe's data
% format: W x H x C with BGR channels
im_data = im(:, :, [3, 2, 1]);  % permute channels from RGB to BGR
im_data = permute(im_data, [2, 1, 3]);  % flip width and height
im_data = single(im_data);  % convert from uint8 to single
im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');  % resize im_data
im_data = im_data - mean_data;  % subtract mean_data (already in W x H x C, BGR)
im = imresize(im_data, [CROPPED_DIM CROPPED_DIM], 'bilinear');  % resize im_data
km = cat(4, im, im, im, im, im);
pm = cat(4, km, km);
input_data = {pm};
%前向運算 單張圖片
scores = net.forward(input_data); %res = net.forward({img}); %前向計算,提取單個特徵
score = scores{2}; %2在net的outputs裡面看,等價prob = net.blobs('prob').get_data();
score = mean(score, 2);  % take average scores over 10 crops //crop裁剪的意思 size=10
[maxscore, maxindex] = max(score);
%得到分類準確度
%prob = net.blobs('prob').get_data();
%net.blobs(’blob_names‘).get_data();取出特徵
%net.layers('layer_names').params(1).get_data();取出權重是1
%用標號的形式,標號在net的net.layer_names和net.blob_names檢視,推薦用名字形式
%取出權值
% conv1_layer = net.layer_vec(1);
% blob1 = conv1_layer.params(1);
% w = blob1.get_data();
% fprintf('Conv1 Weight shape: ');
%上面四行等價於net.layers('conv1/7x7_s2').params(1).get_data();
% size(w)
% visualize_weights(w, 1);
%取出特徵
% fm_data = net.blob_vec(1); 
% d1 = fm_data.get_data();
%上面兩行等價於
%顯示data層輸入圖
feature_data = net.blobs('data').get_data();
fprintf('Data size = ');
size(feature_data)
visualize_feature_maps(feature_data, 1); %呼叫visualize_feature_maps(w,s)函式,s預設為1
%--------------------------------
%test顯示特徵 feature_name 
feature_conv1 = net.blobs('conv1/7x7_s2').get_data();
fprintf('Feature map  size = ');
size(feature_conv1)
visualize_feature_maps(feature_conv1, 1);
%test顯示權重 weight_name
weight_conv1 = net.layers('conv1/7x7_s2').params(1).get_data();
fprintf('Weight shape: ');
size(weight_conv1);
visualize_weights(weight_conv1, 1);