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

Bidirectional LSTM in NLP

Last Updated : 08 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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)

Bidirectional LSTM or BiLSTM is a term used for a sequence model which contains two LSTM layers, one for processing input in the forward direction and the other for processing in the backward direction. It is usually used in NLP-related tasks. The intuition behind this approach is that by processing data in both directions, the model is able to better understand the relationship between sequences (e.g. knowing the following and preceding words in a sentence).

To better understand this let us see an example. The first statement is “Server can you bring me this dish” and the second statement is “He crashed the server”. In both these statements, the word server has different meanings and this relationship depends on the following and preceding words in the statement. The bidirectional LSTM helps the machine to understand this relationship better than compared with unidirectional LSTM. This ability of BiLSTM makes it a suitable architecture for tasks like sentiment analysis, text classification, and machine translation.

Architecture

The architecture of bidirectional LSTM comprises of two unidirectional LSTMs which process the sequence in both forward and backward directions. This architecture can be interpreted as having two separate LSTM networks, one gets the sequence of tokens as it is while the other gets in the reverse order. Both of these LSTM network returns a probability vector as output and the final output is the combination of both of these probabilities. It can be represented as:

p_t = p_t^f + p_t^b

where,

  • p_t    : Final probability vector of the network.
  • p_t^f    : Probability vector from the forward LSTM network.
  • p_t^b    : Probability vector from the backward LSTM network.
Bidirectional LSTM layer Architecture

Bidirectional LSTM layer Architecture

Figure 1 describes the architecture of the BiLSTM layer where X_i    is the input token, Y_i    is the output token, and A    and A'    are LSTM nodes. The final output of Y_i    is the combination of A    and A'    LSTM nodes.

Now, let us look into an implementation of a review system using BiLSTM layers in Python using the Tensorflow library. 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.

Importing Libraries and Dataset

Python libraries make it very easy for us to handle the data and perform typical and complex tasks with a single line of code.

  • Numpy – Numpy arrays are very fast and can perform large computations in a very short time.
  • Matplotlib – This library is used to draw visualizations.
  • TensorFlow – This is an open-source library that is used for Machine Learning and Artificial intelligence and provides a range of functions to achieve complex functionalities with single lines of code.

Python3

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

                    

IMDB movies review dataset is the dataset for binary sentiment classification containing 25,000 highly polar movie reviews for training, and 25,000 for testing. This dataset can be acquired from this website or we can also use the tensorflow_datasets library to acquire it.

Python3

# Obtain the imdb review dataset from tensorflow datasets
dataset = tfds.load('imdb_reviews', as_supervised=True)
  
# Seperate test and train datasets
train_dataset, test_dataset = dataset['train'], dataset['test']
  
# Split the test and train data into batches of 32
# and shuffling the training set
batch_size = 32
train_dataset = train_dataset.shuffle(10000)
train_dataset = train_dataset.batch(batch_size)
test_dataset = test_dataset.batch(batch_size)

                    

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

Python3

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

                    

Output:

Text:
b'Stumbling upon this HBO special late one night, I was absolutely taken by this
attractive British "executive transvestite." I have never laughed so hard over
European History or any of the other completely worthwhile point Eddie Izzard made.
I laughed so much that I woke up my mother sleeping at the other end of the house...'
Label: 1

Model Architecture

In this section, we will define the model we will use for sentiment analysis. The initial layer of this architecture is the text vectorization layer, responsible for encoding the input text into a sequence of token indices. These tokens are subsequently fed into the embedding layer, where each word is assigned a trainable vector. After enough training, these vectors tend to adjust themselves such that words with similar meanings have similar vectors. This data is then passed to Bidirectional LSTM layers which process these sequences and finally convert it to a single logit as the classification output.

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.

Python3

# Using the TextVectorization layer to normalize, split, and map strings
# to integers.
encoder = tf.keras.layers.TextVectorization(max_tokens=10000)
encoder.adapt(train_dataset.map(lambda text, _: text))
  
# Extracting the vocabulary from the TextVectorization layer.
vocabulary = np.array(encoder.get_vocabulary())
  
# Encoding a test example and decoding it back.
original_text = example.numpy()[0]
encoded_text = encoder(original_text).numpy()
decoded_text = ' '.join(vocabulary[encoded_text])
  
print('original: ', original_text)
print('encoded: ', encoded_text)
print('decoded: ', decoded_text)

                    

Output:

