Note: This page has been translated by MathWorks. Click here to see

To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

To create a regression output layer with mean squared error loss, use `regressionLayer`

. If you want to use a different loss function for your
regression problems, then you can define a custom regression output layer using this
example as a guide.

This example shows how to create a custom regression output layer with the mean absolute error (MAE) loss.

To define a custom regression output layer, you can use the template provided in this example, which takes you through the following steps:

Name the layer – Give the layer a name so it can be used in MATLAB

^{®}.Declare the layer properties – Specify the properties of the layer.

Create a constructor function – Specify how to construct the layer and initialize its properties. If you do not specify a constructor function, then the software initializes the properties with

`''`

at creation.Create a forward loss function – Specify the loss between the predictions and the training targets.

Create a backward loss function – Specify the derivative of the loss with respect to the predictions.

A regression MAE layer computes the mean absolute error loss for regression problems. MAE loss is an error measure between two continuous random variables. For
predictions *Y* and training targets *T*, the MAE loss between
*Y* and *T* is given by

$$L=\frac{1}{N}{\displaystyle \sum}_{n=1}^{N}\left(\frac{1}{R}{\displaystyle \sum}_{i=1}^{R}\left|{Y}_{ni}-{T}_{ni}\right|\right),$$

where *N* is the number of observations and
*R* is the number of responses.

Copy the regression output layer template into a new file in MATLAB. This template outlines the structure of a regression output layer and includes the functions that define the layer behavior.

classdef myRegressionLayer < nnet.layer.RegressionLayer properties % (Optional) Layer properties. % Layer properties go here. end methods function layer = myRegressionLayer() % (Optional) Create a myRegressionLayer. % Layer constructor function goes here. end function loss = forwardLoss(layer, Y, T) % Return the loss between the predictions Y and the % training targets T. % % Inputs: % layer - Output layer % Y – Predictions made by network % T – Training targets % % Output: % loss - Loss between Y and T % Layer forward loss function goes here. end function dLdY = backwardLoss(layer, Y, T) % Backward propagate the derivative of the loss function. % % Inputs: % layer - Output layer % Y – Predictions made by network % T – Training targets % % Output: % dLdY - Derivative of the loss with respect to the predictions Y % Layer backward loss function goes here. end end end

First, give the layer a name. In the first line of the class file, replace the
existing name `myRegressionLayer`

with
`maeRegressionLayer`

.

classdef maeRegressionLayer < nnet.layer.RegressionLayer ... end

Next, rename the `myRegressionLayer`

constructor function (the first
function in the `methods`

section) so that it has the same name as the
layer.

methods function layer = maeRegressionLayer() ... end ... end

Save the layer class file in a new file named
`maeRegressionLayer.m`

. The file name must match the layer
name. To use the layer, you must save the file in the current folder or in a folder
on the MATLAB path.

Declare the layer properties in the `properties`

section.

By default, custom output layers have the following properties:

`Name`

– Layer name, specified as a character vector or a string scalar. To include a layer in a layer graph, you must specify a nonempty unique layer name. If you train a series network with the layer and`Name`

is set to`''`

, then the software automatically assigns a name to the layer at training time.`Description`

– One-line description of the layer, specified as a character vector or a string scalar. This description appears when the layer is displayed in a`Layer`

array. If you do not specify a layer description, then the software displays`"Classification Output"`

or`"Regression Output"`

.`Type`

– Type of the layer, specified as a character vector or a string scalar. The value of`Type`

appears when the layer is displayed in a`Layer`

array. If you do not specify a layer type, then the software displays the layer class name.

Custom classification layers also have the following property:

`Classes`

– Classes of the output layer, specified as a categorical vector, string array, cell array of character vectors, or`'auto'`

. If`Classes`

is`'auto'`

, then the software automatically sets the classes at training time. If you specify the string array or cell array of character vectors`str`

, then the software sets the classes of the output layer to`categorical(str,str)`

. The default value is`'auto'`

.

Custom regression layers also have the following property:

`ResponseNames`

– Names of the responses, specified a cell array of character vectors or a string array. At training time, the software automatically sets the response names according to the training data. The default is`{}`

.

