Skip to contents

Base class for recurrent layers

Usage

layer_rnn(
  object,
  cell,
  return_sequences = FALSE,
  return_state = FALSE,
  go_backwards = FALSE,
  stateful = FALSE,
  unroll = FALSE,
  zero_output_for_mask = FALSE,
  ...
)

Arguments

object

Object to compose the layer with. A tensor, array, or sequential model.

cell

A RNN cell instance or a list of RNN cell instances. A RNN cell is a class that has:

  • A call(input_at_t, states_at_t) method, returning (output_at_t, states_at_t_plus_1). The call method of the cell can also take the optional argument constants, see section "Note on passing external constants" below.

  • A state_size attribute. This can be a single integer (single state) in which case it is the size of the recurrent state. This can also be a list of integers (one size per state).

  • A output_size attribute, a single integer.

  • A get_initial_state(batch_size=NULL) method that creates a tensor meant to be fed to call() as the initial state, if the user didn't specify any initial state via other means. The returned initial state should have shape (batch_size, cell.state_size). The cell might choose to create a tensor full of zeros, or other values based on the cell's implementation. inputs is the input tensor to the RNN layer, with shape (batch_size, timesteps, features). If this method is not implemented by the cell, the RNN layer will create a zero filled tensor with shape (batch_size, cell$state_size). In the case that cell is a list of RNN cell instances, the cells will be stacked on top of each other in the RNN, resulting in an efficient stacked RNN.

return_sequences

Boolean (default FALSE). Whether to return the last output in the output sequence, or the full sequence.

return_state

Boolean (default FALSE). Whether to return the last state in addition to the output.

go_backwards

Boolean (default FALSE). If TRUE, process the input sequence backwards and return the reversed sequence.

stateful

Boolean (default FALSE). If TRUE, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch.

unroll

Boolean (default FALSE). If TRUE, the network will be unrolled, else a symbolic loop will be used. Unrolling can speed-up a RNN, although it tends to be more memory-intensive. Unrolling is only suitable for short sequences.

zero_output_for_mask

Boolean (default FALSE). Whether the output should use zeros for the masked timesteps. Note that this field is only used when return_sequences is TRUE and mask is provided. It can useful if you want to reuse the raw output sequence of the RNN without interference from the masked timesteps, e.g., merging bidirectional RNNs.

...

For forward/backward compatability.

Value

The return value depends on the value provided for the first argument. If object is:

  • a keras_model_sequential(), then the layer is added to the sequential model (which is modified in place). To enable piping, the sequential model is also returned, invisibly.

  • a keras_input(), then the output tensor from calling layer(input) is returned.

  • NULL or missing, then a Layer instance is returned.

Call Arguments

  • inputs: Input tensor.

  • initial_state: List of initial state tensors to be passed to the first call of the cell.

  • mask: Binary tensor of shape [batch_size, timesteps] indicating whether a given timestep should be masked. An individual TRUE entry indicates that the corresponding timestep should be utilized, while a FALSE entry indicates that the corresponding timestep should be ignored.

  • training: Python boolean indicating whether the layer should behave in training mode or in inference mode. This argument is passed to the cell when calling it. This is for use with cells that use dropout.

Input Shape

3-D tensor with shape (batch_size, timesteps, features).

Output Shape

  • If return_state: a list of tensors. The first tensor is the output. The remaining tensors are the last states, each with shape (batch_size, state_size), where state_size could be a high dimension tensor shape.

  • If return_sequences: 3D tensor with shape (batch_size, timesteps, output_size).

Masking:

This layer supports masking for input data with a variable number of timesteps. To introduce masks to your data, use a layer_embedding() layer with the mask_zero parameter set to TRUE.

Note on using statefulness in RNNs:

You can set RNN layers to be 'stateful', which means that the states computed for the samples in one batch will be reused as initial states for the samples in the next batch. This assumes a one-to-one mapping between samples in different successive batches.

To enable statefulness:

  • Specify stateful = TRUE in the layer constructor.

  • Specify a fixed batch size for your model, by passing

    • If sequential model: input_batch_shape = c(...) to the keras_model_sequential() call.

    • Else for functional model with 1 or more input layers: batch_shape = c(...) to the layer_input() call(s).

    This is the expected shape of your inputs including the batch size. It should be a list of integers, e.g. c(32, 10, 100).

  • Specify shuffle = FALSE when calling fit().

To reset the states of your model, call reset_state() on either a specific layer, or on your entire model.

Note on specifying the initial state of RNNs:

You can specify the initial state of RNN layers symbolically by calling them with the keyword argument initial_state. The value of initial_state should be a tensor or list of tensors representing the initial state of the RNN layer.

Examples

First, let's define a RNN Cell, as a layer subclass.

