Skip to main content
This section is from the Hands on Machine Learning using Scikit-Learn and Tensorflow 2, 2nd edition
Open In Colab

Time Series Prediction using RNNs

First, let’s import a few common modules, ensure MatplotLib plots figures inline and prepare a function to save the figures. We also check that Python 3.5 or later is installed (although Python 2.x may work, it is deprecated so we strongly recommend you use Python 3 instead), as well as Scikit-Learn ≥0.20 and TensorFlow ≥2.0.

Basic RNNs

Generate the Dataset

Output from cell 5
Note: in this section, the blue dots represent targets, and red crosses represent predictions. In the book, I first used blue crosses for targets and red dots for predictions, then I reversed this later in the chapter. Sorry if this caused some confusion.

Computing Some Baselines

Naive predictions (just predict the last observed value):
Output from cell 7
Linear predictions:
Output from cell 10
Output from cell 11

Using a Simple RNN

Output from cell 15
Output from cell 16

Deep RNNs

Output from cell 19
Output from cell 20
Make the second SimpleRNN layer return only the last output:
Output from cell 23
Output from cell 24

Forecasting Several Steps Ahead

Output from cell 27
Now let’s use this model to predict the next 10 values. We first need to regenerate the sequences with 9 more time steps.
Now let’s predict the next 10 values one by one:
Let’s compare this performance with some baselines: naive predictions and a simple linear model:
Now let’s create an RNN that predicts all 10 next values at once:
Output from cell 36
Now let’s create an RNN that predicts the next 10 steps at each time step. That is, instead of just forecasting time steps 50 to 59 based on time steps 0 to 49, it will forecast time steps 1 to 10 at time step 0, then time steps 2 to 11 at time step 1, and so on, and finally it will forecast time steps 50 to 59 at the last time step. Notice that the model is causal: when it makes predictions at any time step, it can only see past time steps.
Output from cell 41

Deep RNN with Batch Norm

Deep RNNs with Layer Norm

Creating a Custom RNN Class

LSTMs

Output from cell 50
Output from cell 52

PyTorch reference