The Wayback Machine - https://web.archive.org/web/20240926235426/https://www.geeksforgeeks.org/deep-learning-introduction-to-long-short-term-memory/
Open In App

What is LSTM – Long Short Term Memory?

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

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 LSTM?

Long Short-Term Memory is an improved version of recurrent neural network designed by Hochreiter & Schmidhuber.

A traditional RNN has a single hidden state that is passed through time, which can make it difficult for the network to learn long-term dependencies. LSTMs model address this problem by introducing a memory cell, which is a container that can hold information for an extended period.

LSTM architectures are capable of learning long-term dependencies in sequential data, which makes them well-suited for tasks such as language translation, speech recognition, and time series forecasting.

LSTMs can also be used in combination with other neural network architectures, such as Convolutional Neural Networks (CNNs) for image and video analysis.

LSTM Architecture

The LSTM architectures involves the memory cell which is controlled by three gates: the input gate, the forget gate, and the output gate. These gates decide what information to add to, remove from, and output from the memory cell.

  • The input gate controls what information is added to the memory cell.
  • The forget gate controls what information is removed from the memory cell.
  • The output gate controls what information is output from the memory cell.

This allows LSTM networks to selectively retain or discard information as it flows through the network, which allows them to learn long-term dependencies.

The LSTM maintains a hidden state, which acts as the short-term memory of the network. The hidden state is updated based on the input, the previous hidden state, and the memory cell’s current state.

Bidirectional LSTM Model

Bidirectional LSTM (Bi LSTM/ BLSTM) is recurrent neural network (RNN) that is able to process sequential data in both forward and backward directions. This allows Bi LSTM to learn longer-range dependencies in sequential data than traditional LSTMs, which can only process sequential data in one direction.

  • Bi LSTMs are made up of two LSTM networks, one that processes the input sequence in the forward direction and one that processes the input sequence in the backward direction. 
  • The outputs of the two LSTM networks are then combined to produce the final output.

LSTM models, including Bi LSTMs, have demonstrated state-of-the-art performance across various tasks such as machine translation, speech recognition, and text summarization.

Networks in LSTM architectures can be stacked to create deep architectures, enabling the learning of even more complex patterns and hierarchies in sequential data. Each LSTM layer in a stacked configuration captures different levels of abstraction and temporal dependencies within the input data.

LSTM Working

LSTM architecture has a chain structure that contains four neural networks and different memory blocks called cells.

lstm

Information is retained by the cells and the memory manipulations are done by the gates. There are three gates – 

Forget Gate

The information that is no longer useful in the cell state is removed with the forget gate. Two inputs xt (input at the particular time) and ht-1 (previous cell output) are fed to the gate and multiplied with weight matrices followed by the addition of bias. The resultant is passed through an activation function which gives a binary output. If for a particular cell state the output is 0, the piece of information is forgotten and for output 1, the information is retained for future use. The equation for the forget gate is:

[Tex] f_t = σ(W_f · [h_{t-1}, x_t] + b_f) [/Tex]
 where:

  • W_f represents the weight matrix associated with the forget gate.
  • [h_t-1, x_t] denotes the concatenation of the current input and the previous hidden state.
  • b_f is the bias with the forget gate.
  • σ is the sigmoid activation function.

Architecture of LSTM

Input gate

The addition of useful information to the cell state is done by the input gate. First, the information is regulated using the sigmoid function and filter the values to be remembered similar to the forget gate using inputs ht-1 and xt. . Then, a vector is created using tanh function that gives an output from -1 to +1, which contains all the possible values from ht-1 and xt. At last, the values of the vector and the regulated values are multiplied to obtain the useful information. The equation for the input gate is:

[Tex] i_t = σ(W_i · [h_{t-1}, x_t] + b_i) [/Tex]

[Tex]Ĉ_t = tanh(W_c · [h_{t-1}, x_t] + b_c) [/Tex]

We multiply the previous state by ft, disregarding the information we had previously chosen to ignore. Next, we include it∗Ct. This represents the updated candidate values, adjusted for the amount that we chose to update each state value.

[Tex]C_t = f_t ⊙ C_{t-1} + i_t ⊙ Ĉ_t [/Tex]

