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.

This topic explains how to work with sequence and time series data for classification and regression tasks using long short-term memory (LSTM) networks. For an example showing how to classify sequence data using an LSTM network, see Sequence Classification Using Deep Learning.

An LSTM network is a type of recurrent neural network (RNN) that can learn long-term dependencies between time steps of sequence data.

The core components of an LSTM network are a sequence input layer and an LSTM layer. A
*sequence input layer* inputs sequence or time series data into
the network. An *LSTM layer* learns long-term dependencies between
time steps of sequence data.

This diagram illustrates the architecture of a simple LSTM network for classification. The network starts with a sequence input layer followed by an LSTM layer. To predict class labels, the network ends with a fully connected layer, a softmax layer, and a classification output layer.

This diagram illustrates the architecture of a simple LSTM network for regression. The network starts with a sequence input layer followed by an LSTM layer. The network ends with a fully connected layer and a regression output layer.

To create an LSTM network for sequence-to-label classification, create a layer array containing a sequence input layer, an LSTM layer, a fully connected layer, a softmax layer, and a classification output layer.

Specify the size of the sequence input layer to be the feature dimension of the input data. Specify the size of the fully connected layer to be the number of classes.

For the LSTM layer, choose an output size, and specify the output mode `'last'`

.

inputSize = 12; numHiddenUnits = 100; numClasses = 9; layers = [ ... sequenceInputLayer(inputSize) lstmLayer(numHiddenUnits,'OutputMode','last') fullyConnectedLayer(numClasses) softmaxLayer classificationLayer];

For an example showing how to train an LSTM network for sequence-to-label classification and classify new data, see Sequence Classification Using Deep Learning.

To create an LSTM network for sequence-to-sequence regression, use the same architecture for sequence-to-labe classification, but set the output mode of the LSTM layer to 'sequence'.

inputSize = 12; numHiddenUnits = 100; numClasses = 9; layers = [ ... sequenceInputLayer(inputSize) lstmLayer(numHiddenUnits,'OutputMode','sequence') fullyConnectedLayer(numClasses) softmaxLayer classificationLayer];

To create an LSTM network for sequence-to-one regression, create a layer array containing a sequence input layer, an LSTM layer, a fully connected layer, and a regression output layer.

Specify the size of the sequence input layer to be the feature dimension of the input data. Specify the size of the fully connected layer to be the number of responses.

For the LSTM layer, choose an output size, and specify the output mode `'last'`

.

inputSize = 12; outputSize = 125; numResponses = 1; layers = [ ... sequenceInputLayer(inputSize) lstmLayer(outputSize,'OutputMode','last') fullyConnectedLayer(numResponses) regressionLayer];

To create an LSTM network for sequence-to-sequence regression, use the same architecture for sequence-to-one regression, but set the output mode of the LSTM layer to `'sequence'`

.

inputSize = 12; outputSize = 125; numResponses = 1; layers = [ ... sequenceInputLayer(inputSize) lstmLayer(outputSize,'OutputMode','sequence') fullyConnectedLayer(numResponses) regressionLayer];

For an example showing how to train an LSTM network for sequence-to-sequence regression and predict on new data, see Sequence-to-Sequence Regression Using Deep Learning.

You can make LSTM networks deeper by inserting extra LSTM layers with the output mode `'sequence'`

before the LSTM layer.

For sequence-to-label classification networks, the output mode of the last LSTM layer must be `'last'`

.

inputSize = 12; numHiddenUnits1 = 125; numHiddenUnits2 = 100; numClasses = 9; layers = [ ... sequenceInputLayer(inputSize) lstmLayer(numHiddenUnits1,'OutputMode','sequence') lstmLayer(numHiddenUnits2,'OutputMode','last') fullyConnectedLayer(numClasses) softmaxLayer classificationLayer];

For sequence-to-sequence classification networks, the output mode of the last LSTM layer must be `'sequence'`

.

inputSize = 12; numHiddenUnits1 = 125; numHiddenUnits2 = 100; numClasses = 9; layers = [ ... sequenceInputLayer(inputSize) lstmLayer(numHiddenUnits1,'OutputMode','sequence') lstmLayer(numHiddenUnits2,'OutputMode','sequence') fullyConnectedLayer(numClasses) softmaxLayer classificationLayer];

A sequence input layer inputs sequence data to a network. You can create a
sequence input layer using `sequenceInputLayer`

.

An LSTM layer is a recurrent neural network (RNN) layer that enables support for time series and sequence data in a network. The layer performs additive interactions, which can help improve gradient flow over long sequences during training. LSTM layers are best suited for learning *long-term dependencies* (dependencies from distant time steps).

Create an LSTM layer using `lstmLayer`

.

A bidirectional LSTM (BiLSTM) layer is an RNN layer that learns bidirectional long-term dependencies between time steps. These dependencies can be useful when you want the network to learn from the complete time series at each time step.

Create a BiLSTM layer using `bilstmLayer`

.

To classify or make predictions on new data, use `classify`

and `predict`

.

LSTM networks can remember the state of the network between predictions. The network state is useful when you do not have the complete time series in advance, or if you want to make multiple predictions on a long time series.

To predict and classify on parts of a time series and update the network state, you
can use `predictAndUpdateState`

and
`classifyAndUpdateState`

. To
reset the network state between predictions, use `resetState`

.

For an example showing how to forecast future time steps of a sequence, see Time Series Forecasting Using Deep Learning.

