The Wayback Machine - https://web.archive.org/web/20250427200646/https://www.geeksforgeeks.org/bidirectional-recurrent-neural-network/
Open In App

Bidirectional Recurrent Neural Network

Last Updated : 27 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Recurrent Neural Networks (RNNs) are type of neural networks designed to process sequential data such as speech, text and time series. Unlike feedforward neural networks that process input as fixed-length vectors RNNs can handle sequence data by maintaining a hidden state which stores information from previous steps in the sequence.

This memory mechanism allows RNNs to capture key features within the sequence. However traditional RNNs suffer from the vanishing gradient problem where gradients become too small during backpropagation making training difficult. To address this advanced RNN architectures like Bidirectional Recurrent Neural Network. In this article we will learn more about them.

Overview of Bi-directional Recurrent Neural Network

A Bidirectional Recurrent Neural Network (BRNN) is an extension of traditional RNNs designed to process sequential data in both forward and backward directions. This enables the network to utilize both past and future context when making predictions.

It works like normal RNN by moving in forward direction, updating the hidden state depending on the current input and the prior hidden state at each time step. The backward hidden layer on the other hand analyses the input sequence in the opposite manner, updating the hidden state based on the current input and the hidden state of the next time step.

Compared to conventional unidirectional recurrent neural networks the accuracy of BRNN is improved since it can process information in both directions and account for both past and future contexts. Because the two hidden layers can complement one another and predictions are made based on the combined outputs of the two hidden layers. layers.

For example: I like apple. It is very healthy.

Here if we used normal RNN it may get confuse what we referring is it fruit or company by 1st line. But BRNN will get its context easily as it works by moving in both direction.

Bi-directional Recurrent Neural Network

Bi-directional Recurrent Neural Network

Working of Bidirectional Recurrent Neural Network

  1. Inputting a Sequence: A sequence of data points each represented as a vector with the same dimensionality is fed into a BRNN. The sequence might have different lengths.
  2. Dual Processing: Both the forward and backward directions are used to process the data. The hidden state at time step t is determined in:
    • Forward direction: Based on the input at step t and the hidden state at step t-1.
    • Backward direction: Based on the input at step t and the hidden state at step t+1.
  3. Computing the Hidden State: A non-linear activation function is applied to the weighted sum of the input and the previous hidden state. This creates a memory mechanism that enables the network to retain information from earlier steps.
  4. Determining the Output: A non-linear activation function is applied to the weighted sum of the hidden state and output weights to compute the output at each step. This output can either be:
    • The final output of the network.
    • An input to another layer for further processing.

Applications of Bidirectional Recurrent Neural Network

Bi-RNNs have been applied to various natural language processing (NLP) tasks, including:

  1. Sentiment Analysis: By taking account of both prior and subsequent context they can be utilized to categorize the sentiment of a particular sentence.
  2. Named Entity Recognition: By considering the context it can be utilized to identify entities in a sentence.
  3. Machine Translation: It can be used in encoder-decoder models for machine translation where the decoder creates the target sentence and the encoder analyses the source sentence in both directions to capture its context.
  4. Speech Recognition: Helps in transcribing audio more accurately by considering both past and future speech elements.

Advantages of BRNNs

  • Enhanced context understanding: Uses both past and future data for better predictions.
  • Improved accuracy: Useful in NLP and speech processing tasks.
  • Better handling of variable-length sequences: More flexible compared to standard RNNs.
  • Increased robustness: Can mitigate noise and irrelevant information due to forward and backward processing.

Challenges of BRNNs

  • High computational cost: Requires twice processing compared to unidirectional RNNs.
  • Longer training time: More parameters to optimize making convergence slow.
  • Limited real-time applicability: Since they require entire sequence before making predictions they are not ideal for real-time applications like live speech recognition.
  • Less interpretability: Understanding why a prediction was made is more complex than a standard RNN.

Implementation of Bi-directional Recurrent Neural Network

Here’s a simple implementation of a Bidirectional RNN using Keras and TensorFlow for sentiment analysis on the IMDb dataset available in keras:

Step 1: Load and Preprocess Data

Python
import warnings
warnings.filterwarnings('ignore')
from keras.datasets import imdb
from keras_preprocessing.sequence import pad_sequences

features = 2000
len = 50
(X_train, y_train),\
(X_test, y_test) = imdb.load_data(num_words=features)

X_train = pad_sequences(X_train, maxlen=len)
X_test = pad_sequences(X_test, maxlen=len)

Step 2: Define Model Architecture

By using Keras we will implement a Bidirectional Recurrent Neural Network model. This model will have 64 hidden units and 128 as the size of the embedding layer. While compiling a model we provide these three essential parameters:

  • optimizer – This is the method that helps to optimize the cost function by using gradient descent.
  • loss – The loss function by which we monitor whether the model is improving with training or not.
  • metrics – This helps to evaluate the model by predicting the training and the validation data.
Python
from keras.models import Sequential
from keras.layers import Embedding,\
    Bidirectional, SimpleRNN, Dense

embedding = 128
hidden = 64

model = Sequential()
model.add(Embedding(features, embedding,
                    input_length=len))
model.add(Bidirectional(SimpleRNN(hidden)))
model.add(Dense(1, activation='sigmoid'))
model.compile('adam', 'binary_crossentropy',
              metrics=['accuracy'])

Step 3: Train the Model

As we have compiled our model successfully and the data pipeline is also ready so, we can move forward toward the process of training our BRNN.

Python
batch_size = 32
epochs = 5

model.fit(X_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          validation_data=(X_test, y_test))

Step 4: Evaluate the Model

Now as we have our model ready let’s evaluate its performance on the validation data using different evaluation metrics. For this purpose, we will first predict the class for the validation data using this model and then compare the output with the true labels.

Python
loss, accuracy = model.evaluate(X_test, y_test)
print('Test accuracy:', accuracy)

Output :

Epoch 1/5
782/782 ━━━━━━━━━━━━━━━━━━━━ 41s 47ms/step – accuracy: 0.6317 – loss: 0.6182 – val_accuracy: 0.7826 – val_loss: 0.4606
Epoch 2/5
782/782 ━━━━━━━━━━━━━━━━━━━━ 36s 46ms/step – accuracy: 0.8107 – loss: 0.4193 – val_accuracy: 0.7833 – val_loss: 0.4763
Epoch 3/5
782/782 ━━━━━━━━━━━━━━━━━━━━ 38s 42ms/step – accuracy: 0.8567 – loss: 0.3324 – val_accuracy: 0.7858 – val_loss: 0.5230
Epoch 4/5
782/782 ━━━━━━━━━━━━━━━━━━━━ 44s 46ms/step – accuracy: 0.9154 – loss: 0.2180 – val_accuracy: 0.7649 – val_loss: 0.5724
Epoch 5/5
782/782 ━━━━━━━━━━━━━━━━━━━━ 42s 48ms/step – accuracy: 0.9610 – loss: 0.1162 – val_accuracy: 0.7314 – val_loss: 0.7634
782/782 ━━━━━━━━━━━━━━━━━━━━ 7s 9ms/step – accuracy: 0.7261 – loss: 0.7847
Test accuracy: 0.731440007686615

Here we achieved a accuracy of 73% and we can increase it accuracy by more fine tuning.



Next Article

Similar Reads