predictAndUpdateState
(Not recommended) Predict responses using a trained recurrent neural network and update the network state
predictAndUpdateState
is not recommended. Instead, use the
predict
function and use
the state output to update the State
property of the neural network. For more information,
see Version
History.
Syntax
Description
You can make predictions using a trained deep learning network on either a CPU
or GPU. Using a GPU requires
a Parallel Computing Toolbox™ license and a supported GPU device. For information about supported devices, see
GPU Computing Requirements (Parallel Computing Toolbox). Specify the hardware requirements using the ExecutionEnvironment
namevalue argument.
[
predicts responses for data in updatedNet
,Y
] = predictAndUpdateState(recNet
,sequences
)sequences
using the trained
recurrent neural network recNet
and updates the network
state.
This function supports recurrent neural networks only. The input
recNet
must have at least one recurrent layer such as an
LSTM layer or a custom layer with state parameters.
[
predicts the responses for the data in the numeric or cell arrays
updatedNet
,Y
] = predictAndUpdateState(recNet
,X1,...,XN
)X1
, …, XN
for the multiinput network
recNet
. The input Xi
corresponds to the
network input recNet.InputNames(i)
.
[
makes predictions using the multiinput network updatedNet
,Y
] = predictAndUpdateState(recNet
,mixed
)recNet
with
data of mixed data types.
[updatedNet,
predicts responses for the Y1,...,YM
] = predictAndUpdateState(___)M
outputs of a multioutput network
using any of the previous input arguments. The output Yj
corresponds to the network output recNet.OutputNames(j)
. To
return categorical outputs for the classification output layers, set the ReturnCategorical
option to 1
(true).
[___] = predictAndUpdateState(___,
makes predictions with additional options specified by one or more namevalue
arguments using any of the previous syntaxes. For example,
Name=Value
)MiniBatchSize=27
makes predictions using minibatches of size 27.
Tip
When you make predictions with sequences of different lengths,
the minibatch 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 minibatch size and padding options, use the MiniBatchSize
and SequenceLength
options, respectively.
Examples
Predict and Update Network State
Predict responses using a trained recurrent neural network and update the network state.
Suppose you have a long shortterm memory (LSTM) network
net
that was trained on the Japanese Vowels data set as
described in [1] and [2]. Suppose the network was trained on the sequences
sorted by sequence length with a minibatch size of 27.
View the network architecture.
net.Layers
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.
load JapaneseVowelsTestData
Loop over the time steps in a sequence. Predict the scores of each time step and update the network state.
X = XTest{94}; numTimeSteps = size(X,2); for i = 1:numTimeSteps v = X(:,i); [net,score] = predictAndUpdateState(net,v); scores(:,i) = score; end
Plot the prediction scores. The plot shows how the prediction scores change between time steps.
classNames = string(net.Layers(end).Classes); figure lines = plot(scores'); xlim([1 numTimeSteps]) legend("Class " + classNames,Location="northwest") xlabel("Time Step") ylabel("Score") title("Prediction Scores Over Time Steps")
Highlight the prediction scores over time steps for the correct class.
trueLabel = TTest(94); lines(trueLabel).LineWidth = 3;
Display the final time step prediction in a bar chart.
figure bar(score) title("Final Prediction Scores") xlabel("Class") ylabel("Score")
Input Arguments
recNet
— Trained recurrent neural network
SeriesNetwork
object  DAGNetwork
object
Trained recurrent neural network, specified as a SeriesNetwork
or a DAGNetwork
object. You can
get a trained network by importing a pretrained network or by
training your own network using the trainNetwork
function.
recNet
is a recurrent neural network. It must have at least one recurrent
layer (for example, an LSTM network).
sequences
— Sequence or time series data
cell array of numeric arrays  numeric array  datastore
Sequence or time series data, specified as an Nby1 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.
Input  Description 

Vector sequences  cbys matrices, where c is the number of features of the sequences and s is the sequence length. 
1D image sequences  hbycbys arrays, where h and c correspond to the height and number of channels of the images, respectively, and s is the sequence length. 
2D image sequences  hbywbycbys 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. 
3D image sequences  hbywbydbycbys, where h, w, d, and c correspond to the height, width, depth, and number of channels of the 3D 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.
Tip
This argument supports complexvalued predictors. To input complexvalued data
into a SeriesNetwork
or DAGNetwork
object, the
SplitComplexInputs
option of the input layer must be
1
(true
).
X1,...,XN
— Numeric or cell arrays for networks with multiple inputs
numeric array  cell array
Numeric or cell arrays for networks with multiple inputs.
For sequence predictor input, the input must be a numeric array representing a single sequence
or a cell array of sequences, where the format of the predictors match the formats described
in the sequences
argument description. For image and feature predictor
input, the input must be a numeric array and the format of the predictors must match the one
of the following:
Data  Format 

2D images  hbywbyc numeric array, where h, w, and c are the height, width, and number of channels of the images, respectively. 
3D images  hbywbydbyc numeric array, where h, w, d, and c are the height, width, depth, and number of channels of the images, respectively. 
Feature data  cby1 column vectors, where c is the number of features. 
For an example showing how to train a network with multiple inputs, see Train Network on Image and Feature Data.
Tip
To input complexvalued data into a DAGNetwork
or
SeriesNetwork
object, the
SplitComplexInputs
option of the input layer must be
1
.
Data Types: single
 double
 int8
 int16
 int32
 int64
 uint8
 uint16
 uint32
 uint64
 cell
Complex Number Support: Yes
mixed
— Mixed data
TransformedDatastore
 CombinedDatastore
 custom minibatch datastore
Mixed data, specified as one of the following.
Data Type  Description  Example Usage 

TransformedDatastore  Datastore that transforms batches of data read from an underlying datastore using a custom transformation function 

CombinedDatastore  Datastore that reads from two or more underlying datastores 

Custom minibatch datastore  Custom datastore that returns minibatches of data  Make predictions using data in a format that other datastores do not support. For details, see Develop Custom MiniBatch Datastore. 
You can use other builtin datastores for making predictions by using the transform
and combine
functions. These functions can convert the data read from datastores to the table or cell array format required by predictAndUpdateState
. For more information, see Datastores for Deep Learning.
The datastore must return data in a table or a cell array. Custom minibatch datastores must output tables. The format of the datastore output depends on the network architecture.
Datastore Output  Example Output 

Cell array with The
order of inputs is given by the 
data = read(ds) data = 4×3 cell array {12×50 double} {28×1 double} {12×50 double} {28×1 double} {12×50 double} {28×1 double} {12×50 double} {28×1 double} 
For sequence predictor input, the input must be a numeric array representing a single sequence
or a cell array of sequences, where the format of the predictors match the formats described
in the sequences
argument description. For image and feature predictor
input, the input must be a numeric array and the format of the predictors must match the one
of the following:
Data  Format 

2D images  hbywbyc numeric array, where h, w, and c are the height, width, and number of channels of the images, respectively. 
3D images  hbywbydbyc numeric array, where h, w, d, and c are the height, width, depth, and number of channels of the images, respectively. 
Feature data  cby1 column vectors, where c is the number of features. 
For an example showing how to train a network with multiple inputs, see Train Network on Image and Feature Data.
Tip
To convert a numeric array to a datastore, use ArrayDatastore
.
NameValue Arguments
Specify optional pairs of arguments as
Name1=Value1,...,NameN=ValueN
, where Name
is
the argument name and Value
is the corresponding value.
Namevalue arguments must appear after other arguments, but the order of the
pairs does not matter.
Before R2021a, use commas to separate each name and value, and enclose
Name
in quotes.
Example: [updatedNet,Y] =
predictAndUpdateState(recNet,C,MiniBatchSize=27)
makes predictions
using minibatches of size 27.
MiniBatchSize
— Size of minibatches
128
(default)  positive integer
Size of minibatches to use for prediction, specified as a positive integer. Larger minibatch sizes require more memory, but can lead to faster predictions.
When you make predictions with sequences of different lengths,
the minibatch 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 minibatch size and padding options, use the MiniBatchSize
and SequenceLength
options, respectively.
Data Types: single
 double
 int8
 int16
 int32
 int64
 uint8
 uint16
 uint32
 uint64
Acceleration
— Performance optimization
"auto"
(default)  "none"
Performance optimization, specified as one of the following:
"auto"
— Automatically apply a number of optimizations suitable for the input network and hardware resources."none"
— Disable all acceleration.
Using the Acceleration
option "auto"
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 input data.
ExecutionEnvironment
— Hardware resource
"auto"
(default)  "gpu"
 "cpu"
Hardware resource, specified as one of these values:
"auto"
— Use a GPU if one is available. Otherwise, use the CPU."gpu"
— Use the GPU. Using a GPU requires a Parallel Computing Toolbox license and a supported GPU device. For information about supported devices, see GPU Computing Requirements (Parallel Computing Toolbox). If Parallel Computing Toolbox or a suitable GPU is not available, then the software returns an error."cpu"
— Use the CPU.
ReturnCategorical
— Option to return categorical labels
0
(false
) (default)  1
(true
)
Option to return categorical labels, specified as 0
(false
) or 1
(true
).
If ReturnCategorical
is 1
(true
),
then the function returns categorical labels for classification output layers.
Otherwise, the function returns the prediction scores for classification output
layers.
SequenceLength
— Option to pad, truncate, or split sequences
"longest"
(default)  "shortest"
 positive integer
Option to pad, truncate, or split sequences, specified as one of these values:
"longest"
— Pad sequences in each minibatch to have the same length as the longest sequence. This option does not discard any data, though padding can introduce noise to the neural network."shortest"
— Truncate sequences in each minibatch 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 minibatch, pad the sequences to the length of the longest sequence in the minibatch, and then split the sequences into smaller sequences of the specified length. If splitting occurs, then the software creates extra minibatches. If the specified sequence length does not evenly divide the sequence lengths of the data, then the minibatches containing the ends those sequences have length shorter than the specified sequence length. Use this option if the full sequences do not fit in memory. Alternatively, try reducing the number of sequences per minibatch by setting the
MiniBatchSize
option to a lower value.
To learn more about the effect of padding and truncating sequences, see Sequence Padding and Truncation.
Data Types: single
 double
 int8
 int16
 int32
 int64
 uint8
 uint16
 uint32
 uint64
 char
 string
SequencePaddingDirection
— Direction of padding or truncation
"right"
(default)  "left"
Direction of padding or truncation, specified as one of the following:
"right"
— Pad or truncate sequences on the right. The sequences start at the same time step and the software truncates or adds padding to the end of the sequences."left"
— Pad or truncate sequences on the left. The software truncates or adds padding to the start of the sequences so that the sequences end at the same time step.
Because recurrent layers process sequence data one time step at a time, when the recurrent layer OutputMode
property is "last"
, any padding in the final time steps can negatively influence the layer output. To pad or truncate sequence data on the left, set the SequencePaddingDirection
option to "left"
.
For sequencetosequence neural networks (when the OutputMode
property is "sequence"
for each recurrent layer), any padding in the first time steps can negatively influence the predictions for the earlier time steps. To pad or truncate sequence data on the right, set the SequencePaddingDirection
option to "right"
.
To learn more about the effect of padding and truncating sequences, see Sequence Padding and Truncation.
SequencePaddingValue
— Value to pad sequences
0
(default)  scalar
Value by which to pad input sequences, specified as a scalar.
Do not pad sequences with NaN
, because doing so can propagate errors throughout the neural network.
Data Types: single
 double
 int8
 int16
 int32
 int64
 uint8
 uint16
 uint32
 uint64
Output Arguments
updatedNet
— Updated network
SeriesNetwork
object  DAGNetwork
object
Updated network. updatedNet
is the same type of network as the input
network.
Y
— Predicted scores or responses
numeric array  categorical array  cell array
Predicted scores or responses, returned as a numeric array, categorical
array, or a cell array. The format of Y
depends on the
type of problem.
The following table describes the format for classification tasks.
Task  ReturnCategorical  Format 

Sequencetolabel classification  0 (false)  NbyK matrix, where N is the number of observations, and K is the number of classes 
1 (true)  Nby1 categorical vector, where N is the number of observations  
Sequencetosequence classification  0 (false)  Nby1 cell array of matrices,
where N is the number of
observations. The sequences are matrices with
K rows, where
K is the number of classes. Each
sequence has the same number of time steps as the
corresponding input sequence after the

1 (true)  Nby1 cell array of categorical
sequences, where N is the number of
observations. The categorical sequences are categorical
vectors with the same number of time steps as the
corresponding input sequence after the

For sequencetosequence classification tasks with one observation,
sequences
can be a matrix. In this case, the format
of Y
depends on the
ReturnCategorical
option:
If
ReturnCategoical
is0
(false), thenY
is a KbyS matrix scores, where K is the number of classes, and S is the total number of time steps in the corresponding input sequence.If
ReturnCategoical
is1
(true), thenY
is a 1byS categorical vector, where S is the total number of time steps in the corresponding input sequence.
The following table describes the format for regression tasks.
Task  Format 

Sequencetoone regression  NbyR matrix, where N is the number of observations and R is the number of responses. 
Sequencetosequence regression  Nby1 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 after applying the
For
sequencetosequence problems with one observation,

Y1,...,YM
— Predicted scores or responses of networks with multiple outputs
numeric array  categorical array  cell array
Predicted scores or responses of networks with multiple outputs, returned as numeric arrays, categorical arrays, or cell arrays.
Each output Yj
corresponds to the network output
recNet.OutputNames(j)
and has format as described in
the Y
output argument.
Algorithms
FloatingPoint Arithmetic
When you train a neural network using the trainnet
or trainNetwork
functions, or when you use prediction or validation functions with DAGNetwork
and SeriesNetwork
objects, the software performs these computations using singleprecision, floatingpoint arithmetic. Functions for prediction and validation include predict
, classify
, and activations
. The software uses singleprecision arithmetic when you train neural networks using both CPUs and GPUs.
Reproducibility
To provide the best performance, deep learning using a GPU in MATLAB^{®} is not guaranteed to be deterministic. Depending on your network architecture, under some conditions you might get different results when using a GPU to train two identical networks or make two predictions using the same network and data.
Alternatives
For recurrent neural networks with a single classification layer only, you can compute
the predicted classes and scores and update the network state using the classifyAndUpdateState
function.
To compute the activations of a network layer, use the activations
function. The activations
function does not update the network state.
To make predictions without updating the network state, use the classify
function or the predict
function.
References
[1] M. Kudo, J. Toyama, and M. Shimbo. "Multidimensional Curve Classification Using PassingThrough Regions." Pattern Recognition Letters. Vol. 20, No. 11–13, pages 1103–1111.
[2] UCI Machine Learning Repository: Japanese Vowels Dataset. https://archive.ics.uci.edu/ml/datasets/Japanese+Vowels
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
C++ code generation supports the following syntaxes:
[updatedNet,Y] = predictAndUpdateState(recNet,sequences)
, wheresequences
is cell array.[updatedNet,Y] = predictAndUpdateState(recNet,sequences,Name=Value)
For vector sequence inputs, the number of features must be a constant during code generation. The sequence length can be variable sized.
For image sequence inputs, the height, width, and the number of channels must be a constant during code generation.
Only the
MiniBatchSize
,SequenceLength
,SequencePaddingDirection
, andSequencePaddingValue
namevalue arguments are supported for code generation. All namevalue arguments must be compiletime constants.Only the
"longest"
and"shortest"
options of theSequenceLength
namevalue argument is supported for code generation.Code generation for Intel^{®} MKLDNN target does not support the combination of
SequenceLength="longest"
,SequencePaddingDirection="left"
, andSequencePaddingValue=0
namevalue arguments.
GPU Code Generation
Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.
Usage notes and limitations:
GPU code generation supports the following syntaxes:
[updatedNet,Y] = predictAndUpdateState(recNet,sequences)
, wheresequences
is cell array or numeric array.[updatedNet,Y] = predictAndUpdateState(recNet,sequences,Name=Value)
GPU code generation for the
predictAndUpdateState
function is only supported for recurrent neural networks targeting cuDNN and TensorRT libraries.GPU code generation does not support
gpuArray
inputs to thepredictAndUpdateState
function.For vector sequence inputs, the number of features must be a constant during code generation. The sequence length can be variable sized.
For image sequence inputs, the height, width, and the number of channels must be a constant during code generation.
Only the
MiniBatchSize
,SequenceLength
,SequencePaddingDirection
, andSequencePaddingValue
namevalue arguments are supported for code generation. All namevalue pairs must be compiletime constants.Only the
"longest"
and"shortest"
options of theSequenceLength
namevalue argument is supported for code generation.
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
The
ExecutionEnvironment
option must be"auto"
or"gpu"
when the input data is:A
gpuArray
A cell array containing
gpuArray
objectsA table containing
gpuArray
objectsA datastore that outputs cell arrays containing
gpuArray
objectsA datastore that outputs tables containing
gpuArray
objects
For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).
Version History
Introduced in R2017bR2024a: Not recommended
Starting in R2024a, DAGNetwork
and SeriesNetwork
objects are not recommended, use dlnetwork
objects instead. This
recommendation means that the predictAndUpdateState
function is
also not recommended. Instead, use the predict
function and
use the state output to update the State
property of the neural network.
There are no plans to remove support for DAGNetwork
and
SeriesNetwork
objects. However, dlnetwork
objects have these advantages and are recommended instead:
dlnetwork
objects are a unified data type that supports network building, prediction, builtin training, visualization, compression, verification, and custom training loops.dlnetwork
objects support a wider range of network architectures that you can create or import from external platforms.The
trainnet
function supportsdlnetwork
objects, which enables you to easily specify loss functions. You can select from builtin loss functions or specify a custom loss function.Training and prediction with
dlnetwork
objects is typically faster thanLayerGraph
andtrainNetwork
workflows.
To convert a trained DAGNetwork
or SeriesNetwork
object to a dlnetwork
object, use the dag2dlnetwork
function.
This table shows a typical usage of the predictAndUpdateState
function and how to update your code to use dlnetwork
objects
instead.
Not Recommended  Recommended 