If the layer has no other properties, then you can omit the `properties`

section.

The layer does not require any additional properties, so you can remove the
`properties`

section.

Create the function that constructs the layer and initializes the layer properties. Specify any variables required to create the layer as inputs to the constructor function.

To initialize the `Name`

property at creation, specify the input
argument `name`

. Add a comment to the top of the function that explains
the syntax of the function.

function layer = maeRegressionLayer(name) % layer = maeRegressionLayer(name) creates a % mean-absolute-error regression layer and specifies the layer % name. ... end

Replace the comment `% Layer constructor function goes here`

with
code that initializes the layer properties.

Give the layer a one-line description by setting the
`Description`

property of the layer. Set the
`Name`

property to the input argument `name`

.
Set the description to describe the type of layer and its size.

```
function layer = maeRegressionLayer(name)
% layer = maeRegressionLayer(name) creates a
% mean-absolute-error regression layer and specifies the layer
% name.
% Set layer name.
layer.Name = name;
% Set layer description.
layer.Description = 'Mean absolute error';
end
```

Create a function named `forwardLoss`

that returns the MAE loss
between the predictions made by the network and the training targets. The syntax for
`forwardLoss`

is ```
loss = forwardLoss(layer, Y,
T)
```

, where `Y`

is the output of the previous layer and
`T`

contains the training targets.

For regression problems, the dimensions of `T`

also depend on the type of
problem.

Regression Task | Input Size | Observation Dimension |
---|---|---|

2-D image regression | 1-by-1-by-R-by-N, where
R is the number of responses and
N is the number of observations. | 4 |

2-D Image-to-image regression | h-by-w-by-c-by-`N` ,
where h, w, and
c are the height, width, and number of channels
of the output respectively, and N is the number of
observations. | 4 |

3-D image regression | 1-by-1-by-1-by-R-by-N, where
R is the number of responses and
N is the number of observations. | 5 |

3-D Image-to-image regression | h-by-w-by-d-by-c-by-`N` ,
where h, w, d,
and c are the height, width, depth, and number of
channels of the output respectively, and N is the
number of observations. | 5 |

Sequence-to-one regression | R-by-N, where
R is the number of responses and
N is the number of observations. | 2 |

Sequence-to-sequence regression | R-by-N-by-S,
where R is the number of responses,
N is the number of observations, and
S is the sequence length. | 2 |

For example, if the network defines an image regression network with one response and has
mini-batches of size 50, then `T`

is a 4-D array of size
1-by-1-by-1-by-50.

The size of `Y`

depends on the output of the previous layer. To ensure
that `Y`

is the same size as `T`

, you must include a layer
that outputs the correct size before the output layer. For example, for image regression
with *R* responses, to ensure that `Y`

is a 4-D array of
the correct size, you can include a fully connected layer of size *R*
before the output layer.

A regression MAE layer computes the mean absolute error loss for regression problems. MAE loss is an error measure between two continuous random variables. For
predictions *Y* and training targets *T*, the MAE loss between
*Y* and *T* is given by

$$L=\frac{1}{N}{\displaystyle \sum}_{n=1}^{N}\left(\frac{1}{R}{\displaystyle \sum}_{i=1}^{R}\left|{Y}_{ni}-{T}_{ni}\right|\right),$$

where *N* is the number of observations and
*R* is the number of responses.

The inputs `Y`

and `T`

correspond to
*Y* and *T* in the equation, respectively. The
output `loss`

corresponds to *L*. To ensure that
`loss`

is scalar, output the mean loss over the mini-batch. Add a
comment to the top of the function that explains the syntaxes of the function.

```
function loss = forwardLoss(layer, Y, T)
% loss = forwardLoss(layer, Y, T) returns the MAE loss between
% the predictions Y and the training targets T.
% Calculate MAE.
R = size(Y,3);
meanAbsoluteError = sum(abs(Y-T),3)/R;
% Take mean over mini-batch.
N = size(Y,4);
loss = sum(meanAbsoluteError)/N;
end
```

Create the backward loss function.

Create a function named `backwardLoss`

that returns the derivatives
of the MAE loss with respect to the predictions `Y`

. The syntax for
`backwardLoss`

