Skip to content
E
Educatum

Motivation of Recurrent Neural Networks (RNNs)

Curated by Educatum AI teamLast updated:
Neural Networks and Deep Learning
Direct Answer

Recurrent Neural Networks (RNNs) were motivated by the inability of standard feedforward networks to handle variable-length sequences and share parameters across time. By maintaining a recurrent hidden state updated at every time step with shared weights, RNNs preserve context from prior inputs when modeling time series, audio, and language.

Study Card: Motivation of Recurrent Neural Networks (RNNs)

Direct Answer

Standard feedforward networks assume fixed-size, independent inputs and learn separate weights for each input position, making them poorly suited for variable-length sequential data where order and temporal context matter. Recurrent Neural Networks (RNNs) address this by applying the same transition parameters repeatedly across time steps while passing along an internal hidden state hth_t:

ht=tanh⁡(Whhht−1+Wxhxt+bh),y^t=Whyht+byh_t = \tanh(W_{hh} h_{t-1} + W_{xh} x_t + b_h), \qquad \hat{y}_t = W_{hy} h_t + b_y

This recurrence gives RNNs two essential properties: parameter sharing across arbitrary sequence lengths TT, and a stateful memory hth_t summarizing past context (x1,…,xt)(x_1, \dots, x_t) for tasks such as time-series forecasting, speech recognition, and sequence labeling.

Key Terms

  • Sequential Data: Ordered data where element dependencies span time or position (text, time series, audio).
  • Hidden State (hth_t): Recurrent memory vector updated at step tt from the previous hidden state ht−1h_{t-1} and current input xtx_t.
  • Parameter Sharing: Reusing the same matrices (Wxh,Whh,Why)(W_{xh}, W_{hh}, W_{hy}) at every step so learned patterns generalize across positions and sequence lengths.
  • Backpropagation Through Time (BPTT): Unrolling the RNN across steps to compute gradients; repeated multiplication by WhhTW_{hh}^T and activation derivatives can cause vanishing or exploding gradients over long sequences.

Example

Consider predicting the next word in "The weather today is _____". An RNN processes each token sequentially, updating its hidden state hth_t. After reading "The weather today is", the hidden state encodes context about weather and singular present tense, making words like "sunny" or "rainy" far more probable than unrelated nouns. Because the weights are shared across positions, the network does not need a separate parameter set for every possible sentence length.

Code Implementation

import numpy as np
import tensorflow as tf

np.random.seed(42)

# Simple sequence model using LSTM (a gated RNN that mitigates vanishing gradients)
class TimeSeriesRNN(tf.keras.Model):
    def __init__(self, rnn_units):
        super().__init__()
        self.lstm = tf.keras.layers.LSTM(rnn_units, return_sequences=True)
        self.dense = tf.keras.layers.Dense(1)

    def call(self, inputs):
        lstm_output = self.lstm(inputs)
        return self.dense(lstm_output)

# Example usage: 100 sequences, 10 time steps, 1 feature per step
rnn_units = 32
model = TimeSeriesRNN(rnn_units)

X_train = np.random.rand(100, 10, 1).astype(np.float32)
y_train = np.random.rand(100, 10, 1).astype(np.float32)

model.compile(optimizer='adam', loss='mse')
model.fit(X_train, y_train, epochs=10, verbose=0)

sample_input = np.random.rand(1, 10, 1).astype(np.float32)
prediction = model.predict(sample_input, verbose=0)
print("Prediction shape:", prediction.shape)
  • Long Short-Term Memory (LSTM): Adds a cell state with forget, input, and output gates to allow near-linear gradient flow across long horizons, mitigating vanilla RNN vanishing gradients.
  • Gated Recurrent Unit (GRU): Merges cell and hidden states with reset and update gates, using fewer parameters than LSTM while retaining gating benefits.
  • Bidirectional RNNs: Run both forward and backward recurrences when the entire sequence is available upfront (e.g., tagging or encoding), capturing both past and future context.
  • Transformers & Self-Attention: Because RNNs process tokens sequentially in O(T)O(T) dependent steps, they cannot parallelize across time during training and still struggle over very long contexts; Transformer self-attention largely replaced RNNs in large-scale NLP by enabling direct O(1)O(1) path length between any two tokens and full sequence parallelism during training.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.