深度学习Alexnet网络对图像进行分类/预测(迁移学习)

众所周知,在MATLAB里面非常方便对各种算法和技术进行可行性实验,前几个月也很好奇用深度学习对图像进行分类,幸好新版本的MATLAB 2017能够对深度学习提供支持:D,现在抽空把代码分享出来与大家共享~

图像数据集用的是我这边博客里面的:http://blog.csdn.net/cuixing001/article/details/70908064或者百度网盘下载,链接:https://pan.baidu.com/s/1i5OhC7z 密码: utn7

本文快速的用MATLAB对自己的图像数据集进行训练和分类,小伙伴们当然也可以改成自己的试试啦~\(≧▽≦)/~,效果非常不错,利用预训练的alexnet网络对新图像集进行迁移学习,结果全部分类正确,达到100%的正确率~

话不多说,上代码和图:

function predict_transfer_alexnet()
net = alexnet;% 深度学习alexnet经典网络结构,没有的可以去matlab center下载
trainsferLayer = net.Layers(1:end-3);

imds = imageDatastore('F:\svm_images\train_images',...
    'includeSubfolders',true,...
    'labelsource','foldernames','ReadFcn',@IMAGERESIZE);
T = countEachLabel(imds);
disp(T);
[imdsTrain,imdsTest] = splitEachLabel(imds,0.75);% 75%的数据为训练数据,其余的为测试数据

%% train
layers = [trainsferLayer;
    fullyConnectedLayer(5,'WeightLearnRateFactor',50,'BiasLearnRateFactor',50);%注意第一个参数为类别的数量,我这里是5
    softmaxLayer();
    classificationLayer()];
options = trainingOptions('sgdm',...
    'Maxepochs',5,...
    'InitialLearnRate',0.0001);
network = trainNetwork(imdsTrain,layers,options);

%% predict
predictLabels = classify(network,imdsTest);
testLabels = imdsTest.Labels;

accuracy = sum(predictLabels == testLabels)/numel(predictLabels);
disp(['accuracy:',num2str(accuracy)]); % 输出预测精度结果

end


上面代码第5行函数imageDatastore是个非常有用的函数,支持大数据集的图像,而且图像类别啥的都能够清楚的记录;输入参数'ReadFcn'我调用的是IMAGERESIZE自定义函数,主要作用是把自己的图像resize成227*227*3的,因为alexnet输入层大小是227*227*3的,所以必须弄成这个大小。下面给出自定义的IMAGERESIZE的函数:

function output = IMAGERESIZE(input)
input = imread(input);
if numel(size(input)) == 2
    input = cat(3,input,input,input);% 转成3通道的
end
output = imresize(input,[227,227]);




猜你喜欢

转载自blog.csdn.net/cuixing001/article/details/75807845