Zero Labs
Industry News / AI

LSTM Explained: How Neural Networks Remember Long-Term Information

Source · Towards AI By Sanika Tare

From the publisher’s feed, collected in the ZeroLabs newsroom.

Forget gates, input gates, output gates and a “memory highway”: the full, friendly guide to the idea that fixed the biggest weakness of RNNs.A basic RNN forgets things that happened far back in a sequence. An LSTM fixes that by adding a protected long-term memory (the cell state) and three small “valves” (the forget, input and output gates) that decide what to throw away, what to store, and what to show. By the end of this post you’ll be able to read the LSTM equations, follow a full step with real numbers, and train one in Keras.Quick recap: how an RNN remembersTo understand LSTMs, it helps to start with RNNs: networks that read a sequence one step at a time and carry a small summary forward as they go. That summary, the hidden state, is what gives an RNN its “memory.”It’s a lovely idea. But there was a catch, and it’s the reason LSTMs exist:RNNs can remember previous information, but they struggle when important information appears far back in a sequence. LSTM was designed to address this problem.If you’ve ever tried to remember the first sentence of a long paragraph by the time you reach the end, you already understand the problem. We’re going to take it slowly, one piece at a time, with diagrams, a worked example, and code you can run.What you’ll learn in this post:1. What “memory” really means inside an RNN (and why it fades)2. The vanishing gradient problem, explained without scary math3. The LSTM’s two memories: cell state and hidden state4. Each gate in detail: forget, input and output5. One full LSTM step with real numbers6. How an LSTM learns, where it’s used, and a Keras example7. LSTM vs GRU vs BiLSTM, its limits, and what comes next1. Quick recap: what does “memory” mean in an RNN?A regular neural network treats every input on its own. Show it a photo, it gives an answer; show it the next photo, it starts from scratch. That’s fine for images, but terrible for sequences (data where order matters):• Text: “not good” means something different from “good not”• Speech signals: sounds make sense only in order• Time series: today’s stock price depends on yesterday’s• Sentiment labels attached to sequences of wordsAn RNN (Recurrent Neural Network) handles this by processing the sequence one step at a time. At every step it receives two things:• the current input (the word it’s reading right now), and• the previous hidden state (a summary of everything it has read so far).It mixes them together and produces a new hidden state, which is passed to the next step. That hidden state is the memory.An RNN reads one word at a timeThe diagram shows the same RNN drawn two ways. On the left it’s “folded”: a cell with a loop. On the right it’s “unrolled” over time, one copy per word. It’s the same cell with the same weights being reused at each step, which is what lets an RNN handle sequences of any length.My own study notes describe backpropagation for these networks as BPTT (Backpropagation Through Time), and list three stages: forward pass, error calculation, weight updates. Keep that in mind, because BPTT is exactly where the trouble begins.2. The problem with basic RNNsTry this one. Fill in the blank:“I grew up in India, and after living in several different countries for many years, I still speak fluent ___.”You’d say something like Hindi without thinking. But look at what your brain just did: it held on to one tiny clue, “India,” across a long stretch of unrelated words and used it at the very end.That’s called a long-term dependency: the answer depends on information from far earlier in the sequence.A basic RNN struggles with exactly this.Why long sentences hurt a basic RNNBy the time the RNN reaches “fluent,” the signal from “India” has been mixed and re-mixed so many times that very little of it is left. (The curves above are illustrative, to build intuition. They’re not measurements from a trained model.)Why? The vanishing gradient problemRemember how networks learn: compute a loss, then use backpropagation to send gradients backwards and update the weights. In an RNN that happens across time steps, so the gradient has to travel backwards through every word.At each step backwards, the gradient gets multiplied by a number. If those numbers are smaller than 1 (which is very common), the gradient keeps shrinking:Vanishing gradientsMultiply 0.5 by itself 50 times and you get roughly 0.0000000000000009. The network receives almost no learning signal from words far back, so it can’t learn to rely on them. In my notes this is summarized in one line: gradients become very small as they propagate backwards, so RNNs are perfect for short-term predictions but can’t learn long-term dependencies.So the older information gradually disappears, both from what the network remembers during the forward pass and from what it can learn during training.The ideal fix would be a memory that doesn’t get squished on every step, one that the network can choose to protect. That’s the LSTM.3. So, what is an LSTM?LSTM (Long Short-Term Memory) is a special type of RNN that uses gates and a cell state to control what information should be remembered, forgotten, and passed forward.The name is a little confusing, so let’s decode it: it’s a network with short-term memory (the hidden state) and a long-term memory (the cell state), designed so that the short-term memory can last a long time. Hence: Long Short-Term Memory.Two ideas are packed into the definition:1. An additional memory cell. A dedicated pathway that carries long-term information through the sequence.2. A gated architecture. Small learned “valves” that decide what goes into memory, what stays, and what comes out.At a high level, each step looks like this:Previous Information + Current Input ↓ LSTM ↓ Updated Memory ↓ OutputIt’s the same shape as an RNN, but with much better bookkeeping inside. Here’s the headline comparison:RNN: Short-term memory ✓ Long-term memory ✗ LSTM: Short-term memory ✓ Long-term memory ✓And in table form:4. A good analogy: the notebook and the spoken wordBefore the technical details, here’s a mental picture that helps.Imagine you’re listening to a long story and taking notes.• Your notebook holds the important facts. You decide what to cross out, and what new facts to write down.• What you say out loud at any moment is based on the notebook, but it’s only the part that’s relevant right then.That’s an LSTM:5. The two kinds of memory inside an LSTMAn LSTM carries two things from step to step, not one.LSTM carries two memoriesCell state,(the long-term memory)• Holds long-term information• Runs along the whole sequence like a highway• Information can ride along it with only small, controlled changesHidden state,(the working memory)• The current “working” information• Used to produce the output at this step• Also passed to the next stepThe magic is in how the cell state is updated. In a basic RNN the memory is rewritten completely at each step. In an LSTM the cell state is mostly scaled and added to, so useful information can ride along for many steps without being scrambled.6. Why does an LSTM need gates?Unlimited memory with no way to choose what to keep would just fill up with noise. We need a way to say “keep this, drop that.”Gates let the network decide what information should pass through.A gate is a small layer that looks at the current input and the previous hidden state and outputs numbers between 0 and 1. Those numbers are multiplied with the information flowing past:• 0 → block it completely• 1 → let it all through• in between → let part of it throughThat’s why gates use the sigmoid function. Sigmoid squashes any number into the range 0 to 1, which is exactly what a “how open is this valve?” signal needs. In my notes: “sigmoid: 0 → remove, 1 → retain.”There are three gates, and they’re the heart of the LSTM:1. Forget gate: what old information should we remove?2. Input gate: what new information should we store?3. Output gate: what should we reveal right now?Here’s the whole cell on one page before we take it apart:LSTM carries two memoriesCell state,(the long-term memory)• Holds long-term information• Runs along the whole sequence like a highway• Information can ride along it with only small, controlled changesHidden state,(the working memory)• The current “working” information• Used to produce the output at this step• Also passed to the next stepThe magic is in how the cell state is updated. In a basic RNN the memory is rewritten completely at each step. In an LSTM the cell state is mostly scaled and added to, so useful information can ride along for many steps without being scrambled.6. Why does an LSTM need gates?Unlimited memory with no way to choose what to keep would just fill up with noise. We need a way to say “keep this, drop that.”Gates let the network decide what information should pass through.A gate is a small layer that looks at the current input and the previous hidden state and outputs numbers between 0 and 1. Those numbers are multiplied with the information flowing past:• 0 → block it completely• 1 → let it all through• in between → let part of it throughThat’s why gates use the sigmoid function. Sigmoid squashes any number into the range 0 to 1, which is exactly what a “how open is this valve?” signal needs. In my notes: “sigmoid: 0 → remove, 1 → retain.”There are three gates, and they’re the heart of the LSTM:1. Forget gate: what old information should we remove?2. Input gate: what new information should we store?3. Output gate: what should we reveal right now?Here’s the whole cell on one page before we take it apart:Inside one LSTM cellRead it like this:• The thick purple line on top is the cell state highway, withentering on the left andleaving on the right.• The bottom line carriesand(the previous hidden state and the current input). Every gate reads both.• The × circles mean element-wise multiplication (the valves), and the + circle means adding.Each gate has its own learned weights, so each learns a different job even though they all look at the same information.7. Forget gate: “What old information should we remove?”The forget gate looks at the new input and the previous hidden state and decides which parts of the old cell state are still worth keeping.In plain language:The output has one number for every slot in the cell state:Old information ↓ Forget Gate ↓ 0.0 → Forget 0.5 → Partially keep 1.0 → KeepHere’s what it does to a memory with four slots:Forget gateThe first slot (2.0) is fully kept, the second (−1.0) is erased, the third is halved, the fourth is kept.When is this useful? Suppose the network has been tracking the subject of a sentence (“the dog”) and a new sentence starts about someone else. The forget gate can learn to push the old subject’s slots toward 0 so they don’t confuse what comes next.8. Input gate: “What new information should we store?”Now that we’ve made room, what do we write into memory? This happens in two cooperating parts.Part 1: the input gate decides which slots get updated:Part 2: the candidate memory proposes what new values could be written. It uses, which outputs values between −1 and 1:Input Gate + Candidate Memory ↓ New InformationThink of it like this: the candidate says “here’s what I could add,” and the input gate says “but only add this much of it.”Input gate and candidateWhy tanh for the candidate? Because new information can be positive or negative (it can push a memory slot up or down), and tanh outputs values from −1 to 1 centered on zero. My notes describe it exactly this way: the input gate filters information through a sigmoid, and the possible values go through tanh.9. Updating the cell stateThis is the key operation of the whole LSTM, so let’s slow down.Old Cell State ↓ Remove unnecessary information ↓ Add useful new information ↓ New Cell StateBreak it into pieces:Thesymbol means element-wise multiplication: each slot is multiplied by its own matching number.Notice the plus sign. The old memory isn’t pushed through a big transformation at every step. It’s scaled, then added to. That additive path is a big part of why information (and gradients) can travel much farther than in a basic RNN.10. Output gate: “What should we output right now?”The cell state holds a lot, but not all of it is relevant at this exact moment. The output gate picks what to reveal:Then the new hidden state is:We squash the cell state with(to keep values between −1 and 1), then filter it with the output gate. The result,, is both the output for this step and the hidden state passed to the next step.An important detail: the memory can hold something without showing it. A slot might sit quietly infor ten steps and only get revealed through the output gate when it becomes relevant.11. The complete LSTM flowLet’s put it all together:Previous Cell State ↓ Forget Gate → Remove old information ↓ Input Gate → Add new information ↓ Updated Cell State ↓ Output Gate ↓ Hidden State / OutputIf you remember just one sequence, make it this: forget → add → output.All four equations in one place:12. Let’s run the numbers (one full LSTM step)Equations are easier to trust once you’ve pushed numbers through them. Here’s one complete step for a cell with just three memory slots. I picked the gate values by hand so the mechanics are easy to follow. In a real network the gates compute them from the data.One LSTM step with real numbersSlot 1 is fully revealed, slot 2 half, slot 3 not at all. Note that slot 3 is still in the memory; it just wasn’t shown this time.Pause and think: what would happen to slot 2 if the forget gate had said 1.0 instead of 0.0? (Answer: the old −1.0 would survive, and after adding the new 0.8 the slot would hold −0.2 instead of 0.8.)13. Intuition with a sentenceConsider this:“The dog ran across the road because it was scared.”To work out what “it” refers to, the network benefits from keeping track of “dog” while it reads “ran across the road because.”The → dog → ran → across → the → road → because → it ↑ Important information retainedAn important honesty note: this is an intuitive illustration, not a claim that a particular trained LSTM literally stores the word “dog” in a specific slot. Real LSTMs spread information across many numbers, what each slot encodes is learned rather than chosen by us, and it’s often hard to interpret.14. Why LSTM helps with vanishing gradientsConceptually, three things are going on:• The cell state offers a more direct path for information and gradients to flow through time, because updates are mostly additive rather than repeatedly squashed.• The gates regulate that flow, so useful information can be preserved while irrelevant information is dropped.• As a result, LSTMs can learn longer-term dependencies better than basic RNNs.To be honest about it: LSTM helps with the vanishing gradient problem, but it doesn’t make it disappear. Very long sequences are still hard.15. How does an LSTM learn?Nothing exotic here. It’s the standard neural-network training loop, applied across time steps:Input Sequence ↓ Forward Pass ↓ Prediction ↓ Loss ↓ Backpropagation Through Time ↓ Gradient Descent ↓ Update LSTM WeightsThe gates aren’t hand-written rules. They contain learnable weights (and their biases), updated by gradient descent like every other weight. The network learns what to forget, what to store, and what to reveal, purely from the training data.16. LSTM architecture: inputs and outputs17. Where LSTMs are usedLSTMs have been a workhorse for anything that comes in sequences:• Text generation• Speech recognition• Sentiment analysis• Time-series forecasting• Language modeling• Machine translation• Anomaly detectionVariant: BiLSTM (Bidirectional LSTM)A regular LSTM reads left to right, so at the word “bank” it hasn’t seen “of the river” yet. A BiLSTM runs two LSTMs, one forward and one backward, and combines them, so it captures not only the content that comes before a given point but also the content that follows.BiLSTMThe flow in my notes is simple: Input → Embedding → BiLSTM → Output sequence. BiLSTMs are great for understanding a complete text (tagging, classification). They’re not suited to generating text word by word, because when generating, the future words don’t exist yet.18. Example: LSTM for time-series predictionSequences aren’t only text. Suppose we have sales for the week:Monday → 100 Tuesday → 105 Wednesday → 110 Thursday → 108 Friday → ?An LSTM can look at the pattern of previous observations (a steady upward trend with a small dip) and use it to predict the next value. In practice you slice your data into windows like “last 4 days → next day,” and train on thousands of windows.Here’s the shape of the data an LSTM expects:import numpy as np sales = np.array([100, 105, 110, 108, 112, 118, 115, 121, 125, 123], dtype=”float32") window = 4 X, y = [], [] for i in range(len(sales) — window): X.append(sales[i : i + window]) # the last 4 days y.append(sales[i + window]) # the next day X = np.array(X)[…, None] # shape: (samples, time steps, features) y = np.array(y) print(X.shape, y.shape) # (6, 4, 1) (6,)The key idea is the 3D shape: (samples, time steps, features). Almost every LSTM bug for beginners comes from getting this shape wrong.19. Code: LSTM for sentiment classificationLet’s build something real: classify movie reviews as positive or negative with Keras.Sentiment pipelineimport tensorflow as tf from tensorflow.keras import layers, models from tensorflow.keras.datasets import imdb from tensorflow.keras.preprocessing.sequence import pad_sequences vocab_size = 10_000 # keep the 10,000 most common words max_len = 200 # cut or pad every review to 200 words # 1. Load data (reviews are already tokenized into integer IDs) (x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=vocab_size) # 2. Make every sequence the same length x_train = pad_sequences(x_train, maxlen=max_len) x_test = pad_sequences(x_test, maxlen=max_len) # 3. Build the model model = models.Sequential([ layers.Embedding(vocab_size, 64), # word IDs -> vectors layers.LSTM(64), # the LSTM layer layers.Dense(1, activation=”sigmoid”), # 0 = negative, 1 = positive ]) # 4. Compile and train model.compile( optimizer=”adam”, loss=”binary_crossentropy”, metrics=[“accuracy”], ) model.fit(x_train, y_train, epochs=3, batch_size=64, validation_split=0.2) # 5. Evaluate loss, acc = model.evaluate(x_test, y_test) print(f”Test accuracy: {acc:.3f}”)What’s happening, line by line:• Embedding turns each word ID into a small vector of numbers.• LSTM(64) reads the sequence of vectors and produces a 64-number summary (its final hidden state).• Dense(1, sigmoid) turns that summary into a probability that the review is positive.• Adam (optimizer) and binary cross-entropy (loss) are the standard choices for a yes/no classifier.Your exact accuracy will vary from run to run, so treat any number you get as a starting point and not a benchmark.Two easy upgrades to try:layers.Bidirectional(layers.LSTM(64)) # BiLSTM: read both directions layers.LSTM(64, dropout=0.2) # dropout helps against overfitting20. RNN vs LSTM vs GRUThere’s a close cousin worth knowing: the GRU (Gated Recurrent Unit), a simplified gated design with two gates (update and reset) and no separate cell state. It’s the natural next comparison, but we won’t go deep here.21. Limitations of LSTMLSTMs are powerful, but not magic. My notes list the pros as modeling long-term dependencies, robustness to noisy data, and flexibility for various tasks. The cons are just as real:• More complex than basic RNNs• More parameters, so computationally expensive• Training can be slower• Sequential processing (step 2 needs step 1) limits parallelization• Prone to overfitting and needs hyperparameter tuning• Large data requirements• Can still struggle with very long sequencesAnd there’s a bigger picture: Transformers have become the go-to architecture for many modern sequence tasks, precisely because they handle some of these limits differently.22. Common mistakes beginners make1. Mixing up cell state and hidden state. Cell state = long-term notebook. Hidden state = what’s shown now.2. Forgetting that gate outputs are multiplied. A gate doesn’t add information; it scales it.3. Wrong input shape. LSTMs want (samples, time steps, features).4. Forgetting to pad sequences to the same length.5. Expecting an LSTM to fix everything. It helps with long dependencies; it doesn’t remove every problem.6. Using a BiLSTM for text generation. It needs the future, which doesn’t exist yet.23. Common beginner questionsWhat does LSTM stand for? Long Short-Term Memory.Why does LSTM need gates? Without them the network can’t choose what to keep. Gates let it selectively forget, store and reveal information.What’s the difference between cell state and hidden state? The cell state is the long-term memory that runs along the whole sequence. The hidden state is the current working output, produced by filtering the cell state through the output gate.What does the forget gate do? Decides how much of each slot of the old memory to keep (0 = erase, 1 = keep).What does the input gate do? Decides how much of the new candidate memory gets written into the cell state.What does the output gate do? Decides which parts of the memory to expose as the hidden state / output at this step.Why sigmoid in the gates? It outputs values between 0 and 1, which works as a “how open is the valve” signal.Why tanh? It outputs values between −1 and 1, centered at zero, which suits candidate values (they can push memory up or down) and keeps the cell state’s contribution to the output well-scaled.LSTM vs RNN? LSTM adds a cell state and gates to give controlled, longer-lasting memory. A basic RNN has only a hidden state.LSTM vs GRU? GRU is a lighter design with two gates and no separate cell state. LSTM has three gates and a cell state.24. ConclusionRNN ↓ Problem: Long-Term Dependencies ↓ LSTM ↓ Forget ↓ Remember ↓ Update ↓ OutputKey takeaways• A basic RNN’s memory fades because gradients shrink as they travel back through time.• An LSTM adds a cell state (long-term memory) and gates (learned valves).• Forget gate: what to remove. Input gate: what to store. Output gate: what to show.• The cell state is updated by scaling and adding, which keeps information and gradients flowing.• LSTM helps with long dependencies; it doesn’t eliminate every problem.LSTM gives an RNN a controlled memory system, allowing it to decide what information to forget, what new information to remember, and what information to use for the current output.Where to go from hereLSTMs gave neural networks a controlled memory, and the same idea of gating shows up in lighter variants like the GRU. If you want to keep exploring sequence models, the natural next steps are comparing GRUs with LSTMs on a small dataset of your own, trying a BiLSTM on a text task, and then looking at Transformers, which handle long sequences with attention instead of recurrence.LSTM Explained: How Neural Networks Remember Long-Term Information was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.