When passing data through the network, the software pads, truncates, or splits
sequences in each mini-batch to have the specified length. You can specify the sequence
lengths and the value used to pad the sequences using the
`SequenceLength`

and `SequencePaddingValue`

name-value pair arguments in `trainingOptions`

.

If you sort your data by sequence length, then you might reduce the amount of padding or discarded data when padding or truncating the sequences.

To sort the data by sequence length, first get the number of columns of each
sequence by applying `size(X,2)`

to every sequence using
`cellfun`

. Then sort the sequence lengths using
`sort`

, and use the second output to reorder the original
sequences.

sequenceLengths = cellfun(@(X) size(X,2), XTrain); [sequenceLengthsSorted,idx] = sort(sequenceLengths); XTrain = XTrain(idx);

The following figures show the sequence lengths of the sorted and unsorted data in bar charts.

If you specify the sequence length `'longest'`

, then the software
pads the sequences in each mini-batch to have the same length as the longest
sequence in that mini-batch. This option is the default.

The follow figures illustrate the effect of setting `'SequenceLength'`

to `'longest'`

.

If you specify the sequence the length to be `'shortest'`

, then
the software truncates the sequences in each mini-batch to have the same length as
the shortest sequence in that mini-batch. The remaining data in the sequences is
discarded.

The following figures illustrate the effect of setting `'SequenceLength'`

to `'shortest'`

.

If you specify sequence the length to be an integer value, then the software pads the sequences in each mini-batch to have the same length as the longest sequence, then splits the sequences into smaller sequences of the specified length. If splitting occurs, then the software creates extra mini-batches.

The follow figures illustrate the effect of setting `'SequenceLength'`

to 5.

This diagram illustrates the flow of a time series *X* with
*D* features of length *S* through an LSTM layer.
In this diagram, *h* denotes the output (also known as the
*hidden state*) and *c* denotes the
*cell state*.

The first LSTM unit takes the initial state of the network and the first time step of
the sequence $${X}_{1}$$, and then computes the first output $${h}_{1}$$ and the updated cell state $${c}_{1}$$. At time step *t*, the unit takes the current state
of the network $$({c}_{t-1},{h}_{t-1})$$ and the next time step of the sequence $${X}_{t}$$, and then computes the output $${h}_{t}$$ and the updated cell state $${c}_{t}$$.

The state of the layer consists of the *output state* (also known as the
*hidden state*) and the *cell state*. The output
state at time step *t* contains the output of the LSTM layer for this time
step. The cell state contains information learned from the previous time steps. At each time
step, the layer adds information to or removes information from the cell state, where the
layer controls these updates using *gates*.

This table summarizes the components that control the cell state and output state of the layer.

Component | Purpose |
---|---|

Input gate (i) | Control level of cell state update |

Forget gate (f) | Control level of cell state reset (forget) |

Layer input (g) | Add information to cell state |

Output gate (o) | Control level of cell state added to output state |

This diagram illustrates the flow of data at time step *t*. The diagram
highlights how the gates forget, update, and output the cell and output states.

The learnable weights of an LSTM layer are the input weights *W*
(`InputWeights`

), the recurrent weights *R*
(`RecurrentWeights`

), and the bias *b*
(`Bias`

). The matrices *W*, *R*,
and *b* are concatenations of the input weights, the recurrent weights, and
the bias of each component, respectively. These matrices are concatenated as follows:

$$W=\left[\begin{array}{c}{W}_{i}\\ {W}_{f}\\ {W}_{g}\\ {W}_{o}\end{array}\right],R=\left[\begin{array}{c}{R}_{i}\\ {R}_{f}\\ {R}_{g}\\ {R}_{o}\end{array}\right],b=\left[\begin{array}{c}{b}_{i}\\ {b}_{f}\\ {b}_{g}\\ {b}_{o}\end{array}\right],$$

where *i*, *f*, *g*, and
*o* denote the input gate, forget gate, layer input, and output gate,
respectively.

The cell state at time step *t* is given by

$${c}_{t}={f}_{t}\odot {c}_{t-1}+{i}_{t}\odot {g}_{t},$$

The output (hidden) state at time step *t* is given by

$${h}_{t}={o}_{t}\odot \text{tanh}({c}_{t}).$$

This table shows the formula for each component at time step
*t*.

Component | Formula |
---|---|

Input gate | $${i}_{t}=\sigma ({W}_{i}{x}_{t}+\text{}{\text{R}}_{i}{h}_{t-1}+{b}_{i})$$ |

Forget gate | $${f}_{t}=\sigma ({W}_{f}{x}_{t}+\text{}{\text{R}}_{f}{h}_{t-1}+{b}_{f})$$ |

Layer input | $${g}_{t}=\text{tanh}({W}_{g}{x}_{t}+\text{}{\text{R}}_{g}{h}_{t-1}+{b}_{g})$$ |

Output gate | $${o}_{t}=\sigma ({W}_{o}{x}_{t}+\text{}{\text{R}}_{o}{h}_{t-1}+{b}_{o})$$ |

Here, denotes the sigmoid function given by .

[1] Hochreiter, S, and J. Schmidhuber, 1997. Long short-term memory. Neural computation, 9(8), pp.1735–1780.

`bilstmLayer`

| `classifyAndUpdateState`

| `lstmLayer`

| `predictAndUpdateState`

| `resetState`

| `sequenceInputLayer`

Was this topic helpful?