Step-by-Step Explanation of RNN for Time Series Forecasting – part 6 – day 60

A simple RNN combines the current inputs with the preceding hidden state. In a stacked model, the first layer produces a sequence that becomes the input to the next recurrent layer.

Step-by-Step Explanation of RNN for Time Series Forecasting

Step 1: Simple RNN for Univariate Time Series Forecasting

Explanation:

An RNN processes sequences of data, where the output at any time step depends on both the current input and the hidden state (which stores information about previous inputs). In this case, we use a Simple RNN with only one recurrent neuron.

TensorFlow Code:

model = tf.keras.Sequential([

tf.keras.layers.SimpleRNN(1, input_shape=[None, 1])

])

Numerical Example:

Let’s say we have a sequence of three time steps: [x1,x2,x3]=[0.1,0.2,0.3].

1. Input and Hidden State Initialization:

The RNN starts with an initial hidden state h0, typically initialized to 0. Each step processes the input and updates the hidden state:

ht=tanh(Whht−1+Wxxt+b)

where:

  • Wh is the weight for the hidden state.
  • Wx is the weight for the input.
  • b is the bias term.
  • tanh is the activation function (hyperbolic tangent).

Assume:

  • Wh=0.5
  • Wx=1.0
  • b=0.1

Let’s calculate the hidden state updates for each time step:

Time Step 1:

h1=tanh(0.5⋅0+1.0⋅0.1+0.1)=tanh(0.1+0.1)=tanh(0.2)=0.197

Time Step 2:

h2=tanh(0.5⋅0.197+1.0⋅0.2+0.1)=tanh(0.0985+0.2+0.1)=tanh(0.3985)=0.378

Time Step 3:

h3=tanh(0.5⋅0.378+1.0⋅0.3+0.1)=tanh(0.189+0.3+0.1)=tanh(0.589)=0.529

Thus, the final output of the RNN for the sequence is h3=0.529.

PyTorch Equivalent Code:

import torch

import torch.nn as nn

class SimpleRNNModel(nn.Module):

def __init__(self):

super(SimpleRNNModel, self).__init__()

self.rnn = nn.RNN(input_size=1, hidden_size=1, batch_first=True)

def forward(self, x):

output, hidden = self.rnn(x)

return output[:, -1, :]  # returning only the final output

# Model instantiation

model = SimpleRNNModel()

—

Step 2: Understanding the Sequential Process of the RNN

Explanation:

At each time step, the RNN processes the input by updating the hidden state based on both the current input and the previous hidden state. This hidden state acts like “memory,” allowing the RNN to capture temporal dependencies.

Let’s break down the calculations we did above:

  • At time step 1: The hidden state is computed as h1=tanh(Whh0+Wxx1+b).
  • At time step 2: The hidden state is updated to h2=tanh(Whh1+Wxx2+b).
  • At time step 3: The final hidden state becomes h3=tanh(Whh2+Wxx3+b).

The RNN effectively “remembers” the inputs from earlier time steps through the hidden state. This process can be repeated for sequences of any length.

—

Step 3: Larger RNN with a Dense Output Layer

Explanation:

To improve performance, we increase the number of neurons in the RNN and add a fully connected Dense layer. This allows the model to capture more complex relationships and map the RNN’s output to a single prediction.

TensorFlow Code:

univar_model = tf.keras.Sequential([

tf.keras.layers.SimpleRNN(32, input_shape=[None, 1]),

tf.keras.layers.Dense(1)

])

Numerical Example:

Let’s extend our example with a larger RNN that has 32 neurons. The hidden state now becomes a vector of 32 values, instead of just 1.

Let’s assume:

  • ht for each time step is now a vector of length 32.
  • The final hidden state at time step 3, h3, will also be a vector of length 32.

The Dense layer will then map this vector to a single output. Suppose the Dense layer has weights Wd and bias bd. The output is computed as:

y^=WdTh3+bd

Where Wd is a vector of length 32, and h3 is the hidden state vector from the last RNN layer.

PyTorch Equivalent Code:

class SimpleRNNWithDense(nn.Module):

def __init__(self):

super(SimpleRNNWithDense, self).__init__()

self.rnn = nn.RNN(input_size=1, hidden_size=32, batch_first=True)

self.fc = nn.Linear(32, 1)

def forward(self, x):

x, _ = self.rnn(x)

x = x[:, -1, :]

x = self.fc(x)

return x

# Model instantiation

