1、读取数据 digitDatasetPath=fullfile(matlabroot,'toolbox','nnet','nndemos','nndatasets','DigitDataset'); imds=imageDatastore(digitDatasetPath,'IncludeSubfolders',true,'LabelSource','foldernames'); numTrainingFiles=0.75; [imdsTrain,imdsTest]=splitEachLabel(imds,numTrainingFiles,'randomized'); 2、神经网络架构 layers=[... imageInputLayer([28 28 1]); convolution2dLayer(5,6,'Stride',1,'Padding','same'); reluLayer maxPooling2dLayer(2,'Stride',2,'Padding','same') convolution2dLayer(5,16,'Stride',1,'Padding','same'); reluLayer maxPooling2dLayer(2,'Stride',2,'Padding','same') fullyConnectedLayer(120) reluLayer fullyConnectedLayer(84) reluLayer fullyConnectedLayer(10) softmaxLayer classificationLayer ]; 3、超参数设置 options=trainingOptions('adam',... 'ExecutionEnvironment','auto','MaxEpochs',30,... 'InitialLearnRate',1e-3,'Verbose',false,'Plots','training-progress'); 4、神经网络训练 net=trainNetwork(imdsTrain,layers,options); 5、预测和输出 Ypred=classify(net, imdsTest); YTest=imdsTest.Labels; accuracy=sum(Ypred==YTest)/numel(YTest) fprintf('精确值为:%5.2f%%\n',accuracy*100); clear I=imread('风扇.png'); net = squeezenet; %net = resnet50('Weights','none') inputSize=net.Layers(1).InputSize; I_resize=imresize(I,inputSize(1:2)); label=classify(net,I_resize,'ExecutionEnvironment','cpu'); 6、输出图片 figure subplot(1,4,1),plot(layerGraph(net.Layers)); subplot(1,4,2),imshow(I); subplot(1,4,3),imshow(I_resize); subplot(1,4,4),imshow(I_resize);title(string(label))