Matlab影象識別/檢索系列(7)-10行程式碼完成深度學習網路之取中間層資料作為特徵(轉載)
阿新 • • 發佈:2019-02-08
現在,大家都意識到深度神經網路在影象特徵提取方面具有很強的能力,儘管其解釋性不強,儘管人們對它的內部原理不十分清楚。那麼能不能取出網路中某層資料作為影象特徵而進行自己定製的其它處理呢?答案當然是肯定的。在Matlab2017b中,從網路取資料主要有兩種方法。一是使用Neural Network Toolbox的activations函式,一是匯入網路後直接使用網路某層的名字。
1.使用activations函式
%exam1.m
load digitTrainSet;
%建立CNN網路
layers = [imageInputLayer([28 28 1],'Normalization' ,'none');
convolution2dLayer(5,20);
reluLayer();
maxPooling2dLayer(2,'Stride',2);
convolution2dLayer(5,16);
reluLayer();
maxPooling2dLayer(2,'Stride',2);
fullyConnectedLayer(256);
reluLayer();
fullyConnectedLayer(10);
softmaxLayer();
classificationLayer()];
opts = trainingOptions('sgdm' );
%訓練CNN網路
net = trainNetwork(XTrain,TTrain,layers,opts);
%提取輸入X的第6層輸出資料
trainFeatures = activations(net,XTrain,6);
%訓練多分類模型
svm = fitcecoc(trainFeatures,TTrain);
load digitTestSet;
%提取測試資料的第6層輸出資料
testFeatures = activations(net,XTest,6);
%預測測試資料所屬類別
test Predictions = predict(svm,testFeatures);
%對測試資料標籤進行one-hot編碼
ttest = dummyvar(double(TTest))' ;
%對測試資料預測標籤進行one-hot編碼
tpredictions = dummyvar(double(testPredictions))';
%對混淆矩陣做圖
plotconfusion(ttest,tpredictions);
%計算準確率,即實際標籤和預測標籤相同個數的和/測試資料總數
accuracy = sum(TTest == testPredictions)/numel(TTest);
函式activations的用法是:
features = activations(net,X,layer,Name,Value)
引數中net表示建立的網路,X表示輸入資料,layer表示層數,Name和Value用來設定引數的值。函式dummyvar來自Statistics and Machine Learning Toolbox,其作用是將每個類別標籤轉換為只含有0和1的向量,即one-hot編碼。如類別1和9分別轉換為[0 1 0 0 0 0 0 0 0 0]和[0 0 0 0 0 0 0 0 0 1],這裡共有10個類,類標籤為0~9,每個類用10個0或1的數字表示,第幾類用對應位置數字為1其它為0表示。
2.直接使用層的名字
在Matlab2017b中預置了一些常用深度網路,可以函式的形式直接呼叫,如alexnet、vgg16、vgg19和googlenet,可在Neural Network Toolbox的Functions中檢視。第一次使用需要在Matlab主頁工具欄的附加功能中下載。呼叫形式很簡單,程式碼如下。
%exam2.m
unzip('MerchData.zip');
%建立影象集
images = imageDatastore('MerchData',...
'IncludeSubfolders',true,...
'LabelSource','foldernames');
%劃分影象集
[trainingImages,testImages] = splitEachLabel(images,0.7,'randomized');
%獲取訓練影象總數
numTrainImages = numel(trainingImages.Labels);
%在影象總數中隨機取16個數
idx = randperm(numTrainImages,16);
%顯示16幅影象
figure
for i = 1:16
subplot(4,4,i)
I = readimage(trainingImages,idx(i));
imshow(I)
end
%呼叫alexnet網路
net = alexnet;
%設值要用的層為第7個全連線層
layer = 'fc7';
%提取訓練影象fc7層資料
trainingFeatures = activations(net,trainingImages,layer);
%提取測試影象fc7層資料
testFeatures = activations(net,testImages,layer);
%擬合訓練影象多分類器
classifier = fitcecoc(trainingFeatures,trainingLabels, 'FitPosterior',1);
%預測測試影象的類別標籤
predictedLabels = predict(classifier,testFeatures);
%[label,NegLoss,PBScore,Posterior] = predict(classifier,testFeatures);
idx = [1 5 10 15];
figure
for i = 1:numel(idx)
subplot(2,2,i)
I = readimage(testImages,idx(i));
label = predictedLabels(idx(i));
imshow(I);
title(char(label));
end
accuracy = mean(predictedLabels == testLabels);
需要注意的是,要使用的網路層的名字可以在匯入網路後,用除錯模式檢視net變數的值,進一步看網路每層的名字。如下圖:
然後,檢視第20層,如下圖:
可見其層的名字為‘fc7’。
也可以檢視Matlab幫助文件中alexnet的網路結構,或者在Matlab的命令列視窗輸入
net = alexnet
net.Layers
結果顯示如下:
ans =
25x1 Layer array with layers:
1 'data' Image Input 227x227x3 images with 'zerocenter' normalization
2 'conv1' Convolution 96 11x11x3 convolutions with stride [4 4] and padding [0 0]
3 'relu1' ReLU ReLU
4 'norm1' Cross Channel Normalization cross channel normalization with 5 channels per element
5 'pool1' Max Pooling 3x3 max pooling with stride [2 2] and padding [0 0]
6 'conv2' Convolution 256 5x5x48 convolutions with stride [1 1] and padding [2 2]
7 'relu2' ReLU ReLU
8 'norm2' Cross Channel Normalization cross channel normalization with 5 channels per element
9 'pool2' Max Pooling 3x3 max pooling with stride [2 2] and padding [0 0]
10 'conv3' Convolution 384 3x3x256 convolutions with stride [1 1] and padding [1 1]
11 'relu3' ReLU ReLU
12 'conv4' Convolution 384 3x3x192 convolutions with stride [1 1] and padding [1 1]
13 'relu4' ReLU ReLU
14 'conv5' Convolution 256 3x3x192 convolutions with stride [1 1] and padding [1 1]
15 'relu5' ReLU ReLU
16 'pool5' Max Pooling 3x3 max pooling with stride [2 2] and padding [0 0]
17 'fc6' Fully Connected 4096 fully connected layer
18 'relu6' ReLU ReLU
19 'drop6' Dropout 50% dropout
20 'fc7' Fully Connected 4096 fully connected layer
21 'relu7' ReLU ReLU
22 'drop7' Dropout 50% dropout
23 'fc8' Fully Connected 1000 fully connected layer
24 'prob' Softmax softmax
25 'output' Classification Output crossentropyex with 'tench', 'goldfish', and 998 other classes