Gated recurrent unit (GRU) layer

A GRU layer learns dependencies between time steps in time series and sequence data.

creates a GRU layer and sets the `layer`

= gruLayer(`numHiddenUnits`

)`NumHiddenUnits`

property.

sets additional `layer`

= gruLayer(`numHiddenUnits`

,`Name,Value`

)`OutputMode`

, Activations, State, Parameters and Initialization, Learn Rate and Regularization, and `Name`

properties using one or more name-value pair arguments.
You can specify multiple name-value pair arguments. Enclose each property name in
quotes.

`NumHiddenUnits`

— Number of hidden unitspositive integer

Number of hidden units (also known as the hidden size), specified as a positive integer.

The number of hidden units corresponds to the amount of information remembered between time steps (the hidden state). The hidden state can contain information from all previous time steps, regardless of the sequence length. If the number of hidden units is too large, then the layer might overfit to the training data. This value can vary from a few dozen to a few thousand.

The hidden state does not limit the number of time steps that are processed in an
iteration. To split your sequences into smaller sequences for training, use the
`'SequenceLength'`

option in `trainingOptions`

.

**Example: ** 200

`OutputMode`

— Format of output`'sequence'`

(default) | `'last'`

Format of output, specified as one of the following:

`'sequence'`

– Output the complete sequence.`'last'`

– Output the last time step of the sequence.

`ResetGateMode`

— Reset gate mode`'after-multiplication'`

(default) | `'before-multiplication'`

Reset gate mode, specified as one of the following:

`'after-multiplication'`

– Apply reset gate after matrix multiplication. This option is cuDNN compatible.`'before-multiplication'`

– Apply reset gate before matrix multiplication.

For more information about the reset gate calculations, see Gated Recurrent Unit Layer.

`InputSize`

— Input size`'auto'`

(default) | positive integer Input size, specified as a positive integer or `'auto'`

. If `InputSize`

is `'auto'`

, then the software automatically assigns the input size at training time.

**Example: ** 100

`StateActivationFunction`

— Activation function to update the hidden state`'tanh'`

(default) | `'softsign'`

Activation function to update the hidden state, specified as one of the following:

`'tanh'`

– Use the hyperbolic tangent function (tanh).`'softsign'`

– Use the softsign function $$\text{softsign}(x)=\frac{x}{1+\left|x\right|}$$.

The layer uses this option as the function $${\sigma}_{s}$$ in the calculations to update the hidden state.

`GateActivationFunction`

— Activation function to apply to the gates`'sigmoid'`

(default) | `'hard-sigmoid'`

Activation function to apply to the gates, specified as one of the following:

`'sigmoid'`

– Use the sigmoid function $$\sigma (x)={(1+{e}^{-x})}^{-1}$$.`'hard-sigmoid'`