where

  •  ⊙ denotes element-wise multiplication
  • tanh is tanh activation function

bruh

Output gate

The task of extracting useful information from the current cell state to be presented as output is done by the output gate. First, a vector is generated by applying tanh function on the cell. Then, the information is regulated using the sigmoid function and filter by the values to be remembered using inputs [Tex]h_{t-1} [/Tex]and [Tex]x_t[/Tex]. At last, the values of the vector and the regulated values are multiplied to be sent as an output and input to the next cell. The equation for the output gate is:

[Tex]o_t = σ(W_o · [h_{t-1}, x_t] + b_o) [/Tex]

bruh

Applications of LSTM

Some of the famous applications of LSTM includes:

  • Language Modeling: LSTMs have been used for natural language processing tasks such as language modeling, machine translation, and text summarization. They can be trained to generate coherent and grammatically correct sentences by learning the dependencies between words in a sentence.
  • Speech Recognition: LSTMs have been used for speech recognition tasks such as transcribing speech to text and recognizing spoken commands. They can be trained to recognize patterns in speech and match them to the corresponding text.
  • Time Series Forecasting: LSTMs have been used for time series forecasting tasks such as predicting stock prices, weather, and energy consumption. They can learn patterns in time series data and use them to make predictions about future events.
  • Anomaly Detection: LSTMs have been used for anomaly detection tasks such as detecting fraud and network intrusion. They can be trained to identify patterns in data that deviate from the norm and flag them as potential anomalies.
  • Recommender Systems: LSTMs have been used for recommendation tasks such as recommending movies, music, and books. They can learn patterns in user behavior and use them to make personalized recommendations.
  • Video Analysis: LSTMs have been used for video analysis tasks such as object detection, activity recognition, and action classification. They can be used in combination with other neural network architectures, such as Convolutional Neural Networks (CNNs), to analyze video data and extract useful information.

LTSM vs RNN

Feature

LSTM (Long Short-term Memory)

RNN (Recurrent Neural Network)

Memory

Has a special memory unit that allows it to learn long-term dependencies in sequential data

Does not have a memory unit

Directionality

Can be trained to process sequential data in both forward and backward directions

Can only be trained to process sequential data in one direction

Training

More difficult to train than RNN due to the complexity of the gates and memory unit

Easier to train than LSTM

Long-term dependency learning

Yes

Limited

Ability to learn sequential data

Yes

Yes

Applications

Machine translation, speech recognition, text summarization, natural language processing, time series forecasting

Natural language processing, machine translation, speech recognition, image processing, video processing

Problem with Long-Term Dependencies in RNN

Recurrent Neural Networks (RNNs) are designed to handle sequential data by maintaining a hidden state that captures information from previous time steps. However, they often face challenges in learning long-term dependencies, where information from distant time steps becomes crucial for making accurate predictions. This problem is known as the vanishing gradient or exploding gradient problem.

Few common issues are listed below:

Vanishing Gradient

During backpropagation through time, gradients can become extremely small as they are multiplied through the chain of recurrent connections, causing the model to have difficulty learning dependencies that are separated by many time steps.

Exploding Gradient

Conversely, gradients can explode during backpropagation, leading to numerical instability and making it difficult for the model to converge.

Different Variants on Long Short-Term Memory

Over time, several variants and improvements to the original LSTM architecture have been proposed.

Vanilla LSTM

This is the original LSTM architecture proposed by Hochreiter and Schmidhuber. It includes memory cells with input, forget, and output gates to control the flow of information. The key idea is to allow the network to selectively update and forget information from the memory cell.

Peephole Connections

In the peephole LSTM, the gates are allowed to look at the cell state in addition to the hidden state. This allows the gates to consider the cell state when making decisions, providing more context information.

Gated Recurrent Unit (GRU)

GRU is an alternative to LSTM, designed to be simpler and computationally more efficient. It combines the input and forget gates into a single “update” gate and merges the cell state and hidden state. While GRUs have fewer parameters than LSTMs, they have been shown to perform similarly in practice.

Conclusion

