Monday, November 28, 2022
HomeArtificial IntelligenceUnderstanding Easy Recurrent Neural Networks In Keras

Understanding Easy Recurrent Neural Networks In Keras

This tutorial is designed for anyone looking for an understanding of how recurrent neural networks (RNN) work and how to use them via the Keras deep learning library. While all the methods required for solving problems and building applications are provided by the Keras library, it is also important to gain an insight on how everything works. In this article, the computations taking place in the RNN model are shown step by step. Next, a complete end to end system for time series prediction is developed.

After completing this tutorial, you will know:

  • The structure of RNN
  • How RNN computes the output when given an input
  • How to prepare data for a SimpleRNN in Keras
  • How to train a SimpleRNN model

Let’s get started.

Umstead state park

Understanding Simple Recurrent Neural Networks In Keras Photo by Mehreen Saeed, some rights reserved.

Tutorial Overview

This tutorial is divided into two parts; they are:

  1. The structure of the RNN
    1. Different weights and biases associated with different layers of the RNN.
    2. How computations are performed to compute the output when given an input.
  2. A complete application for time series prediction.


It is assumed that you have a basic understanding of RNNs before you start implementing them. An Introduction To Recurrent Neural Networks And The Math That Powers Them gives you a quick overview of RNNs.

Let’s now get right down to the implementation part.

Import section

To start the implementation of RNNs, let’s add the import section.

Keras SimpleRNN

The function below returns a model that includes a SimpleRNN layer and a Dense layer for learning sequential data. The input_shape specifies the parameter (time_steps x features). We’ll simplify everything and use univariate data, i.e., one feature only; the time_steps are discussed below.

The object demo_model is returned with 2 hidden units created via a the SimpleRNN layer and 1 dense unit created via the Dense layer. The input_shape is set at 3×1 and a linear activation function is used in both layers for simplicity. Just to recall the linear activation function $f(x) = x$ makes no change in the input. The network looks as follows:

If we have $m$ hidden units ($m=2$ in the above case), then:

  • Input: $x in R$
  • Hidden unit: $h in R^m$
  • Weights for input units: $w_x in R^m$
  • Weights for hidden units: $w_h in R^{mxm}$
  • Bias for hidden units: $b_h in R^m$
  • Weight for the dense layer: $w_y in R^m$
  • Bias for the dense layer: $b_y in R$

Let’s look at the above weights. Note: As the weights are initialized randomly, the results pasted here will be different from yours. The important thing is to learn what the structure of each object being used looks like and how it interacts with others to produce the final output.

Now let’s do a simple experiment to see how the layers from a SimpleRNN and Dense layer produce an output. Keep this figure in view.

Layers Of A Recurrent Neural Network

Layers Of A Recurrent Neural Network

We’ll input x for three time steps and let the network generate an output. The values of the hidden units at time steps 1, 2 and 3 will be computed. $h_0$ is initialized to the zero vector. The output $o_3$ is computed from $h_3$ and $w_y$. An activation function is not required as we are using linear units.

Running The RNN On Sunspots Dataset

Now that we understand how the SimpleRNN and Dense layers are put together. Let’s run a complete RNN on a simple time series dataset. We’ll need to follow these steps

  1. Read the dataset from a given URL
  2. Split the data into training and test set
  3. Prepare the input to the required Keras format
  4. Create an RNN model and train it
  5. Make the predictions on training and test sets and print the root mean square error on both sets
  6. View the result

Step 1, 2: Reading Data and Splitting Into Train And Test

The following function reads the train and test data from a given URL and splits it into a given percentage of train and test data. It returns single dimensional arrays for train and test data after scaling the data between 0 and 1 using MinMaxScaler from scikit-learn.

Step 3: Reshaping Data For Keras

The next step is to prepare the data for Keras model training. The input array should be shaped as: total_samples x time_steps x features.

There are many ways of preparing time series data for training. We’ll create input rows with non-overlapping time steps. An example for time_steps = 2 is shown in the figure below. Here time_steps denotes the number of previous time steps to use for predicting the next value of the time series data.

How Data Is Prepared For Sunspots Example

How Data Is Prepared For Sunspots Example

The following function get_XY() takes a one dimensional array as input and converts it to the required input X and target Y arrays. We’ll use 12 time_steps for the sunspots dataset as the sunspots generally have a cycle of 12 months. You can experiment with other values of time_steps.

Step 4: Create RNN Model And Train

For this step, we can reuse our create_RNN() function that was defined above.

Step 5: Compute And Print The Root Mean Square Error

The function print_error() computes the mean square error between the actual values and the predicted values.

Step 6: View The result

The following function plots the actual target values and the predicted value. The red line separates the training and test data points.

The following plot is generated:

Consolidated Code

Given below is the entire code for this tutorial. Do try this out at your end and experiment with different hidden units and time steps. You can add a second SimpleRNN to the network and see how it behaves. You can also use the scaler object to rescale the data back to its normal range.

Further Reading

This section provides more resources on the topic if you are looking to go deeper.




In this tutorial, you discovered recurrent neural networks and their various architectures.

Specifically, you learned:

  • The structure of RNNs
  • How the RNN computes an output from previous inputs
  • How to implement an end to end system for time series forecasting using an RNN

Do you have any questions about RNNs discussed in this post? Ask your questions in the comments below and I will do my best to answer.



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments