The Wayback Machine - https://web.archive.org/web/20250226101651/https://www.geeksforgeeks.org/bidirectional-lstm-in-nlp/
Open In App

Bidirectional LSTM in NLP

Last Updated : 26 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Long Short-Term Memory (LSTM) are a type of Neural Network designed to handle long-term dependencies and overcome the vanishing gradient problem of RNN. It uses a memory cell along with input, forget and output gates to selectively retain or discard information.

Bidirectional Long Short-Term Memory (BiLSTM) is an extension of the traditional LSTM (Long Short-Term Memory) network. Unlike conventional LSTMs that process sequences in only one direction, BiLSTMs allow information to flow from both forward and backward enabling them to capture richer contextual information. This makes BiLSTMs particularly effective for tasks where understanding both past and future context is crucial. In this article we will learn more about them and implement a sentiment analysis model using BiLSTM in TensorFlow.

Understanding Bidirectional LSTM (BiLSTM)

A Bidirectional LSTM (BiLSTM) consists of two separate LSTM layers:

  • Forward LSTM: Processes the sequence from start to end
  • Backward LSTM: Processes the sequence from end to start

The outputs of both LSTMs are then combined to form the final output. Mathematically, the final output at time t is computed as:

[Tex]p_t = p_{t_f} + p_{t_b}[/Tex]

where,

  • [Tex]p_t  [/Tex]: Final probability vector of the network.
  • [Tex]p_{tf} [/Tex]: Probability vector from the forward LSTM network.
  • [Tex]p_{tb} [/Tex]: Probability vector from the backward LSTM network.

The following diagram represents the BiLSTM layer:

Bidirectional LSTM layer Architecture

Bidirectional LSTM layer Architecture

Here 

  • [Tex]X_i [/Tex]is the input token 
  • [Tex]Y_i [/Tex]is the output token
  • A and [Tex]A’ [/Tex]are Forward and backward LSTM units
  • The final output of [Tex]Y_i [/Tex]is the combination of [Tex]A [/Tex]and [Tex]A’ [/Tex]LSTM nodes.

Implementation: Sentiment Analysis Using BiLSTM

Now let us look into an implementation of a review system using BiLSTM layers in Python using Tensorflow. We would be performing sentiment analysis on the IMDB movie review dataset. We would implement the network from scratch and train it to identify if the review is positive or negative.

Step 1: Importing Libraries

To implement sentiment analysis using bidirectional LSTM, we will be using python libraries like numpy, pandas and tenserflow. Tenserflow is the key library for building our model.

Python
import tensorflow as tf
import tensorflow_datasets as tfds
import numpy as np
import matplotlib.pyplot as plt

Step 2: Loading and Preparing the IMDB Dataset

  • We loaded IMDB dataset from tenserflow which contains 25,000 labeled movie reviews for training and testing.
  • Shuffling ensures that the model does not learn patterns based on the order of reviews.
Python
dataset = tfds.load('imdb_reviews', as_supervised=True)
train_dataset, test_dataset = dataset['train'], dataset['test']

batch_size = 32

train_dataset = train_dataset.shuffle(10000).batch(batch_size)
test_dataset = test_dataset.batch(batch_size)

Printing a sample review and its label from the training set.

Python
example, label = next(iter(train_dataset))
print('Text:\n', example.numpy()[0])
print('\nLabel: ', label.numpy()[0])

Output:

Text: b “Having seen men Behind the Sun … 1 as a treatment of the subject).”
Label: 0

Step 3: Text Vectorization

We will first perform text vectorization and let the encoder map all the words in the training dataset to a token. We can also see in the example below how we can encode and decode the sample review into a vector of integers.

  • vectorize_layer : tokenizes and normalizes the text.
  • It converts words into numeric values for the neural network to process easily.
Python
vectorize_layer = tf.keras.layers.TextVectorization(output_mode='int', output_sequence_length=100)

vectorize_layer.adapt(train_dataset.map(lambda x, y: x))

Step 4: Model Architecture (BiLSTM Layers)

In this section we define the model for sentiment analysis. The first layer Text Vectorization encodes input text into token indices. These tokens are passed through an embedding layer which maps words to trainable vectors. Over training these vectors adjust such that words with similar meanings have similar representations. The Bidirectional LSTM layers then process these sequences to generate meaningful representations which are converted for classification.

  • Embedding Layer: Converts words into trainable word vectors.
  • Bidirectional LSTM (64 units): First layer processes in both directions.
  • Bidirectional LSTM (32 units): Second layer refines the learned patterns.
  • Dense Layers: Fully connected layers for classification.
  • Final Output: A single neuron output to classify sentiment.
Python
model = tf.keras.Sequential([
    vectorize_layer,  
    tf.keras.layers.Embedding(len(vectorize_layer.get_vocabulary()), 64, mask_zero=True), 
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences=True)),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(1) 
])

model.summary()

model.compile(
    loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
    optimizer=tf.keras.optimizers.Adam(),
    metrics=['accuracy']
)

Output:

Screenshot-2025-02-26-111049

Model Architecture

Step 5: Model Training

Now we will train the model we defined in the previous step for five epochs.

Python
history = model.fit(
    train_dataset, 
    epochs=5,
    validation_data=test_dataset,
)

Output:

Screenshot-2025-02-26-111302

Model Training

Plotting training vs validation accuracy and training vs validation loss.

Python
history_dict = history.history
acc = history_dict['accuracy']
val_acc = history_dict['val_accuracy']
loss = history_dict['loss']
val_loss = history_dict['val_loss']

plt.figure(figsize=(8, 4))

plt.subplot(1, 2, 1)
plt.plot(acc)
plt.plot(val_acc)
plt.title('Training and Validation Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend(['Accuracy', 'Validation Accuracy'])

plt.subplot(1, 2, 2)
plt.plot(loss)
plt.plot(val_loss)
plt.title('Training and Validation Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend(['Loss', 'Validation Loss'])

plt.show()

Output:

download

The plot of training and validation accuracy and loss

The model learns well on training data reaching 98% accuracy but struggles with validation data staying around 86%. The increasing validation loss shows overfitting meaning the model remembers training data but doesn’t generalize well. To fix this we can use Dropout, L2 regularization, early stopping or simplify the model to improve real-world performance.



Next Article

Similar Reads

three90RightbarBannerImg