is ```
loss = backwardLoss(layer, Y,
T)
```

, where `Y`

is the output of the previous layer and
`T`

contains the training targets.

The dimensions of `Y`

and `T`

are the same as the
inputs in `forwardLoss`

.

The derivative of the MAE loss with respect to the predictions *Y* is
given by

$$\frac{\partial L}{\partial {Y}_{i}}=\frac{1}{NR}\text{sign}({Y}_{i}-{T}_{i}),$$

where *N* is the number of observations and *R* is
the number of responses. Add a comment to the top of the function that explains the
syntaxes of the function.

```
function dLdY = backwardLoss(layer, Y, T)
% Returns the derivatives of the MAE loss with respect to the predictions Y
R = size(Y,3);
N = size(Y,4);
dLdY = sign(Y-T)/(N*R);
end
```

View the completed regression output layer class file.

classdef maeRegressionLayer < nnet.layer.RegressionLayer % Example custom regression layer with mean-absolute-error loss. methods function layer = maeRegressionLayer(name) % layer = maeRegressionLayer(name) creates a % mean-absolute-error regression layer and specifies the layer % name. % Set layer name. layer.Name = name; % Set layer description. layer.Description = 'Mean absolute error'; end function loss = forwardLoss(layer, Y, T) % loss = forwardLoss(layer, Y, T) returns the MAE loss between % the predictions Y and the training targets T. % Calculate MAE. R = size(Y,3); meanAbsoluteError = sum(abs(Y-T),3)/R; % Take mean over mini-batch. N = size(Y,4); loss = sum(meanAbsoluteError)/N; end function dLdY = backwardLoss(layer, Y, T) % Returns the derivatives of the MAE loss with respect to the predictions Y R = size(Y,3); N = size(Y,4); dLdY = sign(Y-T)/(N*R); end end end

For GPU compatibility, the layer functions must support inputs
and return outputs of type `gpuArray`

. Any other functions the layer uses
must do the same. Many MATLAB built-in functions support `gpuArray`

input arguments. If you call any of these functions with at least one
`gpuArray`

input, then the function executes on the GPU and returns a
`gpuArray`

output. For a list of functions that execute on a GPU, see
Run MATLAB Functions on a GPU (Parallel Computing Toolbox). To use a GPU for deep
learning, you must also have a CUDA^{®} enabled NVIDIA^{®} GPU with compute capability 3.0 or higher. For more information on working with GPUs in MATLAB, see GPU Computing in MATLAB (Parallel Computing Toolbox).

The MATLAB functions used in `forwardLoss`

, and
`backwardLoss`

in `maeRegressionLayer`

all support
`gpuArray`

inputs, so the layer is GPU compatible.

Check the layer validity of the custom classification output layer `maeRegressionLayer`

.

Define a custom mean absolute error regression layer. To create this layer, save the file `maeRegressionLayer.m`

in the current folder. Create an instance of the layer.

`layer = maeRegressionLayer('mae');`

Check the layer is valid using `checkLayer`

. Specify the valid input size to be the size of a single observation of typical input to the layer. The layer expects a 1-by-1-by-R-by-*N* array inputs, where R is the number of responses, and *N* is the number of observations in the mini-batch.

```
validInputSize = [1 1 10];
checkLayer(layer,validInputSize,'ObservationDimension',4);
```

Skipping GPU tests. No compatible GPU device found. Running nnet.checklayer.OutputLayerTestCase .......... ... Done nnet.checklayer.OutputLayerTestCase __________ Test Summary: 13 Passed, 0 Failed, 0 Incomplete, 4 Skipped. Time elapsed: 0.20535 seconds.

The test summary reports the number of passed, failed, incomplete, and skipped tests.

You can use a custom output layer in the same way as any other output layer in Deep Learning Toolbox. This section shows how to create and train a network for regression using the custom output layer you created earlier.

The example constructs a convolutional neural network architecture, trains a network, and uses the trained network to predict angles of rotated, handwritten digits. These predictions are useful for optical character recognition.

Load the example training data.

[trainImages,~,trainAngles] = digitTrain4DArrayData;

Create a layer array including the regression output layer `maeRegressionLayer`