Long Short-Term Memory (LSTM) is a powerful type of recurrent neural network (RNN) that is well-suited for handling sequential data with long-term dependencies. It addresses the vanishing gradient problem, a common limitation of RNNs, by introducing a gating mechanism that controls the flow of information through the network. This allows LSTMs to learn and retain information from the past, making them effective for tasks like machine translation, speech recognition, and natural language processing.

Also Check:

Frequently Asked Questions (FAQs)

1. What is LSTM and why it is used?

LSTM, or Long Short-Term Memory, is a type of recurrent neural network designed for sequence tasks, excelling in capturing and utilizing long-term dependencies in data.

2. How does LSTM work?

LSTMs use a cell state to store information about past inputs. This cell state is updated at each step of the network, and the network uses it to make predictions about the current input. The cell state is updated using a series of gates that control how much information is allowed to flow into and out of the cell.

3.What are LSTM examples?

LSTM (Long Short-Term Memory) examples include speech recognition, machine translation, and time series prediction, leveraging its ability to capture long-term dependencies in sequential data.

4. What is the difference between LSTM and Gated Recurrent Unit (GRU)?

LSTM has a cell state and gating mechanism which controls information flow, whereas GRU has a simpler single gate update mechanism. LSTM is more powerful but slower to train, while GRU is simpler and faster.

5. What is difference between LSTM and RNN?

  • RNNs have a simple recurrent structure with unidirectional information flow.
  • LSTMs have a gating mechanism that controls information flow and a cell state for long-term memory.
  • LSTMs generally outperform RNNs in tasks that require learning long-term dependencies.

6. Is LSTM faster than CNN?

No, LSTMs and CNNs serve different purposes. LSTMs are for sequential data; CNNs are for spatial data.

7. Is LSTM faster than GRU?

Generally, yes. GRUs have fewer parameters, which can lead to faster training compared to LSTMs.



Previous Article
Next Article

