%% Construct and Train a Convolutional Neural Network for Regression
% Load sample data.

[trainImages,~,trainAngles] = 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 28 is the width of the images. 1 is the number of channels and 5000 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(12,25)
    reluLayer
    fullyConnectedLayer(1)
    regressionLayer]

%
% Set training options. Specify the solver to "Stochastic gradient descent with momentum", and the initial learn rate to 0.001.

options = trainingOptions('sgdm','InitialLearnRate',.001);

%
% Train the network.

net = trainNetwork(trainImages,trainAngles,layers,options)

%
% Run the trained network on a test set and predict the digit angles of rotation.

[testImages,~,testAngles] = digitTest4DArrayData;
predictedTestAngles = predict(net,testImages);

%
% Calculate the root-mean-square error (RMSE).

predictionError = testAngles - predictedTestAngles;
squares = predictionError.^2;
rmse = sqrt(mean(squares))

% Copyright 2012 The MathWorks, Inc.