– Use the hard sigmoid function$$\sigma (x)=\{\begin{array}{cc}\begin{array}{l}0\hfill \\ 0.2x+0.5\hfill \\ 1\hfill \end{array}& \begin{array}{l}\text{if}x-2.5\hfill \\ \text{if}-2.5\le x\le 2.5\hfill \\ \text{if}x2.5\hfill \end{array}\end{array}.$$

The layer uses this option as the function $${\sigma}_{g}$$ in the calculations for the layer gates.

`HiddenState`

— Initial value of the hidden statenumeric vector

Initial value of the hidden state, specified as a `NumHiddenUnits`

-by-1 numeric vector. This value corresponds to the hidden state at time step 0.

After setting this property, calls to the `resetState`

function set the hidden state to this value.

`InputWeightsInitializer`

— Function to initialize input weights`'glorot'`

(default) | `'he'`

| `'orthogonal'`

| `'narrow-normal'`

| `'zeros'`

| `'ones'`

| function handleFunction to initialize the input weights, specified as one of the following:

`'glorot'`

– Initialize the input weights with the Glorot initializer [2] (also known as Xavier initializer). The Glorot initializer independently samples from a uniform distribution with zero mean and variance`2/(InputSize + numOut)`

, where`numOut = 3*NumHiddenUnits`

.`'he'`

– Initialize the input weights with the He initializer [3]. The He initializer samples from a normal distribution with zero mean and variance`2/InputSize`

.`'orthogonal'`

– Initialize the input weights with*Q*, the orthogonal matrix given by the QR decomposition of*Z*=*Q**R*for a random matrix*Z*sampled from a unit normal distribution. [4]`'narrow-normal'`

– Initialize the input weights by independently sampling from a normal distribution with zero mean and standard deviation 0.01.`'zeros'`

– Initialize the input weights with zeros.`'ones'`

– Initialize the input weights with ones.Function handle – Initialize the input weights with a custom function. If you specify a function handle, then the function must be of the form

`weights = func(sz)`

, where`sz`

is the size of the input weights.

The layer only initializes the input weights when the
`InputWeights`

property is empty.

**Data Types: **`char`

| `string`

| `function_handle`

`RecurrentWeightsInitializer`

— Function to initialize recurrent weights`'orthogonal'`

(default) | `'glorot'`

| `'he'`

| `'narrow-normal'`

| `'zeros'`

| `'ones'`

| function handleFunction to initialize the recurrent weights, specified as one of the following:

`'orthogonal'`

– Initialize the recurrent weights with*Q*, the orthogonal matrix given by the QR decomposition of*Z*=*Q**R*for a random matrix*Z*sampled from a unit normal distribution. [4]`'glorot'`

– Initialize the recurrent weights with the Glorot initializer [2] (also known as Xavier initializer). The Glorot initializer independently samples from a uniform distribution with zero mean and variance`2/(numIn + numOut)`

, where`numIn = NumHiddenUnits`

and`numOut = 3*NumHiddenUnits`

.`'he'`

– Initialize the recurrent weights with the He initializer [3]. The He initializer samples from a normal distribution with zero mean and variance`2/NumHiddenUnits`

.`'narrow-normal'`

– Initialize the recurrent weights by independently sampling from a normal distribution with zero mean and standard deviation 0.01.`'zeros'`

– Initialize the recurrent weights with zeros.`'ones'`

– Initialize the recurrent weights with ones.Function handle – Initialize the recurrent weights with a custom function. If you specify a function handle, then the function must be of the form

`weights = func(sz)`

, where`sz`

is the size of the recurrent weights.

The layer only initializes the recurrent weights when the
`RecurrentWeights`

property is empty.

**Data Types: **`char`

| `string`

| `function_handle`

`BiasInitializer`

— Function to initialize bias`'zeros'`

(default) | `'narrow-normal'`

| `'ones'`

| function handleFunction to initialize the bias, specified as one of the following:

`zeros'`

– Initialize the bias with zeros.`'narrow-normal'`

– Initialize the bias by independently sampling from a normal distribution with zero mean and standard deviation 0.01.`'ones'`

– Initialize the bias with ones.Function handle – Initialize the bias with a custom function. If you specify a function handle, then the function must be of the form

`bias = func(sz)`

, where`sz`

is the size of the bias.

The layer only initializes the bias when the `Bias`

property is
empty.

**Data Types: **`char`

| `string`

| `function_handle`

`InputWeights`

— Input weights`[]`

(default) | matrixInput weights, specified as a matrix.

The input weight matrix is a concatenation of the three input weight matrices for the components in the GRU layer. The three matrices are concatenated vertically in the following order:

Reset gate

Update gate

Candidate state

The input weights are learnable parameters. When training a network, if `InputWeights`

is nonempty, then `trainNetwork`

uses the `InputWeights`

property as the initial value. If `InputWeights`

is empty, then `trainNetwork`

uses the initializer specified by `InputWeightsInitializer`

.

At training time, `InputWeights`

is a
`3*NumHiddenUnits`

-by-`InputSize`

matrix.

`RecurrentWeights`

— Recurrent weights`[]`

(default) | matrixRecurrent weights, specified as a matrix.

The recurrent weight matrix is a concatenation of the three recurrent weight matrices for the components in the GRU layer. The three matrices are vertically concatenated in the following order:

Reset gate

Update gate

Candidate state

The recurrent weights are learnable parameters. When training a network, if `RecurrentWeights`

is nonempty, then `trainNetwork`

uses the `RecurrentWeights`

property as the initial value. If `RecurrentWeights`

is empty, then `trainNetwork`

uses the initializer specified by `RecurrentWeightsInitializer`

.

At training time `RecurrentWeights`

is a
`3*NumHiddenUnits`

-by-`NumHiddenUnits`

matrix.

`Bias`

— Layer biases`[]`

(default) | numeric vectorLayer biases for the GRU layer, specified as a numeric vector.

The bias vector is a concatenation of the three bias vectors for the components in the GRU layer. The three vectors are concatenated vertically in the following order:

Reset gate

Update gate

Candidate state

The layer biases are learnable parameters. When training a network, if `Bias`

is nonempty, then `trainNetwork`

uses the `Bias`

property as the initial value. If `Bias`

is empty, then `trainNetwork`

uses the initializer specified by `BiasInitializer`

.

At training time, `Bias`

is a
`3*NumHiddenUnits`

-by-1 numeric vector.

`InputWeightsLearnRateFactor`

— Learning rate factor for input weights1 (default) | numeric scalar | 1-by-3 numeric vector

Learning rate factor for the input weights, specified as a numeric scalar or a 1-by-3 numeric vector.

The software multiplies this factor by the global learning rate to determine the learning rate factor for the input weights of the layer. For example, if `InputWeightsLearnRateFactor`

is 2, then the learning rate factor for the input weights of the layer is twice the current global learning rate. The software determines the global learning rate based on the settings specified with the `trainingOptions`

function.

To control the value of the learning rate factor for the three individual matrices
in `InputWeights`

, specify a 1-by-3 vector. The entries of
`InputWeightsLearnRateFactor`

correspond to the learning rate
factor of the following:

Reset gate

Update gate

Candidate state

To specify the same value for all the matrices, specify a nonnegative scalar.

**Example: **`2`

**Example: **
`[1 2 1]`

`RecurrentWeightsLearnRateFactor`

— Learning rate factor for recurrent weights1 (default) | numeric scalar | 1-by-3 numeric vector

Learning rate factor for the recurrent weights, specified as a numeric scalar or a 1-by-3 numeric vector.

The software multiplies this factor by the global learning rate to determine the learning rate for the recurrent weights of the layer. For example, if `RecurrentWeightsLearnRateFactor`

is 2, then the learning rate for the recurrent weights of the layer is twice the current global learning rate. The software determines the global learning rate based on the settings specified with the `trainingOptions`

function.

To control the value of the learning rate factor for the three individual matrices
in `RecurrentWeights`

, specify a 1-by-3 vector. The entries of
`RecurrentWeightsLearnRateFactor`

correspond to the learning rate
factor of the following:

Reset gate

Update gate

Candidate state

To specify the same value for all the matrices, specify a nonnegative scalar.

**Example: **`2`

**Example: **
`[1 2 1]`

`BiasLearnRateFactor`

— Learning rate factor for biases1 (default) | nonnegative scalar | 1-by-3 numeric vector

Learning rate factor for the biases, specified as a nonnegative scalar or a 1-by-3 numeric vector.

The software multiplies this factor by the global learning rate
to determine the learning rate for the biases in this layer. For example, if
`BiasLearnRateFactor`

is 2, then the learning rate for the biases in the
layer is twice the current global learning rate. The software determines the global learning
rate based on the settings specified with the `trainingOptions`

function.

To control the value of the learning rate factor for the three individual matrices
in `Bias`

, specify a 1-by-3 vector. The entries of
`BiasLearnRateFactor`

correspond to the learning rate factor of
the following:

Reset gate

Update gate

Candidate state

To specify the same value for all the matrices, specify a nonnegative scalar.

**Example: **
`2`

**Example: **
`[1 2 1]`

`InputWeightsL2Factor`

— L2 regularization factor for input weights1 (default) | numeric scalar | 1-by-3 numeric vector

L2 regularization factor for the input weights, specified as a numeric scalar or a 1-by-3 numeric vector.

The software multiplies this factor by the global L2 regularization factor to determine the L2 regularization factor for the input weights of the layer. For example, if `InputWeightsL2Factor`

is 2, then the L2 regularization factor for the input weights of the layer is twice the current global L2 regularization factor. The software determines the L2 regularization factor based on the settings specified with the `trainingOptions`

function.

To control the value of the L2 regularization factor for the three individual
matrices in `InputWeights`

, specify a 1-by-3 vector. The entries of
`InputWeightsL2Factor`

correspond to the L2 regularization factor
of the following:

Reset gate

Update gate

Candidate state

To specify the same value for all the matrices, specify a nonnegative scalar.

**Example: **`2`

**Example: **
`[1 2 1]`

`RecurrentWeightsL2Factor`

— L2 regularization factor for recurrent weights1 (default) | numeric scalar | 1-by-3 numeric vector

L2 regularization factor for the recurrent weights, specified as a numeric scalar or a 1-by-3 numeric vector.

The software multiplies this factor by the global L2 regularization factor to determine the L2 regularization factor for the recurrent weights of the layer. For example, if `RecurrentWeightsL2Factor`

is 2, then the L2 regularization factor for the recurrent weights of the layer is twice the current global L2 regularization factor. The software determines the L2 regularization factor based on the settings specified with the `trainingOptions`

function.

To control the value of the L2 regularization factor for the three individual
matrices in `RecurrentWeights`

, specify a 1-by-3 vector. The
entries of `RecurrentWeightsL2Factor`

correspond to the L2
regularization factor of the following:

Reset gate

Update gate

Candidate state

To specify the same value for all the matrices, specify a nonnegative scalar.

**Example: **`2`

**Example: **
`[1 2 1]`

`BiasL2Factor`

— L2 regularization factor for biases0 (default) | nonnegative scalar | 1-by-3 numeric vector

L2 regularization factor for the biases, specified as a nonnegative scalar or a 1-by-3 numeric vector.

The software multiplies this factor by the global L2
regularization factor to determine the L2 regularization for the biases in this layer. For
example, if `BiasL2Factor`

is 2, then the L2 regularization for the biases in
this layer is twice the global L2 regularization factor. You can specify the global L2
regularization factor using the `trainingOptions`

function.

To control the value of the L2 regularization factor for the three individual
matrices in `Bias`

, specify a 1-by-3 vector. The entries of
`BiasL2Factor`

correspond to the L2 regularization factor of the
following:

Reset gate

Update gate

Candidate state

To specify the same value for all the matrices, specify a nonnegative scalar.

**Example: **
`2`

**Example: **
`[1 2 1]`

`Name`

— Layer name`''`

(default) | character vector | string scalarLayer name, specified as a character vector or a string scalar. If `Name`

is set to `''`

, then the software automatically assigns a name at
training time.

**Data Types: **`char`

| `string`

`NumInputs`

— Number of inputs1 (default)

Number of inputs of the layer. This layer accepts a single input only.

**Data Types: **`double`

`InputNames`

— Input names`{'in'}`

(default)Input names of the layer. This layer accepts a single input only.

**Data Types: **`cell`

`NumOutputs`

— Number of outputs1 (default)

Number of outputs of the layer. This layer has a single output only.

**Data Types: **`double`

`OutputNames`

— Output names`{'out'}`

(default)Output names of the layer. This layer has a single output only.

**Data Types: **`cell`

Create a GRU layer with the name `'gru1'`

and 100 hidden units.

layer = gruLayer(100,'Name','gru1')

layer = GRULayer with properties: Name: 'gru1' Hyperparameters InputSize: 'auto' NumHiddenUnits: 100 OutputMode: 'sequence' StateActivationFunction: 'tanh' GateActivationFunction: 'sigmoid' Learnable Parameters InputWeights: [] RecurrentWeights: [] Bias: [] State Parameters HiddenState: [] Show all properties

Include a GRU layer in a `Layer`

array.

```
inputSize = 12;
numHiddenUnits = 100;
numClasses = 9;
layers = [ ...
sequenceInputLayer(inputSize)
gruLayer(numHiddenUnits)
fullyConnectedLayer(numClasses)
softmaxLayer
classificationLayer]
```

layers = 5x1 Layer array with layers: 1 '' Sequence Input Sequence input with 12 dimensions 2 '' GRU GRU with 100 hidden units 3 '' Fully Connected 9 fully connected layer 4 '' Softmax softmax 5 '' Classification Output crossentropyex

A GRU layer learns dependencies between time steps in time series and sequence data.

The *hidden state* of the layer at time step *t*
contains the output of the GRU layer for this time step. At each time step, the layer adds
information to or removes information from the state. The layer controls these updates using
*gates*.

The following components control the hidden state of the layer.

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

Update gate (z) | Control level of state update |

Reset gate (r) | Control level of state reset |

Candidate state ($$\tilde{h}$$) | Control level of update added to hidden state |

The learnable weights of a GRU 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}_{r}\\ {W}_{z}\\ {W}_{\tilde{h}}\end{array}\right],R=\left[\begin{array}{c}{R}_{r}\\ {R}_{z}\\ {R}_{\tilde{h}}\end{array}\right],b=\left[\begin{array}{c}{b}_{r}\\ {b}_{z}\\ {b}_{\tilde{h}}\end{array}\right],$$

where *z*, *r*, and $$\tilde{h}$$ denote the update gate, reset gate, and output gate, respectively.

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

$${h}_{t}=(1-{z}_{t})\odot {\tilde{h}}_{t}+{z}_{t}\odot {h}_{t-1}.$$

The following formulas describe the components at time step
*t*.

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

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

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

Candidate state (when
`ResetGateMode` is
`'after-multiplication'` ) | $${\tilde{h}}_{t}={\sigma}_{s}({W}_{\tilde{h}}{x}_{t}+{r}_{t}\odot \text{}({\text{R}}_{\tilde{h}}{h}_{t-1})+{b}_{\tilde{h}})$$ | |

Candidate state (when
`ResetGateMode` is
`'before-multiplication'` ) | $${\tilde{h}}_{t}={\sigma}_{s}({W}_{\tilde{h}}{x}_{t}+{R}_{\tilde{h}}({r}_{t}\odot \text{}{h}_{t-1})+{b}_{\tilde{h}})$$ |

In these calculations, $${\sigma}_{g}$$ and $${\sigma}_{s}$$ denotes the gate and state activation functions, respectively. The
`gruLayer`

function, by default, uses the sigmoid function given by $$\sigma (x)={(1+{e}^{-x})}^{-1}$$ to compute the gate activation function and the hyperbolic tangent
function (tanh) to compute the state activation function.

