使用matlab訓練caltech 256數據集!

1、下載數據集

caltech 256數據集官網:http://www.vision.caltech.edu/Image_Datasets/Caltech256/

2、開始訓練

所有的代碼都是基於matlab R2018b!代碼中有註解;按照下面的流程同樣可以訓練你自己的數據集!

% 數據集加載
dataset = imageDatastore('256_ObjectCategories',...
    'IncludeSubfolders',true);
% 每張圖像對應的標籤
labels = zeros(30607,1);

for i = 1:30607
    split = strsplit(dataset.Files{i,1},{'\','_','.'});
    labels(i) = str2double(split{7});
end
dataset.Labels = categorical(labels);

% 加載網絡;我這裏選擇alexnet;因爲我的電腦GPU不行;
% 也可以是vgg16或者googlenet等
net = alexnet;
% 查看網絡參數
layers = net.Layers
% 輸入層圖像尺寸
insz = layers(1).InputSize;
% 看一下自己數據集有多少個類
numclass = length(unique(labels))
% 數據集劃分:訓練集和測試集,按比例拆分ImageDatastore中的文件
[testImgs,trainImgs] = splitEachLabel(dataset,0.3,'randomized');

% 圖像增強的預處理
scaleRange = [0.9 1.1];
imageAugmenter = imageDataAugmenter(...
    'RandXReflection',true,...
    'RandXScale',scaleRange,...
    'RandYScale',scaleRange,...
    'RandYReflection',true,...
    'RandRotation',[-20,20],...
    'RandXTranslation',[-3,3],...
    'RandYTranslation',[-3,3])

% 對數據集進行打亂
% 這裏只需要對訓練集進行打亂和圖像預處理就行了;測試集就不需要了
trainImgs1 = shuffle(trainImgs);

% 這裏是對圖像進行預處理
augtrainImgs = augmentedImageDatastore(insz, trainImgs1,...
'ColorPreprocessing','gray2rgb',...
'DataAugmentation',imageAugmenter);
augtestImgs = augmentedImageDatastore(insz, testImgs,...
    'ColorPreprocessing','gray2rgb');
save('./256_Object/augTestImgs.mat','augtestImgs');

% 修改網絡
layers(end-2) = fullyConnectedLayer(numclass);
layers(end) = classificationLayer;

% 確定訓練選項
options = trainingOptions('sgdm',...
    'InitialLearnRate',0.001,...
    'MaxEpochs',15,...
    'Shuffle','every-epoch',...
    'LearnRateDropFactor',0.2,...
    'Plots','training-progress',...
    'ExecutionEnvironment','cpu')

% 開始訓練
[corel10Knet, info] = trainNetwork(augtrainImgs,layers,options);
% info中包含了所有的訓練信息,建議保存
save('./256_Object/info.mat','info');

% 保存網絡和其他參數;按自己需要保存
save('./256_Object/net_trained.mat','corel10Knet');
save('./256_Object/augtestImgs.mat','augtestImgs');
save('./256_Object/augtrainImgs.mat','augtrainImgs');

 訓練過程!都保存在info裏了,也可以自己繪製如下圖

% 繪製訓練圖
plot(info.TrainingAccuracy)
plot(info.TrainingLoss)
plot(info.BaseLearnRate)

 

 

 

3、測試訓練好的網絡

load('./256_Object/net_trained.mat');
load('./256_Object/augtestImgs.mat');
[pred,scores] = classify(corel10Knet,augtestImgs);
% 顯示混淆矩陣
confusionchart(testImgs.Labels,pred);
% 測試準確率
testaccuracy = nnz(testImgs.Labels == pred)/numel(testImgs.Labels)

% 如何使用自己訓練好的網絡進行特徵提取
% 我們拿一張圖像爲例,首先要對圖像進行預處理
% 輸入層的圖像尺寸
% 方法一
inputSize = corel10Knet.Layers(1).InputSize; % [227 227 3]:寬*高*通道
% 方法二:前提是你微調網絡
net = alexnet;
inputSize1 = net.Layers(1).InputSize


結果:testaccuracy=69%

說明:1、數據集龐大,自己電腦辣雞,選擇CPU訓練,然後訓練的批次比較少,最終的效果不是特別好,如果大家機器很好,可以調高參數,提高網絡的準確率!

           2、最好選擇VGG16或者其他的網絡進行微調,感覺效果會更好!

 

感謝各位的觀看!有問題請留言!有錯誤望各位指出!謝謝!

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章