|TensorFlow 1 version||View source on GitHub|
Base class for recurrent layers.
Compat aliases for migration
See Migration guide for more details.
tf.keras.layers.RNN( cell, return_sequences=False, return_state=False, go_backwards=False, stateful=False, unroll=False, time_major=False, **kwargs )
Used in the notebooks
|Used in the guide||Used in the tutorials|
See the Keras RNN API guide for details about the usage of RNN API.
A RNN cell instance or a list of RNN cell instances.
A RNN cell is a class that has:
The shape format of the
inputs: Input tensor.
mask: Binary tensor of shape
[batch_size, timesteps]indicating whether a given timestep should be masked. An individual
Trueentry indicates that the corresponding timestep should be utilized, while a
Falseentry 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.
initial_state: List of initial state tensors to be passed to the first call of the cell.
constants: List of constant tensors to be passed to the cell at each timestep.
N-D tensor with shape
[batch_size, timesteps, ...] or
[timesteps, batch_size, ...] when time_major is True.
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_sizecould be a high dimension tensor shape.
return_sequences: N-D tensor with shape
[batch_size, timesteps, output_size], where
output_sizecould be a high dimension tensor shape, or
[timesteps, batch_size, output_size]when
- Else, N-D tensor with shape
[batch_size, output_size], where
output_sizecould be a high dimension tensor shape.
This layer supports masking for input data with a variable number
of timesteps. To introduce masks to your data,
use an [tf.keras.layers.Embedding] layer with the
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: `batch_input_shape=(...)` to the first layer in your model. Else for functional model with 1 or more Input layers: `batch_shape=(...)` to all the first layers in your model. This is the expected shape of your inputs *including the batch size*. It should be a tuple of integers, e.g. `(32, 10, 100)`. - Specify `shuffle=False` when calling `fit()`.
To reset the states of your model, call
.reset_states() 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.
You can specify the initial state of RNN layers numerically by
reset_states with the keyword argument
states. The value of
states should be a numpy array or list of numpy arrays representing
the initial state of the RNN layer.
Note on passing external constants to RNNs:
You can pass "external" constants to the cell using the
keyword argument of
RNN.__call__ (as well as
RNN.call) method. This
requires that the
cell.call method accepts the same keyword argument
constants. Such constants can be used to condition the cell
transformation on additional static inputs (not changing over time),
a.k.a. an attention mechanism.
# First, let's define a RNN Cell, as a layer subclass. class MinimalRNNCell(keras.layers.Layer): def __init__(self, units, **kwargs): self.units = units self.state_size = units super(MinimalRNNCell, self).__init__(**kwargs) def build(self, input_shape): self.kernel = self.add_weight(shape=(input_shape[-1], self.units), initializer='uniform', name='kernel') self.recurrent_kernel = self.add_weight( shape=(self.units, self.units), initializer='uniform', name='recurrent_kernel') self.built = True def call(self, inputs, states): prev_output = states h = backend.dot(inputs, self.kernel) output = h + backend.dot(prev_output, self.recurrent_kernel) return output, [output] # Let's use this cell in a RNN layer: ce