rnn_cell_minimal <- Layer(
  "MinimalRNNCell",

  initialize = function(units, ...) {
    super$initialize(...)
    self$units <- as.integer(units)
    self$state_size <- as.integer(units)
  },

  build = function(input_shape) {
    self$kernel <- self$add_weight(
      shape = shape(tail(input_shape, 1), self$units),
      initializer = 'uniform',
      name = 'kernel'
    )
    self$recurrent_kernel <- self$add_weight(
      shape = shape(self$units, self$units),
      initializer = 'uniform',
      name = 'recurrent_kernel'
    )
    self$built <- TRUE
  },

  call = function(inputs, states) {
    prev_output <- states[[1]]
    h <- op_matmul(inputs, self$kernel)
    output <- h + op_matmul(prev_output, self$recurrent_kernel)
    list(output, list(output))
  }
)

Let's use this cell in a RNN layer:

cell <- rnn_cell_minimal(units = 32)
x <- layer_input(shape = shape(NULL, 5))
layer <- layer_rnn(cell = cell)
y <- layer(x)

cells <- list(rnn_cell_minimal(units = 32), rnn_cell_minimal(units = 4))
x <- layer_input(shape = shape(NULL, 5))
layer <- layer_rnn(cell = cells)
y <- layer(x)

See also

Other rnn cells:
rnn_cell_gru()
rnn_cell_lstm()
rnn_cell_simple()

Other rnn layers:
layer_bidirectional()
layer_conv_lstm_1d()
layer_conv_lstm_2d()
layer_conv_lstm_3d()
layer_gru()
layer_lstm()
layer_simple_rnn()
layer_time_distributed()
rnn_cell_gru()
rnn_cell_lstm()
rnn_cell_simple()
rnn_cells_stack()

Other layers:
Layer()
layer_activation()
layer_activation_elu()
layer_activation_leaky_relu()
layer_activation_parametric_relu()
layer_activation_relu()
layer_activation_softmax()
layer_activity_regularization()
layer_add()
layer_additive_attention()
layer_alpha_dropout()
layer_attention()
layer_average()
layer_average_pooling_1d()
layer_average_pooling_2d()
layer_average_pooling_3d()
layer_batch_normalization()
layer_bidirectional()
layer_category_encoding()
layer_center_crop()
layer_concatenate()
layer_conv_1d()
layer_conv_1d_transpose()
layer_conv_2d()
layer_conv_2d_transpose()
layer_conv_3d()
layer_conv_3d_transpose()
layer_conv_lstm_1d()
layer_conv_lstm_2d()
layer_conv_lstm_3d()
layer_cropping_1d()
layer_cropping_2d()
layer_cropping_3d()
layer_dense()
layer_depthwise_conv_1d()
layer_depthwise_conv_2d()
layer_discretization()
layer_dot()
layer_dropout()
layer_einsum_dense()
layer_embedding()
layer_feature_space()
layer_flatten()
layer_flax_module_wrapper()
layer_gaussian_dropout()
layer_gaussian_noise()
layer_global_average_pooling_1d()
layer_global_average_pooling_2d()
layer_global_average_pooling_3d()
layer_global_max_pooling_1d()
layer_global_max_pooling_2d()
layer_global_max_pooling_3d()
layer_group_normalization()
layer_group_query_attention()
layer_gru()
layer_hashed_crossing()
layer_hashing()
layer_identity()
layer_integer_lookup()
layer_jax_model_wrapper()
layer_lambda()
layer_layer_normalization()
layer_lstm()
layer_masking()
layer_max_pooling_1d()
layer_max_pooling_2d()
layer_max_pooling_3d()
layer_maximum()
layer_mel_spectrogram()
layer_minimum()
layer_multi_head_attention()
layer_multiply()
layer_normalization()
layer_permute()
layer_random_brightness()
layer_random_contrast()
layer_random_crop()
layer_random_flip()
layer_random_rotation()
layer_random_translation()
layer_random_zoom()
layer_repeat_vector()
layer_rescaling()
layer_reshape()
layer_resizing()
layer_separable_conv_1d()
layer_separable_conv_2d()
layer_simple_rnn()
layer_spatial_dropout_1d()
layer_spatial_dropout_2d()
layer_spatial_dropout_3d()
layer_spectral_normalization()
layer_string_lookup()
layer_subtract()
layer_text_vectorization()
layer_tfsm()
layer_time_distributed()
layer_torch_module_wrapper()
layer_unit_normalization()
layer_upsampling_1d()
layer_upsampling_2d()
layer_upsampling_3d()
layer_zero_padding_1d()
layer_zero_padding_2d()
layer_zero_padding_3d()
rnn_cell_gru()
rnn_cell_lstm()
rnn_cell_simple()
rnn_cells_stack()