[1] Cho, Kyunghyun, Bart Van Merriënboer, Caglar Gulcehre, Dzmitry Bahdanau, Fethi Bougares, Holger Schwenk, and Yoshua Bengio. "Learning phrase representations using RNN encoder-decoder for statistical machine translation." *arXiv preprint arXiv:1406.1078* (2014).

[2] Glorot, Xavier, and Yoshua Bengio. "Understanding the difficulty of training deep feedforward neural networks." In *Proceedings of the thirteenth international conference on artificial intelligence and statistics*, pp. 249-256. 2010.

[3] He, Kaiming, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. "Delving deep into rectifiers: Surpassing human-level performance on imagenet classification." In *Proceedings of the IEEE international conference on computer vision*, pp. 1026-1034. 2015.

[4] Saxe, Andrew M., James L. McClelland, and Surya Ganguli. "Exact solutions to the nonlinear dynamics of learning in deep linear neural networks." *arXiv preprint arXiv:1312.6120* (2013).

`bilstmLayer`

| `classifyAndUpdateState`

| `flattenLayer`

| `lstmLayer`

| `predictAndUpdateState`

| `resetState`

| `sequenceFoldingLayer`

| `sequenceInputLayer`

| `sequenceUnfoldingLayer`

- Sequence Classification Using Deep Learning
- Time Series Forecasting Using Deep Learning
- Sequence-to-Sequence Classification Using Deep Learning
- Sequence-to-Sequence Regression Using Deep Learning
- Classify Videos Using Deep Learning
- Visualize Activations of LSTM Network
- Long Short-Term Memory Networks
- Compare Layer Weight Initializers
- Deep Learning in MATLAB
- List of Deep Learning Layers

A modified version of this example exists on your system. Do you want to open this version instead?

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

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

Select web siteYou can also select a web site from the following list:

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

- América Latina (Español)
- Canada (English)
- United States (English)

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