predictAndUpdateState - (Not recommended) Predict responses using a trained recurrent neural network and

        update the network state - MATLAB ([original](https://in.mathworks.com/help/deeplearning/ref/seriesnetwork.predictandupdatestate.html)) ([raw](?raw))

(Not recommended) Predict responses using a trained recurrent neural network and update the network state

predictAndUpdateState is not recommended. Instead, use thepredict 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, seeGPU Computing Requirements (Parallel Computing Toolbox). Specify the hardware requirements using the ExecutionEnvironment name-value argument.

[[updatedNet](#d126e215727),[Y](#d126e215746)] = predictAndUpdateState([recNet](#d126e214943),[sequences](#mw%5Fe64205e2-5297-4ff5-ad37-0d5375e19ef2%5Fsep%5Fmw%5F5a3519e4-ff13-4b34-baf4-c9f3a716e62d)) predicts responses for data in sequences using the trained recurrent neural network recNet and updates the network state.

This function supports recurrent neural networks only. The inputrecNet must have at least one recurrent layer such as an LSTM layer or a custom layer with state parameters.

example

[[updatedNet](#d126e215727),[Y](#d126e215746)] = predictAndUpdateState([recNet](#d126e214943),[X1,...,XN](#mw%5Fe64205e2-5297-4ff5-ad37-0d5375e19ef2%5Fsep%5Fmw%5Fbd719580-c2ff-492b-a0ab-8291fdbdc004)) predicts the responses for the data in the numeric or cell arraysX1, …, XN for the multi-input networkrecNet. The input Xi corresponds to the network input recNet.InputNames(i).

[[updatedNet](#d126e215727),[Y](#d126e215746)] = predictAndUpdateState([recNet](#d126e214943),[mixed](#mw%5Fe64205e2-5297-4ff5-ad37-0d5375e19ef2%5Fsep%5Fmw%5F24c37e26-6497-4d74-ab01-7a7b3250bf9a)) makes predictions using the multi-input network recNet with data of mixed data types.

[updatedNet,[Y1,...,YM](#mw%5F43dbc3bc-3fb7-4703-ba56-666f53d1f06a)] = predictAndUpdateState(___) predicts responses for the M outputs of a multi-output 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(___,[Name=Value](#namevaluepairarguments)) makes predictions with additional options specified by one or more name-value arguments using any of the previous syntaxes. For example,MiniBatchSize=27 makes predictions using mini-batches of size 27.

Tip

When you make 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 MiniBatchSize and SequenceLength options, respectively.

Examples

collapse all

Predict responses using a trained recurrent neural network and update the network state.

Suppose you have a long short-term memory (LSTM) networknet 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 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.

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;

Figure contains an axes object. The axes object with title Prediction Scores Over Time Steps, xlabel Time Step, ylabel Score contains 9 objects of type line. These objects represent Class 1, Class 2, Class 3, Class 4, Class 5, Class 6, Class 7, Class 8, Class 9.

Display the final time step prediction in a bar chart.

figure bar(score) title("Final Prediction Scores") xlabel("Class") ylabel("Score")

Figure contains an axes object. The axes object with title Final Prediction Scores, xlabel Class, ylabel Score contains an object of type bar.

Input Arguments

collapse all

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).

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.

Input Description
Vector sequences c_-by-s matrices, where_c is the number of features of the sequences and s is the sequence length.
1-D image sequences _h_-by-_c_-by-s arrays, where h and c correspond to the height and number of channels of the images, respectively, 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.

Tip

This argument supports complex-valued predictors. To input complex-valued data into a SeriesNetwork or DAGNetwork object, theSplitComplexInputs option of the input layer must be1 (true).

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
2-D images _h_-by-_w_-by-c numeric array, where h, w, and c are the height, width, and number of channels of the images, respectively.
3-D images _h_-by-_w_-by-_d_-by-c numeric array, where h, w, d, and c are the height, width, depth, and number of channels of the images, respectively.
Feature data _c_-by-1 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 complex-valued data into a DAGNetwork orSeriesNetwork object, theSplitComplexInputs option of the input layer must be1.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | cell
Complex Number Support: Yes

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 Make predictions using networks with multiple inputs.Transform outputs of datastores not supported bypredictAndUpdateState so they have the required format.Apply custom transformations to datastore output.
CombinedDatastore Datastore that reads from two or more underlying datastores Make predictions using networks with multiple inputs.Combine predictors from different data sources.
Custom mini-batch datastore Custom datastore that returns mini-batches of data Make predictions using data in a format that other datastores do not support.For details, see Develop Custom Mini-Batch Datastore.

You can use other built-in 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 mini-batch datastores must output tables. The format of the datastore output depends on the network architecture.

Datastore Output Example Output
Cell array with numInputs columns, wherenumInputs is the number of network inputs.The order of inputs is given by the InputNames property of the network. 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
2-D images _h_-by-_w_-by-c numeric array, where h, w, and c are the height, width, and number of channels of the images, respectively.
3-D images _h_-by-_w_-by-_d_-by-c numeric array, where h, w, d, and c are the height, width, depth, and number of channels of the images, respectively.
Feature data _c_-by-1 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.

Name-Value Arguments

collapse all

Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value 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 mini-batches of size 27.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Performance optimization, specified as one of the following:

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.

Hardware resource, specified as one of these values:

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.

Option to pad, truncate, or split sequences, specified as one of these values:

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

Direction of padding or truncation, specified as one of the following:

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 sequence-to-sequence 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.

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

collapse all

Updated network. updatedNet is the same type of network as the input network.

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
Sequence-to-label classification 0 (false) _N_-by-K matrix, where N is the number of observations, and K is the number of classes
1 (true) N_-by-1 categorical vector, where_N is the number of observations
Sequence-to-sequence classification 0 (false) 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 classes. Each sequence has the same number of time steps as the corresponding input sequence after theSequenceLength option is applied to each mini-batch independently.
1 (true) _N_-by-1 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 theSequenceLength option is applied to each mini-batch independently.

For sequence-to-sequence classification tasks with one observation,sequences can be a matrix. In this case, the format of Y depends on theReturnCategorical option:

The following table describes the format for regression tasks.

Task Format
Sequence-to-one regression _N_-by-R matrix, where N is the number of observations and R is the number of responses.
Sequence-to-sequence regression 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 after applying theSequenceLength option to each mini-batch independently.For sequence-to-sequence problems with one observation,sequences can be a matrix. In this case, Y is a matrix of responses.

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 outputrecNet.OutputNames(j) and has format as described in the Y output argument.

Algorithms

collapse all

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 single-precision, floating-point arithmetic. Functions for prediction and validation include predict, classify, and activations. The software uses single-precision arithmetic when you train neural networks using both CPUs and GPUs.

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 Passing-Through 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

expand all

Usage notes and limitations:

Usage notes and limitations:

For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).

Version History

Introduced in R2017b

expand all

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 andSeriesNetwork objects. However, dlnetwork objects have these advantages and are recommended instead:

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;

Starting in R2022b, when you make predictions with sequence data using thepredict, 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 mini-batch and then splits the sequences into mini-batches with the specified sequence length. If SequenceLength does not evenly divide the sequence length of the mini-batch, then the last split mini-batch has a length shorter thanSequenceLength. This behavior prevents time steps that contain only padding values from influencing predictions.

In previous releases, the software pads mini-batches of sequences to have a length matching the nearest multiple of SequenceLength that is greater than or equal to the mini-batch length and then splits the data. To reproduce this behavior, manually pad the input data such that the mini-batches have the length of the appropriate multiple of SequenceLength. For sequence-to-sequence workflows, you may also need to manually remove time steps of the output that correspond to padding values.