Motivation of Recurrent Neural Networks (RNNs)
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 :
This recurrence gives RNNs two essential properties: parameter sharing across arbitrary sequence lengths , and a stateful memory summarizing past context 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 (): Recurrent memory vector updated at step from the previous hidden state and current input .
- Parameter Sharing: Reusing the same matrices 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 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 . 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)
Related Concepts
- 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 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 path length between any two tokens and full sequence parallelism during training.