Recurrent Neural Network (RNN)
A Recurrent Neural Network (RNN) is a neural network specifically designed to handle sequential data (such as text, speech, and time series).
Unlike traditional feedforward neural networks, RNNs have a "memory" capability that can retain information from previous steps.
Recurrent neural networks can use the hidden state from the previous step (Hidden State) to influence the output of the current step, thereby capturing temporal dependencies in sequences.

The Core Idea of RNN
The core of an RNN lies inRecurrent Connections(Recurrent Connection), meaning the network's output depends not only on the current input but also on the inputs of all previous time steps. This structure enables RNNs to process sequence data of arbitrary length.
Traditional Neural Networks: Inputs and outputs are independent (e.g., in image classification, there is no relation between individual images).
RNN: ThroughRecurrent Connections(Recurrent Connection) passes the hidden state from the previous step to the next step, forming a "memory".
-
Input at each step = current data + hidden state from the previous step.
-
The output depends not only on the current input but also on the context of all previous steps.
Just as when a person reads a sentence, understanding the current word depends on what was read before (for example, "He opened the __", you would predict "door" or "book").
Example
A Simple RNN Cell Implementation Example
import
numpy
as
np
class
SimpleRNN:
def
init
(
self
,
input_size
,
hidden_size
)
:
self
.
Wx
=
np.
random
.
randn
(
hidden_size
,
input_size
)
Input Weights
self
.
Wh
=
np.
random
.
randn
(
hidden_size
,
hidden_size
)
Hidden State Weights
self
.
b
=
np.
zeros
(
(
hidden_size
,
1
)
)
Bias Term
def
forward
(
self
,
x
,
h_prev
)
:
h_next
=
np.
tanh
(
np.
dot
(
self
.
Wx
,
x
)
- np.
dot
(
self
.
Wh
,
h_prev
)
self
.
b
)
return
h_next
How RNNs Work
At each time step t, an RNN performs the following computations:
- Receive the current input xₜ and the hidden state hₜ₋₁ from the previous moment
- Compute the new hidden state hₜ = f(Wₕₕ·hₜ₋₁ + Wₓₕ·xₜ + b)
- Produce the output yₜ = g(Wₕᵧ·hₜ + c)
where f and g are usually activation functions (such as tanh or softmax).
Pros and Cons of RNNs
Advantages:
- Can handle variable-length sequences
- Theoretically able to remember historical information of any length
- Parameter sharing (the same set of weights is used for all time steps)
Disadvantages:
- Vanishing/exploding gradient problem (difficult to learn long-term dependencies)
- Relatively low computational efficiency (time steps cannot be processed in parallel)
Long Short-Term Memory (LSTM)
LSTM (Long Short-Term Memory) is an improved architecture of RNN, specifically designed to solve the long-term dependency problem of standard RNNs.
2.1 The Core Structure of LSTM
LSTM introduces three gating mechanisms and one memory cell:
| Component | Function |
|---|---|
| Input Gate | Controls the inflow of new information |
| Forget Gate | Decides which old information to discard |
| Output Gate | Controls the amount of information output |
| Memory Cell | Stores long-term state |
Example
Basic Implementation of an LSTM Cell
class
LSTMCell:
def
init
(
self
,
input_size
,
hidden_size
)
:
Combine the weights of all gates
self
.
W
=
np.
random
.
randn
(
4
*hidden_size
,
input_size+hidden_size
)
self
.
b
=
np.
random
.
randn
(
4
*hidden_size
,
1
)
def
forward
(
self
,
x
,
h_prev
,
c_prev
)
:
combined
=
np.
vstack
(
(
h_prev
,
x
)
)
gates
=
np.
dot
(
self
.
W
,
combined
)
self
.
b
Split to obtain each gate
f_gate
=
sigmoid
(
gates
[
:hidden_size
]
)
Forget Gate
i_gate
=
sigmoid
(
gates
[
hidden_size:
2
*hidden_size
]
)
Input Gate
o_gate
=
sigmoid
(
gates
[
2
*hidden_size:
3
*hidden_size
]
)
Output Gate
c_candidate
=
np.
tanh
(
gates
[
3
*hidden_size:
]
)
Candidate Memory
Update the memory and hidden state
c_next
=
f_gate * c_prev + i_gate * c_candidate
h_next
=
o_gate * np.
tanh
(
c_next
)
return
h_next
,
c_next
How LSTM Solves the Long-Term Dependency Problem
- Selective Memory: The forget gate can decide to retain or discard specific information
- Gradient Pathway: The memory cell provides a relatively direct path for gradient propagation
- Information Protection: The memory content is not directly modified by the operations at every time step
Gated Recurrent Unit (GRU)
GRU (Gated Recurrent Unit) is a simplified version of LSTM that reduces the number of parameters while maintaining similar performance.
The Core Structure of GRU
GRU merges certain components of LSTM:
| Component | Function |
|---|---|
| Update Gate | Decides how much old information to retain |
| Reset Gate | Decides how to combine new and old information |
| Candidate Activation | A new state computed based on the reset gate |
Example
Implementation of a GRU Cell
class
GRUCell:
def
init
(
self
,
input_size
,
hidden_size
)
:
self
.
W
=
np.
random
.
randn
(
3
*hidden_size
,
input_size+hidden_size
)
self
.
b
=
np.
random
.
randn
(
3
*hidden_size
,
1
)
def
forward
(
self
,
x
,
h_prev
)
:
combined
=
np.
vstack
(
(
h_prev
,
x
)
)
gates
=
np.
dot
(
self
.
W
,
combined
)
self
.
b
Split the gating signals
z
=
sigmoid
(
gates
[
:hidden_size
]
)
Update Gate
r
=
sigmoid
(
gates
[
hidden_size:
2
*hidden_size
]
)
Reset Gate
h_candidate
=
np.
tanh
(
np.
dot
(
self
.
W
[
2
*hidden_size:
]
,
np.
vstack
(
(
r*h_prev
,
x
)
)
)
self
.
b
[
2
*hidden_size:
]
Update the hidden state
h_next
=
(
1
-z
)
h_prev + zh_candidate
return
h_next
GRU vs LSTM
| Feature | GRU | LSTM |
|---|---|---|
| Number of Parameters | less | Relatively Many |
| Training Speed | is usually faster than | Slower |
| Memory Cell | None | Yes |
| Number of Gates | 2 | 3 |
| Performance | Better on small datasets | Possibly better on large datasets |
Bidirectional RNN (Bi-RNN)
Bidirectional RNNs enhance sequence modeling by considering both past and future context information simultaneously.
Bidirectional RNN Architecture
A Bi-RNN contains two independent RNN layers:
- Forward layer: processes the sequence in chronological order
- Backward layer: processes the sequence in reverse chronological order
The final output is a combination of the outputs from both directions (usually concatenation or summation).

Application Scenarios of Bidirectional RNNs
- Natural Language Processing: Part-of-speech tagging, named entity recognition
- Speech recognition: Using preceding and following context to improve accuracy
- Bioinformatics: Protein structure prediction
- Time Series Forecasting: Considering historical and future trends
Bidirectional LSTM/GRU
In modern applications, bidirectional RNNs usually use LSTM or GRU as their basic units:
Example
from
tensorflow.
keras
.
layers
import
Bidirectional
,
LSTM
model.
add
(
Bidirectional
(
LSTM
(
64
)
)
)
Create a bidirectional LSTM layer
Practical Exercise
Exercise 1: Implement a Simple RNN
Use Python and NumPy to implement a simple RNN capable of character-level text generation.
Exercise 2: LSTM Sentiment Analysis
Use Keras to build an LSTM-based sentiment classifier for movie reviews.
Exercise 3: Bidirectional GRU Named Entity Recognition
Implement a bidirectional GRU model to recognize entities such as person names and place names in text.
Exercise 4: Comparative Experiment
Compare the performance differences of Vanilla RNN, LSTM, and GRU on the same dataset.
Summary and further learning
RNNs and their variants are powerful tools for processing sequential data. To master them thoroughly:
- Understand how gradients propagate in RNNs
- Learn how attention mechanisms enhance RNNs
- Explore the relationship between the Transformer architecture and RNNs
- Practice various sequence modeling tasks (machine translation, speech synthesis, etc.)