model = SimpleRNNWithDense()

—

Step 4: Building a Deeper RNN (Stacked RNN Layers)

Explanation:

In a deeper RNN (also called a stacked RNN), multiple RNN layers are placed on top of each other. The first RNN layer processes the input sequence and passes its output (a sequence of hidden states) to the second RNN layer, and so on. Each layer refines the representation of the input data, helping the network learn more complex temporal dependencies.

TensorFlow Code:

deep_model = tf.keras.Sequential([

tf.keras.layers.SimpleRNN(32, return_sequences=True, input_shape=[None, 1]),  # First RNN layer

tf.keras.layers.SimpleRNN(32, return_sequences=True),  # Second RNN layer

tf.keras.layers.SimpleRNN(32),  # Third RNN layer

tf.keras.layers.Dense(1)  # Dense output layer

])

Numerical Example:

Let’s use a **3-time-step sequence** [x1,x2,x3]=[0.1,0.2,0.3] as input.

We will assume that each RNN layer has:

  • A hidden size of 32 neurons.
  • Weight matrices Wh (hidden-to-hidden weights), Wx (input-to-hidden weights), and biases b.
  • tanh as the activation function.

First RNN Layer:

At each time step, the input xt and the previous hidden state ht−1 are combined to produce the new hidden state ht1 for the first layer:

ht1=tanh(Wh1ht−11+Wx1xt+b1)

For simplicity, assume Wh1=Wx1=0.5 and b1=0.1. The initial hidden state h01=0.

Time Step 1:

h11=tanh(0.5⋅0+0.5⋅0.1+0.1)=tanh(0.05+0.1)=tanh(0.15)=0.149

Time Step 2:

h21=tanh(0.5⋅0.149+0.5⋅0.2+0.1)=tanh(0.0745+0.1+0.1)=tanh(0.2745)=0.268

Time Step 3:

h31=tanh(0.5⋅0.268+0.5⋅0.3+0.1)=tanh(0.134+0.15+0.1)=tanh(0.384)=0.366

At the end of the first RNN layer, we have the following hidden states for all time steps:

[h11,h21,h31]=[0.149,0.268,0.366]

Second RNN Layer:

The second RNN layer takes the outputs from the first RNN layer and processes them similarly. Assume Wh2=Wx2=0.6 and b2=0.05.

Time Step 1:

h12=tanh(0.6⋅0+0.6⋅0.149+0.05)=tanh(0.0894+0.05)=tanh(0.1394)=0.138

Time Step 2:

h22=tanh(0.6⋅0.138+0.6⋅0.268+0.05)=tanh(0.0828+0.1608+0.05)=tanh(0.2936)=0.285

Time Step 3:

h32=tanh(0.6⋅0.285+0.6⋅0.366+0.05)=tanh(0.171+0.2196+0.05)=tanh(0.4406)=0.414

After the second RNN layer, we have:

[h12,h22,h32]=[0.138,0.285,0.414]

Third RNN Layer:

The third RNN layer follows the same process. Assume Wh3=Wx3=0.7 and b3=0.02.

Time Step 1:

h13=tanh(0.7⋅0+0.7⋅0.138+0.02)=tanh(0.0966+0.02)=tanh(0.1166)=0.116

Time Step 2:

h23=tanh(0.7⋅0.116+0.7⋅0.285+0.02)=tanh(0.0812+0.1995+0.02)=tanh(0.3007)=0.292

Time Step 3:

h33=tanh(0.7⋅0.292+0.7⋅0.414+0.02)=tanh(0.2044+0.2898+0.02)=tanh(0.5142)=0.473

The output of the third RNN layer at the final time step h33=0.473 is passed to the Dense Layer.

Dense Layer Output:

Assume the Dense layer has weights Wd=0.4 and bias bd=0.1. The final prediction is computed as:

y^=Wd⋅h33+bd=0.4⋅0.473+0.1=0.2892+0.1=0.3892

Thus, the final output of the stacked RNN is y^=0.3892.

—

Step 5: Forecasting Multivariate Time Series

Explanation:

In multivariate time series, each time step contains multiple features (e.g., temperature, humidity, and wind speed). The RNN takes these multiple features and updates its hidden state based on all of them.

TensorFlow Code:

mulvar_model = tf.keras.Sequential([

tf.keras.layers.SimpleRNN(32, input_shape=[None, 5]),  # 5 features per time step

tf.keras.layers.Dense(1)

])

