# Documentation

### This is machine translation

Translated by
Mouseover text to see original. Click the button below to return to the English version of the page.

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

## Long Short-Term Memory Networks

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.

### LSTM Network Architecture

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.

#### Classification LSTM Networks

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]; ```

#### Regression LSTM Networks

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.

#### Deeper LSTM Networks

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];```

### Layers

#### Sequence Input Layer

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

#### LSTM Layer

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

#### Bidirectional LSTM Layer

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

### Classification and Prediction

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.

### Sequence Padding, Truncation, and Splitting

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

#### Sort Sequences by Length

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'`.

#### Truncate Sequences

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'`.

#### Split Sequences

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.

### LSTM Layer Architecture

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 $\left({c}_{t-1},{h}_{t-1}\right)$ 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.

ComponentPurpose
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},$`
where $\odot$ denotes the Hadamard product (element-wise multiplication of vectors).

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

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

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

ComponentFormula
Input gate${i}_{t}=\sigma \left({W}_{i}{x}_{t}+\text{​}{\text{R}}_{i}{h}_{t-1}+{b}_{i}\right)$
Forget gate${f}_{t}=\sigma \left({W}_{f}{x}_{t}+\text{​}{\text{R}}_{f}{h}_{t-1}+{b}_{f}\right)$
Layer input${g}_{t}=\text{tanh}\left({W}_{g}{x}_{t}+\text{​}{\text{R}}_{g}{h}_{t-1}+{b}_{g}\right)$
Output gate${o}_{t}=\sigma \left({W}_{o}{x}_{t}+\text{​}{\text{R}}_{o}{h}_{t-1}+{b}_{o}\right)$

Here, denotes the sigmoid function given by .

## References

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