Similar Reads

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
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
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
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
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
Long Short Term Memory Networks Explanation
Prerequisites: Recurrent Neural Networks To solve the problem of Vanishing and Exploding Gradients in a Deep Recurrent Neural Network, many variations were developed. One of the most famous of them is the Long Short Term Memory Network(LSTM). In concept, an LSTM recurrent unit tries to "remember" all the past knowledge that the network is seen so f
7 min read
Long Short Term Memory Networks using PyTorch
Long Short-Term Memory Networks (LSTMs) are used for sequential data analysis. LSTM offers solutions to the challenges of learning long-term dependencies. In this article, explore how LSTM works, and how we can build and train LSTM models in PyTorch. Long Short-Term Memory Networks (LSTMs)The difficulties of conventional RNNs in learning, and remem
6 min read
Text Generation using Recurrent Long Short Term Memory Network
This article will demonstrate how to build a Text Generator by building a Recurrent Long Short Term Memory Network. The conceptual procedure of training the network is to first feed the network a mapping of each character present in the text on which the network is training to a unique number. Each character is then hot-encoded into a vector which
5 min read
Short term Memory
In the wider community of neurologists and those who are researching the brain, It is agreed that two temporarily distinct processes contribute to the acquisition and expression of brain functions. These variations can result in long-lasting alterations in neuron operations, for instance through activity-dependent changes in synaptic transmission.
5 min read
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)Bidirectional LSTM or BiLSTM is a term used for a sequenc
8 min read
Understanding of LSTM Networks
This article talks about the problems of conventional RNNs, namely, the vanishing and exploding gradients, and provides a convenient solution to these problems in the form of Long Short Term Memory (LSTM). Long Short-Term Memory is an advanced version of recurrent neural network (RNN) architecture that was designed to model chronological sequences
9 min read
LSTM - Derivation of Back propagation through time
LSTM (Long short term Memory ) is a type of RNN(Recurrent neural network), which is a famous deep learning algorithm that is well suited for making predictions and classification with a flavour of the time. In this article, we will derive the algorithm backpropagation through time and find the gradient value for all the weights at a particular time
4 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
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 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
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
Memory-bounded search ( Memory Bounded Heuristic Search ) in AI
Search algorithms are fundamental techniques in the field of artificial intelligence (AI) that let agents or systems solve challenging issues. Memory-bounded search strategies are necessary because AI systems often encounter constrained memory resources in real-world circumstances. The notion of memory-bound search, often referred to as memory-boun
10 min read
How long does it take to learn the R programming language?
R is an advanced open-source programming language that is available for statistical analysis, data analysis, and data representation. Flexibility coupled with a strong supporting environment makes it a useful application for individuals in the academic community, data scientists, end-users, and professionals in all industry forms. Nevertheless, one
6 min read
How Long does it take to become Data Scientist?
Becoming a data scientist is a journey that requires a blend of formal education, practical experience, and ongoing learning. The time it takes to become proficient can vary widely depending on your background, the time you can dedicate, and the specific skills you need to acquire. Here's a detailed breakdown of the timeline and the topics you need
3 min read
Understanding TF-IDF (Term Frequency-Inverse Document Frequency)
TF-IDF stands for Term Frequency Inverse Document Frequency of records. It can be defined as the calculation of how relevant a word in a series or corpus is to a text. The meaning increases proportionally to the number of times in the text a word appears but is compensated by the word frequency in the corpus (data-set). Terminologies: Term Frequenc
6 min read
How to Fit a Sinusoidal Term to Data in R?
In the field of machine learning and data science, data is often concidered to show patterns similar, to sinusoidal waves. It's much more important to understand and describe such data to study natural patterns such as weather patterns and many more. By the sinusoidal models, we can uncover insights and forecast future trends in the processes. This
8 min read
How to Include an Interaction Term in GAM in R?
Generalized Additive Models (GAM) are an extension of Generalized Linear Models (GLM) that allow for flexibility in modeling nonlinear relationships between predictors and the outcome variable. Generalized Linear Models (GLM) are particularly useful when the relationship between the predictor variables and the response variable is not well-represen
6 min read
Create a Term-Document Matrix with a Dictionary of One or Two Words using R
A Term-Document Matrix (TDM), is a significant technique in text mining, used to represent the frequency of words across a collection of documents. Each row in the matrix corresponds to a unique phrase, and each column represents a document. The cell values reflect the number of times a phrase occurs in a document. TDMs are essential for many text
4 min read
How to Fix "Document-Term Matrix in R - Bigram Tokenizer Not Working"?
Creating a Document-Term Matrix (DTM) is crucial in text analysis, allowing you to explore the frequency of terms within a set of documents. Sometimes, using a Bigram tokenizer with your DTM in R may lead to unexpected issues. This article will help you understand what bigrams are, why they matter, and how to troubleshoot common problems with bigra
4 min read
ANN - Bidirectional Associative Memory (BAM)
Bidirectional Associative Memory (BAM) is a supervised learning model in Artificial Neural Network. This is hetero-associative memory, for an input pattern, it returns another pattern which is potentially of a different size. This phenomenon is very similar to the human brain. Human memory is necessarily associative. It uses a chain of mental assoc
2 min read
Bidirectional Associative Memory (BAM) Implementation from Scratch
Prerequisite: ANN | Bidirectional Associative Memory (BAM) Learning AlgorithmTo implement BAM model, here are some essential consideration and approach- Consider the value of M, as BAM will be constructed with M pairs of patterns. Here the value of M is 4.Set A: Input PatternsSet B: Corresponding Target PatternsAssign the neurons in input and outpu
4 min read
ANN - Bidirectional Associative Memory (BAM) Learning Algorithm
Prerequisite: ANN | Bidirectional Associative Memory (BAM) There are three main steps to construct the BAM model. Learning Testing Retrieval Each step has been described with mathematical formulation in the article ANN | Bidirectional Associative Memory (BAM). Here, this learning algorithm is explained iteratively with an example. Assume, Set A: In
4 min read
Episodic Memory and Deep Q-Networks
Episodic Memory: Episodic Memory is a category of long-term memory that involves recent recollection of specific events, situations, and experiences. For Example Your first day at college. There are two important aspects of episodic memory are Pattern Separation and Pattern Completion. Semantic Memory is used in many ways in machine learning such a
7 min read
Article Tags :
Practice Tags :