[net,Y] = predictAndUpdateState(net,X); 
[scores,state] = predict(net,X); net.State = state; 
R2022b: Prediction functions pad minibatches to length of longest sequence before splitting when you specify SequenceLength
option as an integer
Starting in R2022b, when you make predictions with sequence data using the
predict
, classify
,
predictAndUpdateState
, classifyAndUpdateState
,
and activations
functions and the SequenceLength
option is an integer, the software pads sequences to the length of the longest sequence in
each minibatch and then splits the sequences into minibatches with the specified sequence
length. If SequenceLength
does not evenly divide the sequence length of
the minibatch, then the last split minibatch has a length shorter than
SequenceLength
. This behavior prevents time steps that contain only
padding values from influencing predictions.
In previous releases, the software pads minibatches of sequences to have a length matching the nearest multiple of SequenceLength
that is greater than or equal to the minibatch length and then splits the data. To reproduce this behavior, manually pad the input data such that the minibatches have the length of the appropriate multiple of SequenceLength
. For sequencetosequence workflows, you may also need to manually remove time steps of the output that correspond to padding values.
See Also
dlnetwork
 minibatchpredict
 predict
 scores2label
 sequenceInputLayer
 lstmLayer
 bilstmLayer
 gruLayer
 classifyAndUpdateState
MATLAB 命令
您点击的链接对应于以下 MATLAB 命令：
请在 MATLAB 命令行窗口中直接输入以执行命令。Web 浏览器不支持 MATLAB 命令。
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
 América Latina (Español)
 Canada (English)
 United States (English)
Europe
 Belgium (English)
 Denmark (English)
 Deutschland (Deutsch)
 España (Español)
 Finland (English)
 France (Français)
 Ireland (English)
 Italia (Italiano)
 Luxembourg (English)
 Netherlands (English)
 Norway (English)
 Österreich (Deutsch)
 Portugal (English)
 Sweden (English)
 Switzerland
 United Kingdom (English)