Predict responses using a trained deep learning neural network
You can make predictions using a trained neural network for deep learning on
either a CPU or GPU. Using a GPU requires
Computing Toolbox™ and a CUDA® enabled NVIDIA® GPU with compute capability 3.0 or higher. Specify the hardware requirements using the
ExecutionEnvironment name-value pair argument.
YPred = predict(net,X)
YPred = predict(net,sequences)
YPred = predict(___,Name,Value)
When making predictions with sequences of different lengths, the mini-batch size can impact the amount of padding added to the input data which can result in different predicted values. Try using different values to see which works best with your network. To specify mini-batch size and padding options, use the
Load the sample data.
[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 28 is the width of the images. 1 is the number of channels and 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(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,YTrain,layers,options);
Training on single CPU. Initializing input data normalization. |========================================================================================| | Epoch | Iteration | Time Elapsed | Mini-batch | Mini-batch | Base Learning | | | | (hh:mm:ss) | Accuracy | Loss | Rate | |========================================================================================| | 1 | 1 | 00:00:00 | 11.72% | 2.2909 | 0.0100 | | 2 | 50 | 00:00:05 | 52.34% | 1.8173 | 0.0100 | | 3 | 100 | 00:00:10 | 66.41% | 1.1120 | 0.0100 | | 4 | 150 | 00:00:15 | 67.19% | 0.9866 | 0.0100 | | 6 | 200 | 00:00:21 | 73.44% | 0.7928 | 0.0100 | | 7 | 250 | 00:00:26 | 81.25% | 0.6349 | 0.0100 | | 8 | 300 | 00:00:31 | 83.59% | 0.6306 | 0.0100 | | 9 | 350 | 00:00:37 | 83.59% | 0.4726 | 0.0100 | | 11 | 400 | 00:00:41 | 92.97% | 0.3709 | 0.0100 | | 12 | 450 | 00:00:47 | 95.31% | 0.2843 | 0.0100 | | 13 | 500 | 00:00:51 | 92.19% | 0.2760 | 0.0100 | | 15 | 550 | 00:00:56 | 98.44% | 0.2187 | 0.0100 | | 16 | 600 | 00:01:01 | 96.88% | 0.2164 | 0.0100 | | 17 | 650 | 00:01:05 | 96.88% | 0.1960 | 0.0100 | | 18 | 700 | 00:01:10 | 100.00% | 0.1066 | 0.0100 | | 20 | 750 | 00:01:14 | 99.22% | 0.0850 | 0.0100 | | 21 | 800 | 00:01:19 | 99.22% | 0.1224 | 0.0100 | | 22 | 850 | 00:01:23 | 99.22% | 0.0832 | 0.0100 | | 24 | 900 | 00:01:28 | 97.66% | 0.1246 | 0.0100 | | 25 | 950 | 00:01:32 | 98.44% | 0.0821 | 0.0100 | | 26 | 1000 | 00:01:38 | 99.22% | 0.0601 | 0.0100 | | 27 | 1050 | 00:01:46 | 99.22% | 0.0679 | 0.0100 | | 29 | 1100 | 00:01:54 | 99.22% | 0.0519 | 0.0100 | | 30 | 1150 | 00:02:00 | 99.22% | 0.0590 | 0.0100 | | 30 | 1170 | 00:02:02 | 100.00% | 0.0579 | 0.0100 | |========================================================================================|
Run the trained network on a test set and predict the scores.
[XTest,YTest] = digitTest4DArrayData; YPred = predict(net,XTest);
predict, by default, uses a CUDA® enabled GPU with compute capability 3.0, when available. You can also choose to run
predict on a CPU using the
'ExecutionEnvironment','cpu' name-value pair argument.
Display the first 10 images in the test data and compare to the predictions from
ans = 10x1 categorical array 0 0 0 0 0 0 0 0 0 0
ans = 10x10 single matrix 0.9988 0.0000 0.0002 0.0006 0.0000 0.0000 0.0000 0.0000 0.0000 0.0004 0.9188 0.0000 0.0206 0.0001 0.0000 0.0002 0.0030 0.0001 0.0017 0.0554 0.9999 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.9704 0.0000 0.0000 0.0000 0.0000 0.0000 0.0038 0.0000 0.0029 0.0229 0.9775 0.0000 0.0036 0.0001 0.0000 0.0000 0.0001 0.0001 0.0186 0.0001 0.9708 0.0000 0.0004 0.0000 0.0000 0.0000 0.0028 0.0000 0.0245 0.0015 0.9921 0.0000 0.0001 0.0000 0.0000 0.0000 0.0075 0.0000 0.0004 0.0000 1.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.9594 0.0000 0.0004 0.0000 0.0000 0.0004 0.0000 0.0000 0.0002 0.0397 0.9420 0.0000 0.0050 0.0014 0.0001 0.0001 0.0352 0.0000 0.0130 0.0033
YTest contains the digits corresponding to the images in
XTest. The columns of
predict’s estimation of a probability that an image contains a particular digit. That is, the first column contains the probability estimate that the given image is digit 0, the second column contains the probability estimate that the image is digit 1, the third column contains the probability estimate that the image is digit 2, and so on. You can see that
predict’s estimation of probabilities for the correct digits are almost 1 and the probability for any other digit is almost 0.
predict correctly estimates the first 10 observations as digit 0.
Load pretrained network.
JapaneseVowelsNet is a pretrained LSTM network trained on the Japanese Vowels dataset as described in  and . It was trained on the sequences sorted by sequence length with a mini-batch size of 27.
View the network architecture.
ans = 5x1 Layer array with layers: 1 'sequenceinput' Sequence Input Sequence input with 12 dimensions 2 'lstm' LSTM LSTM with 100 hidden units 3 'fc' Fully Connected 9 fully connected layer 4 'softmax' Softmax softmax 5 'classoutput' Classification Output crossentropyex with '1' and 8 other classes
Load the test data.
Make predictions on the test data.
YPred = predict(net,XTest);
View the prediction scores for the first 10 sequences.
ans = 10x9 single matrix 0.9918 0.0000 0.0000 0.0000 0.0006 0.0010 0.0001 0.0006 0.0059 0.9868 0.0000 0.0000 0.0000 0.0006 0.0010 0.0001 0.0010 0.0105 0.9924 0.0000 0.0000 0.0000 0.0006 0.0010 0.0001 0.0006 0.0054 0.9896 0.0000 0.0000 0.0000 0.0006 0.0009 0.0001 0.0007 0.0080 0.9965 0.0000 0.0000 0.0000 0.0007 0.0009 0.0000 0.0003 0.0016 0.9888 0.0000 0.0000 0.0000 0.0006 0.0010 0.0001 0.0008 0.0087 0.9886 0.0000 0.0000 0.0000 0.0006 0.0010 0.0001 0.0008 0.0089 0.9982 0.0000 0.0000 0.0000 0.0006 0.0007 0.0000 0.0001 0.0004 0.9883 0.0000 0.0000 0.0000 0.0006 0.0010 0.0001 0.0008 0.0093 0.9959 0.0000 0.0000 0.0000 0.0007 0.0011 0.0000 0.0004 0.0019
Compare these prediction scores to the labels of these sequences. The function assigns high prediction scores to the correct class.
ans = 10x1 categorical array 1 1 1 1 1 1 1 1 1 1
sequences— Sequence or time series data
Sequence or time series data, specified as an N-by-1 cell array of numeric arrays, where N is the number of observations, a numeric array representing a single sequence, or a datastore.
For cell array or numeric array input, the dimensions of the numeric arrays containing the sequences depend on the type of data.
|Vector sequences||c-by-s matrices, where c is the number of features of the sequences and s is the sequence length.|
|2-D image sequences||h-by-w-by-c-by-s arrays, where h, w, and c correspond to the height, width, and number of channels of the images, respectively, and s is the sequence length.|
|3-D image sequences||h-by-w-by-d-by-c-by-s, where h, w, d, and c correspond to the height, width, depth, and number of channels of the 3-D images, respectively, and s is the sequence length.|
For datastore input, the datastore must return data as a cell array of sequences or a table whose first column contains sequences. The dimensions of the sequence data must correspond to the table above.
'MiniBatchSize',256specifies the mini-batch size as 256.
Specify optional comma-separated pair of
Name is the argument name and
Value is the
Name must appear inside single quotes
'Acceleration'— Performance optimization
Performance optimization, specified as the comma-separated pair consisting of
'Acceleration' and one of the following:
'auto' — Automatically apply a number of optimizations
suitable for the input network and hardware resource.
'mex' — Compile and execute a MEX function. This option is available when using a GPU only. Using a GPU requires Parallel
Computing Toolbox and a CUDA enabled NVIDIA GPU with compute capability 3.0 or higher. If Parallel
Computing Toolbox or a suitable GPU is not available, then the software returns an error.
'none' — Disable all acceleration.
The default option is
specified, MATLAB® will apply a number of compatible optimizations. If you use the
'auto' option, MATLAB does not ever generate a MEX function.
'mex' can offer performance benefits, but at the expense of an
increased initial run time. Subsequent calls with compatible parameters are faster. Use
performance optimization when you plan to call the function multiple times using new
'mex' option generates and executes a MEX function based on the network
and parameters used in the function call. You can have several MEX functions associated
with a single network at one time. Clearing the network variable also clears any MEX
functions associated with that network.
'mex' option is only available for input data specified as a
numeric array, cell array of numeric arrays, table, or image datastore. No other types
of datastore support the
'mex' option is only available when you are using a GPU. You must also have a C/C++ compiler installed. For setup instructions, see MEX Setup (GPU Coder).
'mex' acceleration does not support all layers. For a list of supported
layers, see Supported Layers (GPU Coder).
'ExecutionEnvironment'— Hardware resource
Hardware resource, specified as the comma-separated pair consisting of
'ExecutionEnvironment' and one of the following:
'auto' — Use a GPU if one is available; otherwise, use the
'gpu' — Use the GPU. Using a GPU requires
Computing Toolbox and a CUDA enabled NVIDIA GPU with compute capability 3.0 or higher. If Parallel
Computing Toolbox or a suitable GPU is not available, then the software returns an
'cpu' — Use the CPU.
'SequenceLength'— Option to pad, truncate, or split input sequences
'shortest'| positive integer
Option to pad, truncate, or split input sequences, specified as one of the following:
'longest' — Pad sequences in each mini-batch to have the same length as the longest sequence. This option does not discard any data, though padding can introduce noise to the network.
'shortest' — Truncate sequences in each mini-batch to have the same length as the shortest sequence. This option ensures that no padding is added, at the cost of discarding data.
Positive integer — For each mini-batch, pad the sequences to the nearest multiple
of the specified length that is greater than the longest sequence length in the
mini-batch, and then split the sequences into smaller sequences of the specified
length. If splitting occurs, then the software creates extra mini-batches. Use this
option if the full sequences do not fit in memory. Alternatively, try reducing the
number of sequences per mini-batch by setting the
option to a lower value.
If you specify the sequence length as a positive integer, then the software processes the smaller sequences in consecutive iterations. The network updates the network state between the split sequences.
The software pads and truncates the sequences on the right. To learn more about the effect of padding, truncating, and splitting the input sequences, see Sequence Padding, Truncation, and Splitting.
'SequencePaddingValue'— Value to pad input sequences
Value by which to pad input sequences, specified as a scalar. The option is valid only
'longest' or a positive
integer. Do not pad sequences with
NaN, because doing so can
propagate errors throughout the network.
YPred— Predicted scores or responses
Predicted scores or responses, returned as a matrix, a 4-D numeric array,
or a cell array of matrices. The format of
depends on the type of problem.
The following table describes the format for classification problems.
|Image classification||N-by-K matrix, where N is the number of observations, and K is the number of classes|
N-by-1 cell array of matrices, where N is the number of observations. The sequences are matrices with K rows, where K is the number of responses. Each sequence has the same number of time steps as the corresponding input sequence.
The following table describes the format for regression problems.
|Sequence-to-one regression||N-by-R matrix, where N is the number of observations and R is the number of responses.|
N-by-1 cell array of numeric sequences, where N is the number of observations. The sequences are matrices with R rows, where R is the number of responses. Each sequence has the same number of time steps as the corresponding input sequence.
For sequence-to-sequence regression problems with one observation,
sequences can be a matrix. In this case,
YPred is a matrix of responses.
If the image data contains
predict propagates them through the network. If the network has ReLU
layers, these layers ignore
NaNs. However, if the network does not
have a ReLU layer, then
predict returns NaNs as
All functions for deep learning training,
prediction, and validation in Deep Learning
Toolbox™ perform computations using single-precision, floating-point arithmetic. Functions
for deep learning include
software uses single-precision arithmetic when you train networks using both CPUs and
You can compute the predicted scores and the predicted classes from a trained network
You can also compute the activations from a network layer using
 M. Kudo, J. Toyama, and M. Shimbo. "Multidimensional Curve Classification Using Passing-Through Regions." Pattern Recognition Letters. Vol. 20, No. 11–13, pages 1103–1111.
 UCI Machine Learning Repository: Japanese Vowels Dataset. https://archive.ics.uci.edu/ml/datasets/Japanese+Vowels
Usage notes and limitations:
Only the syntax
YPred = predict(net,X) is
X must not have a variable size. The
size must be fixed at code generation time.
For more information about generating code for deep learning neural networks, see Workflow for Deep Learning Code Generation with MATLAB Coder (MATLAB Coder).