Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Recurrent Neural Network (RNN)

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".

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

)

dot

(

self

.

Wh

,

h_prev

)

self

.

b

)

       

return

h_next

How RNNs Work

At each time step t, an RNN performs the following computations:

  1. Receive the current input xₜ and the hidden state hₜ₋₁ from the previous moment
  2. Compute the new hidden state hₜ = f(Wₕₕ·hₜ₋₁ + Wₓₕ·xₜ + b)
  3. 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:

Disadvantages:


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

  1. Selective Memory: The forget gate can decide to retain or discard specific information
  2. Gradient Pathway: The memory cell provides a relatively direct path for gradient propagation
  3. 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:

  1. Forward layer: processes the sequence in chronological order
  2. 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

  1. Natural Language Processing: Part-of-speech tagging, named entity recognition
  2. Speech recognition: Using preceding and following context to improve accuracy
  3. Bioinformatics: Protein structure prediction
  4. 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:

  1. Understand how gradients propagate in RNNs
  2. Learn how attention mechanisms enhance RNNs
  3. Explore the relationship between the Transformer architecture and RNNs
  4. Practice various sequence modeling tasks (machine translation, speech synthesis, etc.)