.

```
layers = [
imageInputLayer([28 28 1])
convolution2dLayer(5,20)
batchNormalizationLayer
reluLayer
fullyConnectedLayer(1)
maeRegressionLayer('mae')]
```

layers = 6x1 Layer array with layers: 1 '' Image Input 28x28x1 images with 'zerocenter' normalization 2 '' Convolution 20 5x5 convolutions with stride [1 1] and padding [0 0 0 0] 3 '' Batch Normalization Batch normalization 4 '' ReLU ReLU 5 '' Fully Connected 1 fully connected layer 6 'mae' Regression Output Mean absolute error

Set the training options and train the network.

```
options = trainingOptions('sgdm');
net = trainNetwork(trainImages,trainAngles,layers,options);
```

Training on single CPU. Initializing input data normalization. |========================================================================================| | Epoch | Iteration | Time Elapsed | Mini-batch | Mini-batch | Base Learning | | | | (hh:mm:ss) | RMSE | Loss | Rate | |========================================================================================| | 1 | 1 | 00:00:00 | 28.21 | 25.1 | 0.0100 | | 2 | 50 | 00:00:07 | 14.21 | 11.1 | 0.0100 | | 3 | 100 | 00:00:13 | 13.16 | 10.1 | 0.0100 | | 4 | 150 | 00:00:18 | 10.14 | 7.8 | 0.0100 | | 6 | 200 | 00:00:23 | 9.87 | 7.3 | 0.0100 | | 7 | 250 | 00:00:28 | 10.05 | 7.4 | 0.0100 | | 8 | 300 | 00:00:32 | 9.01 | 7.2 | 0.0100 | | 9 | 350 | 00:00:37 | 9.26 | 7.2 | 0.0100 | | 11 | 400 | 00:00:42 | 9.40 | 7.3 | 0.0100 | | 12 | 450 | 00:00:47 | 8.40 | 6.3 | 0.0100 | | 13 | 500 | 00:00:53 | 8.74 | 5.7 | 0.0100 | | 15 | 550 | 00:01:00 | 8.97 | 6.3 | 0.0100 | | 16 | 600 | 00:01:08 | 8.38 | 6.0 | 0.0100 | | 17 | 650 | 00:01:13 | 8.73 | 6.5 | 0.0100 | | 18 | 700 | 00:01:18 | 7.83 | 5.7 | 0.0100 | | 20 | 750 | 00:01:24 | 7.00 | 5.2 | 0.0100 | | 21 | 800 | 00:01:29 | 7.59 | 5.4 | 0.0100 | | 22 | 850 | 00:01:37 | 7.02 | 5.7 | 0.0100 | | 24 | 900 | 00:01:45 | 7.70 | 5.5 | 0.0100 | | 25 | 950 | 00:01:52 | 7.45 | 5.2 | 0.0100 | | 26 | 1000 | 00:01:59 | 7.69 | 5.8 | 0.0100 | | 27 | 1050 | 00:02:08 | 8.25 | 6.2 | 0.0100 | | 29 | 1100 | 00:02:17 | 8.82 | 7.0 | 0.0100 | | 30 | 1150 | 00:02:24 | 6.42 | 4.8 | 0.0100 | | 30 | 1170 | 00:02:27 | 6.31 | 4.7 | 0.0100 | |========================================================================================|

Evaluate the network performance by calculating the prediction error between the predicted and actual angles of rotation.

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

Calculate the number of predictions within an acceptable error margin from the true angles. Set the threshold to be 10 degrees and calculate the percentage of predictions within this threshold.

thr = 10; numCorrect = sum(abs(predictionError) < thr); numTestImages = size(testImages,4); accuracy = numCorrect/numTestImages

accuracy = 0.7662

`assembleNetwork`

| `checkLayer`

| `regressionLayer`

- Define Custom Deep Learning Layers
- Check Layer Validity
- Define Custom Classification Output Layer
- Define Custom Weighted Classification Layer
- Define Custom Deep Learning Layer with Learnable Parameters
- Define Custom Deep Learning Layer with Multiple Inputs
- List of Deep Learning Layers
- Deep Learning Tips and Tricks