www.gusucode.com > nnet 案例源码 matlab代码程序 > nnet/ClassifyImagesUsingTrainedConvNetExample.m

    %% Classify Images Using Trained ConvNet  

%% 
% *NOTE:* Training a convolutional neural network requires Parallel
% Computing Toolbox(TM) and a CUDA(R)-enabled NVIDIA(R) GPU with compute capability
% 3.0 or higher.

%% 
% Load the sample data. 
[XTrain,TTrain] = digitTrain4DArrayData; 

%%
% |digitTrain4DArrayData| loads the digit training set as 4-D array data.
% |XTrain| is a 28-by-28-by-1-by-4940 array, where 28 is the height and
% 28 is the width of the images. 1 is the number of channels and 4940 is
% the number of synthetic images of handwritten digits. |TTrain| is a categorical
% vector containing the labels for each observation.  

%% 
% Construct the convolutional neural network architecture. 
layers = [imageInputLayer([28 28 1]);
          convolution2dLayer(5,20);
          reluLayer();
          maxPooling2dLayer(2,'Stride',2);
          fullyConnectedLayer(10);
          softmaxLayer();
          classificationLayer()];  

%% 
% Set the options to default settings for the stochastic gradient descent
% with momentum. 
options = trainingOptions('sgdm');  

%% 
% Train the network. 
rng('default')
net = trainNetwork(XTrain,TTrain,layers,options);  

%% 
% Run the trained network on a test set. 
[XTest,TTest]= digitTest4DArrayData;  
YTestPred = classify(net,XTest);  

%% 
% Display the first 10 images in the test data and compare to the classification
% from |classify|. 
[TTest(1:10,:) YTestPred(1:10,:)] 

%%
% The results from |classify| match the true digits for the first ten images.  

%% 
% Calculate the accuracy over all test data. 
accuracy = sum(YTestPred == TTest)/numel(TTest)