original: 
b'Stumbling upon this HBO special late one night, I was absolutely taken by this
attractive British "executive transvestite." I have never laughed so hard over
European History or any of the other completely worthwhile point Eddie Izzard made.
I laughed so much that I woke up my mother sleeping at the other end of the house...'
encoded:
[9085 720 11 4335 309 534 29 311 10 14 412 602 33 11
1523 683 3505 1 10 26 110 1434 38 264 126 1835 489 42
99 5 2 81 325 2601 215 1781 9352 91 10 1434 38 73
12 10 9259 58 56 462 2703 31 2 81 129 5 2 313]
decoded:
stumbling upon this hbo special late one night i was absolutely taken by this
attractive british executive [UNK] i have never laughed so hard over european history
or any of the other completely worthwhile point eddie izzard made i laughed so much
that i woke up my mother sleeping at the other end of the house

Now, we will use this trained encoder along with Bidirectional LSTM layers to define a model as discussed earlier.

We will implement a Sequential model which will contain the following parts:

  • First layer is the embedding layer used to create a embedding for the inpurt text.
  • Then bidirectional LSTM layers in the network to learn greater dependencies in the network.
  • Then we will have two fully connected layers whose final output will be teh probability of being the positive review.

Python3

# Creating the model
model = tf.keras.Sequential([
    encoder,
    tf.keras.layers.Embedding(
        len(encoder.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)
])
  
# Summary of the model
model.summary()
  
# Compile the model
model.compile(
    loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
    optimizer=tf.keras.optimizers.Adam(),
    metrics=['accuracy']
)

                    

Output:

Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
text_vectorization (TextVec (None, None) 0
torization)

embedding (Embedding) (None, None, 64) 640000

bidirectional (Bidirectiona (None, None, 128) 66048
l)

bidirectional_1 (Bidirectio (None, 64) 41216
nal)

dense (Dense) (None, 64) 4160

dense_1 (Dense) (None, 1) 65

=================================================================
Total params: 751,489
Trainable params: 751,489
Non-trainable params: 0
_________________________________________________________________

Model Training

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

Python3

# Training the model and validating it on test set
history = model.fit(
    train_dataset, 
    epochs=5,
    validation_data=test_dataset,
)

                    

Output:

Epoch 1/5
782/782 [==============================] - 1209s 2s/step - loss: 0.3657 -
accuracy: 0.8266 - val_loss: 0.3110 - val_accuracy: 0.8441
Epoch 2/5
782/782 [==============================] - 1269s 2s/step - loss: 0.2147 -
accuracy: 0.9126 - val_loss: 0.3566 - val_accuracy: 0.8590
Epoch 3/5
782/782 [==============================] - 1146s 1s/step - loss: 0.1616 -
accuracy: 0.9380 - val_loss: 0.3764 - val_accuracy: 0.8670
Epoch 4/5
782/782 [==============================] - 1963s 3s/step - loss: 0.0962 -
accuracy: 0.9647 - val_loss: 0.4271 - val_accuracy: 0.8564
Epoch 5/5
782/782 [==============================] - 1121s 1s/step - loss: 0.0573 -
accuracy: 0.9796 - val_loss: 0.5516 - val_accuracy: 0.8575

Plotting the training and validation accuracy and loss plots.

Python3

# Plotting the accuracy and loss over time
  
# Training history
history_dict = history.history
  
# Seperating validation and training accuracy
acc = history_dict['accuracy']
val_acc = history_dict['val_accuracy']
  
# Seperating validation and training loss
loss = history_dict['loss']
val_loss = history_dict['val_loss']
  
# Plotting
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 plot of training and validation accuracy and loss

Model Evaluation

Now, we will test the trained model with a random review and check its output.

Python3

# Making predictions
sample_text = (
    '''The movie by GeeksforGeeks was so good and the animation are so dope. 
    I would recommend my friends to watch it.'''
)
predictions = model.predict(np.array([sample_text]))
print(*predictions[0])
  
# Print the label based on the prediction
if predictions[0] > 0:
    print('The review is positive')
else:
    print('The review is negative')

                    

Output:

1/1 [==============================] - 0s 33ms/step
5.414222
The review is positive

Applications of BiDirectional LSTM

Some of the popular application which uses BiLSTM are sentiment analysis, text classification, text generation, and machine translation. You can also explore some of these applications in the following articles:

  1. LSTM-Based Poetry Generation Using NLP in Python
  2. Emotion Detection using Bidirectional LSTM


Similar Reads

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 this capability. Let's explore the differences be
3 min read
AWD-LSTM : Unraveling the Secrets of DropConnect in LSTM
AWD LSTM is a machine learning technique that helps in understanding patterns over time, like predicting what comes next in a sequence of data. Let's explore AWD LSTM in the article. What is AWD-LSTM?AWD-LSTM stands for ASGD Weight-Dropped Long Short-Term Memory, represents a significant advancement in the realm of recurrent neural networks (RNNs).
7 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, in this article, our focus is on the Bidirection
10 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 article are expected to be familiar with LSTM. In or
7 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 applications, such as language modeling. In the case
10 min read
Long short-term memory (LSTM) RNN in Tensorflow
This article discusses the concept of "Recurrent Neural Networks(RNN)" and "Long Short Term Memory(LSTM)" and their implementation using Python programming language and the necessary library. RECURRENT NEURAL NETWORKIt is one of the oldest networks which was created in the year the 1980s but at the time there is no computation power of computers so
5 min read
What's the difference of stateless LSTM and a normal feed-forward NN?
Answer: Stateless LSTM disregards past sequences, while a feed-forward neural network lacks internal memory and processes inputs sequentially.Here is a comparison between stateless LSTM and a normal feed-forward NN: AspectStateless LSTMFeed-Forward Neural Network (NN)ArchitectureIncorporates Long Short-Term Memory (LSTM) cells that allow capturing
2 min read
What's the Difference Between the Cell and Hidden State in LSTM?
Answer: In an LSTM (Long Short-Term Memory) network, the cell state represents the memory of the network, storing information over time, while the hidden state contains the information that is passed to the next time step.Here's the difference between the cell state and hidden state in LSTM presented in a tabular form: AspectCell State (Ct)Hidden S
1 min read
LSTM Full Form - Long Short-Term Memory
LSTM stands for Long Short-Term Memory. It is a type of recurrent neural network (RNN) architecture that is designed to remember long-term dependencies in sequence data. Unlike traditional RNNs, LSTM networks have a more complex architecture that allows them to learn and remember over long sequences, making them particularly effective for tasks suc
1 min read
What is LSTM - Long Short Term Memory?
LSTM excels in sequence prediction tasks, capturing long-term dependencies. Ideal for time series, machine translation, and speech recognition due to order dependence. The article provides an in-depth introduction to LSTM, covering the LSTM model, architecture, working principles, and the critical role they play in various applications. What is LST
10 min read
Long Short-Term Memory (LSTM) using R
Implementing Long Short-Term Memory (LSTM) networks in R involves using libraries that support deep learning frameworks like TensorFlow or Keras. These frameworks provide high-level interfaces for efficiently building and training LSTM models. Here's a step-by-step guide to implementing LSTM using R Programming Language. What are LSTM Networks?LSTM
5 min read
Difference Between "Hidden" and "Output" in PyTorch LSTM
Long Short-Term Memory (LSTM) networks are a type of recurrent neural network (RNN) that are widely used for sequence prediction tasks. In PyTorch, the nn.LSTM module is a powerful tool for implementing these networks. However, understanding the difference between the "hidden" and "output" states of an LSTM can be confusing for many. This article a
4 min read
Adding Attention Layer to a Bi-LSTM
The integration of attention mechanisms with Bidirectional Long Short-Term Memory (Bi-LSTM) networks has become a popular approach in various natural language processing (NLP) tasks. The attention mechanism allows the model to focus on specific parts of the input sequence, enhancing its ability to capture relevant information. This article provides
5 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 a fixed-length vector. Each vector is processed d
9 min read
Bidirectional Search in AI
Bidirectional search in AI is an algorithm that searches simultaneously from both the initial state and the goal state, meeting in the middle to reduce search time. The aim of the article is to provide an in-depth understanding of the bidirectional search algorithm, its working mechanism, benefits, and practical applications in artificial intellige
9 min read
NLP | Classifier-based Chunking | Set 2
Using the data from the treebank_chunk corpus let us evaluate the chunkers (prepared in the previous article). Code #1 : C/C++ Code # loading libraries from chunkers import ClassifierChunker from nltk.corpus import treebank_chunk train_data = treebank_chunk.chunked_sents()[:3000] test_data = treebank_chunk.chunked_sents()[3000:] # initializing chun
2 min read
BART Model for Text Auto Completion in NLP
BART stands for Bidirectional and Auto-Regressive Transformer. It is a denoising autoencoder that is a pre-trained sequence-to-sequence method, that uses masked language modeling for Natural Language Generation and Translation. It is developed by Lewis et al. in 2019. BART architecture is similar to an encoder-decoder network except that it uses a
7 min read
Processing text using NLP | Basics
In this article, we will be learning the steps followed to process the text data before using it to train the actual Machine Learning Model. Importing Libraries The following must be installed in the current working environment: NLTK Library: The NLTK library is a collection of libraries and programs written for processing of English language writt
2 min read
Readability Index in Python(NLP)
Readability is the ease with which a reader can understand a written text. In natural language, the readability of text depends on its content (the complexity of its vocabulary and syntax). It focuses on the words we choose, and how we put them into sentences and paragraphs for the readers to comprehend. Our main objective in writing is to pass alo
6 min read
Feature Extraction Techniques - NLP
Introduction : This article focuses on basic feature extraction techniques in NLP to analyse the similarities between pieces of text. Natural Language Processing (NLP) is a branch of computer science and machine learning that deals with training computers to process a large amount of human (natural) language data. Briefly, NLP is the ability of com
11 min read
NLP | Chunking and chinking with RegEx
Chunk extraction or partial parsing is a process of meaningful extracting short phrases from the sentence (tagged with Part-of-Speech). Chunks are made up of words and the kinds of words are defined using the part-of-speech tags. One can even define a pattern or words that can't be a part of chuck and such words are known as chinks. A ChunkRule cla
2 min read
NLP | Training Unigram Tagger
A single token is referred to as a Unigram, for example - hello; movie; coding. This article is focused on unigram tagger. Unigram Tagger: For determining the Part of Speech tag, it only uses a single word. UnigramTagger inherits from NgramTagger, which is a subclass of ContextTagger, which inherits from SequentialBackoffTagger. So, UnigramTagger i
2 min read
NLP | Synsets for a word in WordNet
WordNet is the lexical database i.e. dictionary for the English language, specifically designed for natural language processing. Synset is a special kind of a simple interface that is present in NLTK to look up words in WordNet. Synset instances are the groupings of synonymous words that express the same concept. Some of the words have only one Syn
2 min read
NLP | Word Collocations
Collocations are two or more words that tend to appear frequently together, for example - United States. There are many other words that can come after United, such as the United Kingdom and United Airlines. As with many aspects of natural language processing, context is very important. And for collocations, context is everything. In the case of co
3 min read
NLP | WuPalmer - WordNet Similarity
How does Wu & Palmer Similarity work? It calculates relatedness by considering the depths of the two synsets in the WordNet taxonomies, along with the depth of the LCS (Least Common Subsumer). The score can be 0 < score <= 1. The score can never be zero because the depth of the LCS is never zero (the depth of the root of taxonomy is one).
2 min read
NLP | Splitting and Merging Chunks
SplitRule class : It splits a chunk based on the specified split pattern for the purpose. It is specified like <NN.*>}{<.*> i.e. two opposing curly braces surrounded by a pattern on either side. MergeRule class : It merges two chunks together based on the ending of the first chunk and the beginning of the second chunk. It is specified l
2 min read
NLP | Chunking Rules
Below are the steps involved for Chunking - Conversion of sentence to a flat tree. Creation of Chunk string using this tree.Creation of RegexpChunkParser by parsing the grammar using RegexpParser.Applying the created chunk rule to the ChunkString that matches the sentence into a chunk. Splitting the bigger chunk to a smaller chunk using the defined
2 min read
NLP | Leacock Chordorow (LCH) and Path similarity for Synset
Path-based Similarity: It is a similarity measure that finds the distance that is the length of the shortest path between two synsets. Leacock Chordorow (LCH) : It is a similarity measure which is an extended version of Path-based similarity as it incorporates the depth of the taxonomy. Therefore, it is the negative log of the shortest path (spath)
1 min read
NLP | Part of speech tagged - word corpus
What is Part-of-speech (POS) tagging ? It is a process of converting a sentence to forms – list of words, list of tuples (where each tuple is having a form (word, tag)). The tag in case of is a part-of-speech tag, and signifies whether the word is a noun, adjective, verb, and so on. Example of Part-of-speech (POS) tagged corpus The/at-tl expense/nn
2 min read
NLP | Categorized Text Corpus
If we have a large number of text data, then one can categorize it to separate sections. Code #1 : Categorization C/C++ Code # Loading brown corpus from nltk.corpus import brown brown.categories() Output : ['adventure', 'belles_lettres', 'editorial', 'fiction', 'government', 'hobbies', 'humor', 'learned', 'lore', 'mystery', 'news', 'religion', 'rev
1 min read