%% Train Residual Network
% Create and train a residual network to classify images.
% Load the digits data as in-memory numeric arrays using the digitTrain4DArrayData and digitTest4DArrayData functions.

[XTrain,YTrain] = digitTrain4DArrayData;
[XTest,YTest] = digitTest4DArrayData;

% Define the residual network. The digits data contains 28-by-28 pixel images, therefore, construct a residual network with smaller filters.

imageSize = [28 28 1];
numClasses = 10;

lgraph = resnetLayers(imageSize,numClasses, ...
    InitialStride=1, ...
    InitialFilterSize=3, ...
    InitialNumFilters=16, ...
    StackDepth=[4 3 2], ...
    NumFilters=[16 32 64]);

% Set the options to the default settings for the stochastic gradient descent with momentum. Set the maximum number of epochs at 5, and start the training with an initial learning rate of 0.1.

options = trainingOptions("sgdm", ...
    MaxEpochs=5, ...
    InitialLearnRate=0.1, ...
    Verbose=false, ...
    Plots="training-progress");

% Train the network.

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

% Test the performance of the network by evaluating the prediction accuracy of the test data. Use the classify function to predict the class label of each test image.

YPred = classify(net,XTest);

% Calculate the accuracy. The accuracy is the fraction of labels that the network predicts correctly.

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

% Copyright 2021 The MathWorks, Inc.