一、实验意义及目的
-
卷积神经网络是深度学习的基本工具,本实验要求学生掌握常用神经网络算法原理,能够利用Matlab创建和训练简单的卷积神经网络来进行深度学习分类。
-
软件要求Matlab2018a及以上版本(18a版本开始提供Deep Learning Toolbox的工具箱,正式拉开了Matlab进军深度学习领域的序幕)。
二、实验内容
创建简单的深度卷积神经网络用于图像分类。
三、实验过程
1.加载和浏览图像数据。
2.定义网络架构。
3.指定训练选项。
4.训练网络。
四、实验说明与代码
加载数字样本数据作为图像数据存储。imageDatastore根据文件夹名称自动标注图像,并将数据存储为ImageDatastore对象。通过图像数据存储可以存储大图像数据,包括无法放入内存的数据,并在卷积神经网络的训练过程中高效分批读取图像。
digitDatasetPath = fullfile(matlabroot,'toolbox','nnet','nndemos','nndatasets','DigitDataset');
imds = imageDatastore(digitDatasetPath,'IncludeSubfolders',true,'LabelSource','foldernames');
显示数据存储中的部分图像。
figure(1);
perm = randperm(10000,20);
for i = 1:20
subplot(4,5,i);
imshow(imds.Files{perm(i)});
end
图 1 随机展示的图片数据
labelcount = countEachLabel(imds);%计算每一个类别中的图像数量
img = readimage(imds,1);%在网络的输入层中指定图像的大小
numTrainFiles = 900;%将数据集划分为训练集和测试集,训练集的每个类别包含900个图像
[imdsTrain,imdsValidation] = splitEachLabel(imds,numTrainFiles,'randomize');
%定义卷积神经网络
layers = [
imageInputLayer([28 28 1])
convolution2dLayer(3,8,'padding','same')
batchNormalizationLayer
reluLayer
maxPooling2dLayer(2,'stride',2)
convolution2dLayer(3,16,'padding','same')
batchNormalizationLayer
reluLayer
maxPooling2dLayer(2,'stride',2)
convolution2dLayer(3,32,'padding','same')
batchNormalizationLayer
reluLayer
fullyConnectedLayer(10)
softmaxLayer
classificationLayer];
%指定训练选项
%学习率设置为0.04,训练轮数设置为10,每轮迭代次数为70
options = trainingOptions('sgdm',...
'InitialLearnRate',0.04,...
'MaxEpochs',10,...
'Shuffle','every-epoch',...
'ValidationData',imdsValidation,...
'ValidationFrequency',70,...
'Verbose',false,...
'Plots','training-progress');
%使用训练数据训练网络
```python
net = trainNetwork(imdsTrain,layers,options);
%对验证图像进行分类并计算准确度
YPred = classify(net,imdsValidation);
YValidation = imdsValidation.Labels;
accuracy = sum(YPred == YValidation)/numel(YValidation);
运行结果:
图 2 运行结果-1
图 3 运行结果-2