%% Train Convolutional Neural Network Using Data in an Array
% Load the sample data, which consists of synthetic images of handwritten numbers.

[XTrain,YTrain] = digitTrain4DArrayData;

% digitTrain4DArrayData loads the digit training set as 4-D array data. XTrain is a 28-by-28-by-1-by-5000 array, where:
% 28 is the height and width of the images.
% 1 is the number of channels
% 5000 is the number of synthetic images of handwritten digits.
% YTrain is a categorical vector containing the labels for each observation.
% Construct the convolutional neural network architecture.

layers = [
    imageInputLayer([28 28 1])
    
    convolution2dLayer(3,8,'Padding','same')
    batchNormalizationLayer
    reluLayer       
    convolution2dLayer(3,16,'Padding','same','Stride',2)
    batchNormalizationLayer
    reluLayer   
    convolution2dLayer(3,32,'Padding','same','Stride',2)
    batchNormalizationLayer
    reluLayer   
        
    fullyConnectedLayer(10)
    softmaxLayer
    classificationLayer];

% Set the training options for stochastic gradient descent with momentum.

options = trainingOptions('sgdm', ...
    'MaxEpochs',5, ...
    'Verbose',0, ...
    'Plots','training-progress');

% Train the network.

net = trainNetwork(XTrain,YTrain,layers,options);

% Run the trained network on a test set and predict the image labels.

[XTest,YTest] = digitTest4DArrayData;
YPred = classify(net,XTest);

% Calculate the accuracy.

accuracy = sum(YPred==YTest)/numel(YTest)

% Copyright 2012 The MathWorks, Inc.