Bidirectional LSTM in NLP
Last Updated :
26 Feb, 2025
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:
-660.jpg)
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:

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:

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:

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.
Similar Reads
Bidirectional LSTM in NLP
In this article, we will first discuss bidirectional LSTMs and their architecture. We will then look into the implementation of a review system using Bidirectional LSTM. Finally, we will conclude this article while discussing the applications of bidirectional LSTM. Bidirectional LSTM (BiLSTM)Bidirec
8 min read
Bidirectional RNNs in NLP
The state of a recurrent network at a given time unit only knows about the inputs that have passed before it up to that point in the sentence; it is unaware of the states that will come after that. With knowledge of both past and future situations, the outcomes are significantly enhanced in some app
10 min read
Emotion Detection using Bidirectional LSTM
Emotion Detection is one of the hottest topics in research nowadays. Emotion-sensing technology can facilitate communication between machines and humans. It will also help to improve the decision-making process. Many Machine Learning Models have been proposed to recognize emotions from the text. But
10 min read
Difference Between a Bidirectional LSTM and an LSTM
Long Short-Term Memory (LSTM) networks are capable of learning long-term dependencies. They were introduced to address the vanishing and exploding gradient problems that standard RNNs face. While LSTMs are powerful in many sequence-based tasks, a variation called Bidirectional LSTM (BiLSTM) enhances
3 min read
Bidirectional Recurrent Neural Network
Recurrent Neural Networks (RNNs) are a particular class of neural networks that was created with the express purpose of processing sequential input, including speech, text, and time series data. RNNs process data as a sequence of vectors rather than feedforward neural networks, which process data as
9 min read
Building Language Models in NLP
Building language models is a fundamental task in natural language processing (NLP) that involves creating computational models capable of predicting the next word in a sequence of words. These models are essential for various NLP applications, such as machine translation, speech recognition, and te
4 min read
History and Evolution of NLP
As we know Natural language processing (NLP) is an exciting area that has grown at some stage in time, influencing the junction of linguistics, synthetic intelligence (AI), and computer technology knowledge. This article takes you on an in-depth journey through the history of NLP, diving into its co
13 min read
LSTM Based Poetry Generation Using NLP in Python
One of the major tasks that one aims to accomplish in Conversational AI is Natural Language Generation (NLG) which refers to employing models for the generation of natural language. In this article, we will get our hands on NLG by building an LSTM-based poetry generator. Note: The readers of this ar
7 min read
Self - attention in NLP
Self-attention was proposed by researchers at Google Research and Google Brain. It was proposed due to challenges faced by the encoder-decoder in dealing with long sequences. The authors also provide two variants of attention and transformer architecture. This transformer architecture generates stat
7 min read
Self -attention in NLP
Self-attention was proposed by researchers at Google Research and Google Brain. It was proposed due to challenges faced by encoder-decoder in dealing with long sequences. The authors also provide two variants of attention and transformer architecture. This transformer architecture generates the stat
5 min read