A bidirectional RNN processes a sequence in both directions and merges the resulting representations. Because RNNs are sensitive to order, the two passes can capture patterns that a single-direction pass might miss. section 13.3.6
Listing 14.21 Building an LSTM sequence model
hidden_dim = 64 inputs = keras.Input(shape=(max_length,), dtype="int32") x = one_hot_encoding(inputs) x = layers.Bidirectional(layers.LSTM(hidden_dim))(x) x = layers.Dropout(0.5)(x) outputs = layers.Dense(1, activation="sigmoid")(x) model = keras.Model(inputs, outputs, name="lstm_with_one_hot") model.compile( optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"], )
This movie-review classifier wraps an LSTM in Keras’s Bidirectional layer, then applies dropout and a sigmoid classifier. section 14.5.1
In the classifier, information can propagate forward and backward along the token sequence before the review is classified. The example uses one-hot token vectors, but they make the model expensive: each 600-word review becomes a 600-by-30,000 matrix. Training is slow, and the model reaches about 84% test accuracy; word embeddings offer an alternative to one-hot encoding. section 14.5.1
The two recurrent passes can use layers such as LSTMs or GRUs. Direction matters: reversing the input to a single LSTM is not the same as merging two passes. In temperature forecasting, a reversed-order LSTM underperforms even the commonsense baseline, illustrating the importance of processing order for that task. section 13.3.6
Listing 15.11 Building a sequence-to-sequence encoder
embed_dim = 256 hidden_dim = 1024 source = keras.Input(shape=(None,), dtype="int32", name="english") x = layers.Embedding(vocab_size, embed_dim, mask_zero=True)(source) rnn_layer = layers.GRU(hidden_dim) rnn_layer = layers.Bidirectional(rnn_layer, merge_mode="sum") encoder_output = rnn_layer(x)
A translation encoder wraps a GRU in Bidirectional and uses merge_mode="sum" to combine the two representations. section 15.2.2
Choose direction based on what the model is allowed to know:
- Use bidirectional processing when the whole input is available and a rich representation is useful, as in text classification or a translation encoder. section 14.5.1 section 15.2.2
- Keep next-token prediction unidirectional. A backward pass can expose future tokens during training, making the task artificially easy and breaking generation. section 15.1.2 section 15.2.2