Numerical Example:

Let’s assume we have a **3-time-step sequence** with **5 features** at each time step. For simplicity, let’s use the following input:

X=[x11x12x13x14x15x21x22x23x24x25x31x32x33x34x35]=[0.10.20.30.40.50.20.30.40.50.60.30.40.50.60.7]

The input matrix X has 3 time steps (rows) and 5 features (columns).

Assume:

  • Wx is a matrix of size 32×5 (to process 5 features and produce 32 hidden states).
  • Wh is a matrix of size 32×32 (to process the previous hidden state of 32 units).
  • The biases b are vectors of size 32.
  • The activation function is tanh.

Let’s calculate the hidden state updates for each time step:

Time Step 1:

The input at the first time step is x1=[0.1,0.2,0.3,0.4,0.5].

The hidden state is updated as:

h1=tanh(Wh⋅0+Wx⋅x1+b)

For simplicity, assume Wx⋅x1=[0.15,0.2,…] (a vector of 32 values) and the bias b adds a small value to each component. The hidden state becomes a vector of length 32:

h1=tanh([0.15,0.2,…])=[0.149,0.197,…]

—

Time Step 2:

The input at time step 2 is x2=[0.2,0.3,0.4,0.5,0.6]. The hidden state is updated as:

h2=tanh(Wh⋅h1+Wx⋅x2+b)

Assume Wh⋅h1=[0.12,0.18,…] and Wx⋅x2=[0.25,0.3,…]. The hidden state becomes:

h2=tanh([0.37,0.48,…])=[0.354,0.447,…]

—

Time Step 3:

The input at time step 3 is x3=[0.3,0.4,0.5,0.6,0.7]. The hidden state is updated as:

h3=tanh(Wh⋅h2+Wx⋅x3+b)

Assume Wh⋅h2=[0.2,0.25,…] and Wx⋅x3=[0.3,0.35,…]. The final hidden state becomes:

h3=tanh([0.5,0.6,…])=[0.462,0.537,…]

—

Dense Layer Output:

The final hidden state h3 is passed to the Dense layer, which outputs the prediction. Assume the Dense layer has weights Wd=[0.5,…] and bias bd=0.1. The output is:

y^=WdTh3+bd=0.5⋅0.462+0.5⋅0.537+…+0.1=0.631

Thus, the final prediction is y^=0.631.

—

Key Takeaways:

  • Step 4: In stacked RNNs, each layer processes the sequence and passes it on, allowing the network to learn deeper temporal dependencies.
  • Step 5: For multivariate time series, RNNs can process multiple features at each time step, updating the hidden state based on the combined information from all the features.

If you need further details or other examples, feel free to reach out!

 

Count parameters and track shapes

A recurrent layer with d inputs and h hidden units has an input-to-state weight for each input and state pair and a state-to-state weight for each pair of hidden units. With a single bias vector it also has h bias entries. Sequence length changes the number of applications, not the count of distinct parameters.

P=dh+h2+h

A Keras SimpleRNN with five features and 32 hidden units has 160 input weights, 1,024 recurrent weights, and 32 biases, totaling 1,216 parameters. With eight steps and batch size 16, returning all states produces shape 16 by 8 by 32. A second layer that returns only the last state produces 16 by 32 for a single-target readout.

Count parameters and track shapesInput window16 by 8 by 5First RNN16 by 8 by 32Last state16 by 32
The second layer consumes the full time axis from the first layer.

Match Keras and PyTorch conventions

Keras 3 uses return_sequences=True when a following recurrent layer needs the time axis. PyTorch’s nn.RNN provides the time sequence and a separate final-state tensor. Default PyTorch uses two bias vectors per layer, so count an extra 32 entries for the illustrated single layer.

For forecasting, keep the target outside the input window and confirm that the label and final predictions have compatible shapes before relying on a reported loss.

References

Practice and FAQs

How does doubling sequence length affect the parameter count?

It leaves the count unchanged for the same recurrent architecture. It adds more applications of the same weights.

What goes into the second layer of a stacked RNN?

The sequence of hidden outputs from the previous recurrent layer.

What do you compare to reproduce a handwritten recurrence?

Use the same input order, weights, biases, activation, and initial state, then check each hidden state before comparing the final prediction.

You Can Also Learn Deep Learning in 80 Days Inside the iOS App Continue this roadmap in a focused mobile study experience with offline access, flashcards, notes, and progress tracking.
Open on the App Store