starting stateful, not turned on yet
[notebooks.git] / rnn_tutorial_jm.ipynb
blobdfb578b490e0051770a308ae542196ea2b91b27c
2   "nbformat": 4,
3   "nbformat_minor": 0,
4   "metadata": {
5     "colab": {
6       "name": "rnn_tutorial_jm.ipynb",
7       "provenance": [],
8       "collapsed_sections": []
9     },
10     "kernelspec": {
11       "name": "python3",
12       "display_name": "Python 3"
13     },
14     "language_info": {
15       "name": "python"
16     }
17   },
18   "cells": [
19     {
20       "cell_type": "markdown",
21       "metadata": {
22         "id": "hEhvqXQBNN6r"
23       },
24       "source": [
25         "# Understanding Simple Recurrent Neural Networks In Keras\n",
26         "From https://machinelearningmastery.com/understanding-simple-recurrent-neural-networks-in-keras/ \n",
27         "With changes by Jan Mandel\n",
28         "2021-12-26: small changes for clarity\n",
29         "2022-06-16: added same by functional interface"
30       ]
31     },
32     {
33       "cell_type": "markdown",
34       "metadata": {
35         "id": "pINycjukQijP"
36       },
37       "source": [
38         "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.\n",
39         "\n",
40         "After completing this tutorial, you will know:\n",
41         "\n",
42         "* The structure of RNN\n",
43         "* How RNN computes the output when given an input\n",
44         "* How to prepare data for a SimpleRNN in Keras\n",
45         "* How to train a SimpleRNN model\n",
46         "\n",
47         "Let’s get started."
48       ]
49     },
50     {
51       "cell_type": "markdown",
52       "metadata": {
53         "id": "3D7sqhF-QtJ4"
54       },
55       "source": [
56         "## Tutorial Overview\n",
57         "\n",
58         "This tutorial is divided into two parts; they are:\n",
59         "\n",
60         "1. The structure of the RNN\n",
61         "  1. Different weights and biases associated with different layers of the RNN.\n",
62         "  2. How computations are performed to compute the output when given an input.\n",
63         "2. A complete application for time series prediction."
64       ]
65     },
66     {
67       "cell_type": "markdown",
68       "metadata": {
69         "id": "jU0opwkmQ9wm"
70       },
71       "source": [
72         "## Prerequisites\n",
73         "\n",
74         "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](https://machinelearningmastery.com/an-introduction-to-recurrent-neural-networks-and-the-math-that-powers-them) gives you a quick overview of RNNs.\n",
75         "\n",
76         "Let’s now get right down to the implementation part."
77       ]
78     },
79     {
80       "cell_type": "markdown",
81       "metadata": {
82         "id": "-UcYCr1FMaE7"
83       },
84       "source": [
85         "## Import section"
86       ]
87     },
88     {
89       "cell_type": "code",
90       "metadata": {
91         "id": "FimVgAB4LsI9"
92       },
93       "source": [
94         "from pandas import read_csv\n",
95         "import numpy as np\n",
96         "from keras.models import Sequential\n",
97         "from keras.layers import Dense, SimpleRNN\n",
98         "from sklearn.preprocessing import MinMaxScaler\n",
99         "from sklearn.metrics import mean_squared_error\n",
100         "import math\n",
101         "import matplotlib.pyplot as plt\n",
102         "import tensorflow as tf"
103       ],
104       "execution_count": null,
105       "outputs": []
106     },
107     {
108       "cell_type": "markdown",
109       "metadata": {
110         "id": "O-okDDv9Md4Z"
111       },
112       "source": [
113         "## Keras SimpleRNN"
114       ]
115     },
116     {
117       "cell_type": "markdown",
118       "metadata": {
119         "id": "W-WQZp0qRta0"
120       },
121       "source": [
122         "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."
123       ]
124     },
125     {
126       "cell_type": "code",
127       "source": [
128         "api_type = 2   # 1 = sequential, 2 = functional"
129       ],
130       "metadata": {
131         "id": "Qf35beQp1Ewv"
132       },
133       "execution_count": null,
134       "outputs": []
135     },
136     {
137       "cell_type": "code",
138       "metadata": {
139         "id": "Aoh0LWQ7Ltdk"
140       },
141       "source": [
142         "def create_RNN_sequential(hidden_units, dense_units, input_shape, activation):\n",
143         "    model = Sequential()\n",
144         "    model.add(SimpleRNN(hidden_units, input_shape=input_shape, \n",
145         "                        activation=activation[0]))\n",
146         "    model.add(Dense(units=dense_units, activation=activation[1]))\n",
147         "    model.compile(loss='mean_squared_error', optimizer='adam')\n",
148         "    return model"
149       ],
150       "execution_count": null,
151       "outputs": []
152     },
153     {
154       "cell_type": "code",
155       "source": [
156         "def create_RNN_functional(hidden_units, dense_units, input_shape=None, activation=None,\n",
157         "                          return_sequences=False,stateful=False,batch_shape=None):\n",
158         "    inputs = tf.keras.Input(shape=input_shape)\n",
159         "    if stateful:\n",
160         "      x = tf.keras.layers.SimpleRNN(hidden_units, batch_shape=batch_shape,\n",
161         "                        return_sequences=return_sequences,\n",
162         "                        stateful=true,\n",
163         "                        activation=activation[0])(inputs)\n",
164         "    else:\n",
165         "      x = tf.keras.layers.SimpleRNN(hidden_units, input_shape=input_shape,\n",
166         "                        return_sequences=return_sequences,\n",
167         "                        activation=activation[0])(inputs)\n",
168         "    outputs = tf.keras.layers.Dense(dense_units, activation=activation[1])(x)\n",
169         "    model = tf.keras.Model(inputs=inputs, outputs=outputs)\n",
170         "    model.compile(loss='mean_squared_error', optimizer='adam')\n",
171         "    return model"
172       ],
173       "metadata": {
174         "id": "zBQxW0h8pvGb"
175       },
176       "execution_count": null,
177       "outputs": []
178     },
179     {
180       "cell_type": "code",
181       "source": [
182         "def create_RNN(hidden_units, dense_units, input_shape, activation):\n",
183         "    if api_type==1:\n",
184         "      print('using sequential api')\n",
185         "      return create_RNN_sequential(hidden_units, dense_units, input_shape, activation)\n",
186         "    if api_type==2:\n",
187         "      print('using functional api')\n",
188         "      return create_RNN_functional(hidden_units, dense_units, input_shape, activation)\n",
189         "    print('api_type must be 1 or 2, got ',api_type)\n",
190         "    raise(ValueError)\n",
191         "\n",
192         "demo_model = create_RNN(hidden_units=2, dense_units=1, input_shape=(3,1), \n",
193         "                        activation=['linear', 'linear'])"
194       ],
195       "metadata": {
196         "id": "dYLai9HypVRo"
197       },
198       "execution_count": null,
199       "outputs": []
200     },
201     {
202       "cell_type": "markdown",
203       "metadata": {
204         "id": "_CZtOyDPSuMy"
205       },
206       "source": [
207         "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."
208       ]
209     },
210     {
211       "cell_type": "code",
212       "source": [
213         "print(dir(demo_model))\n",
214         "# help(demo_model)\n",
215         "help(demo_model.get_weights)"
216       ],
217       "metadata": {
218         "id": "TgDQmxwQpUtw"
219       },
220       "execution_count": null,
221       "outputs": []
222     },
223     {
224       "cell_type": "markdown",
225       "metadata": {
226         "id": "BI0vVCjQTBPF"
227       },
228       "source": [
229         "Look at the model following https://machinelearningmastery.com/visualize-deep-learning-neural-network-model-keras/ :"
230       ]
231     },
232     {
233       "cell_type": "code",
234       "metadata": {
235         "id": "Rdz2nblaTMV5"
236       },
237       "source": [
238         "print(demo_model.summary())\n",
239         "from keras.utils.vis_utils import plot_model\n",
240         "plot_model(demo_model, to_file='model_plot.png', \n",
241         "           show_shapes=True, show_layer_names=True)"
242       ],
243       "execution_count": null,
244       "outputs": []
245     },
246     {
247       "cell_type": "markdown",
248       "metadata": {
249         "id": "6KMS82uNTZz4"
250       },
251       "source": [
252         "If we have m\n",
253         " hidden units (\n",
254         "m\n",
255         "=\n",
256         "2\n",
257         " in the above case), then:\n",
258         "* Input: \n",
259         "x\n",
260         "∈\n",
261         "R\n",
262         "* Hidden unit: \n",
263         "h\n",
264         "∈\n",
265         "R<sup>m</sup>\n",
266         "* Weights for input units: \n",
267         "w<sub>x</sub>\n",
268         "∈\n",
269         " R<sup>m</sup>\n",
270         "* Weights for hidden units: \n",
271         "w<sub>h</sub>\n",
272         "∈\n",
273         "R<sup>m x m</sup>\n",
274         "* Bias for hidden units: \n",
275         "b<sub>h</sub>\n",
276         "∈\n",
277         "R\n",
278         "<sup>m</sup>\n",
279         "*Weight for the dense layer: \n",
280         "w<sub>y</sub>\n",
281         "∈\n",
282         "R\n",
283         "<sup>m</sup>\n",
284         "*Bias for the dense layer: \n",
285         "b<sub>y</sub>\n",
286         "∈\n",
287         "R\n",
288         "\n",
289         "Let’s look at the above weights. The weights are generated randomly so they will be different every time. 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. The get_weights() method of the model object returns a list of arrays, which consists of the weights and the bias of each layer, in the order of the layers. The first layer's input takes two entries, the (external) input values and the values of the hidden variables from the previous step."
290       ]
291     },
292     {
293       "cell_type": "code",
294       "metadata": {
295         "id": "f-C4rYMDL1_l"
296       },
297       "source": [
298         "w = demo_model.get_weights()\n",
299         "#print(len(w),' weight arrays:',w)\n",
300         "wname=('wx','wh','bh','wy','by','wz','bz')\n",
301         "for i in range(len(w)):\n",
302         "  print(i,':',wname[i],'shape=',w[i].shape)\n",
303         "\n",
304         "wx = w[0]\n",
305         "wh = w[1]\n",
306         "bh = w[2]\n",
307         "wy = w[3]\n",
308         "by = w[4]"
309       ],
310       "execution_count": null,
311       "outputs": []
312     },
313     {
314       "cell_type": "code",
315       "source": [
316         "# help(SimpleRNN)"
317       ],
318       "metadata": {
319         "id": "kNzpNlwP4MSs"
320       },
321       "execution_count": null,
322       "outputs": []
323     },
324     {
325       "cell_type": "markdown",
326       "metadata": {
327         "id": "oks2sHZlUQZB"
328       },
329       "source": [
330         "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.\n",
331         "<img src=\"https://machinelearningmastery.com/wp-content/uploads/2021/09/rnnCode1.png\">"
332       ]
333     },
334     {
335       "cell_type": "markdown",
336       "metadata": {
337         "id": "eGi9cUkgUkTe"
338       },
339       "source": [
340         "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. \n",
341         "h<sub>0</sub>\n",
342         " is initialized to the zero vector. The output \n",
343         "o<sub>3</sub>\n",
344         " is computed from \n",
345         "h<sub>3</sub>\n",
346         " and \n",
347         "w<sub>3</sub>\n",
348         ". An activation function is linear, f(x)=x, so the update of $h(k)$ and the output $o(k)$ are given by"
349       ]
350     },
351     {
352       "cell_type": "markdown",
353       "metadata": {
354         "id": "QSD8ABJXxS7K"
355       },
356       "source": [
357         "\\begin{align*}\n",
358         "h\\left(  0\\right)  = &\\left[\n",
359         "\\begin{array}\n",
360         "[c]{c}%\n",
361         "0\\\\\n",
362         "0\n",
363         "\\end{array}\n",
364         "\\right]  \\\\\n",
365         "h\\left(  k+1\\right)  =&x\\left(  k\\right)  \\left[\n",
366         "\\begin{array}\n",
367         "[c]{c}%\n",
368         "w_{x,0}\\\\\n",
369         "w_{x,1}%\n",
370         "\\end{array}\n",
371         "\\right]  +\\left[  h_{0}(k),h_{1}(k)\\right]  \\left[\n",
372         "\\begin{array}\n",
373         "[c]{cc}%\n",
374         "w_{h,00} & w_{h,01}\\\\\n",
375         "w_{h,10} & w_{h,11}%\n",
376         "\\end{array}\n",
377         "\\right]  +\\left[\n",
378         "\\begin{array}\n",
379         "[c]{c}%\n",
380         "b_{h,0}\\\\\n",
381         "b_{h,1}%\n",
382         "\\end{array}\n",
383         "\\right]  \\\\\n",
384         "o(k+1)=& \\left[  h_{0}(k+1),h_{1}(k+1)\\right]  \\left[\n",
385         "\\begin{array}\n",
386         "[c]{c}%\n",
387         "w_{y,0}\\\\\n",
388         "w_{y,1}%\n",
389         "\\end{array}\n",
390         "\\right] \n",
391         "\\end{align*}\n"
392       ]
393     },
394     {
395       "cell_type": "markdown",
396       "metadata": {
397         "id": "MAvXBZodx8RP"
398       },
399       "source": [
400         "We compute this for $k=1,2,3$ and compare with the output of the model:"
401       ]
402     },
403     {
404       "cell_type": "code",
405       "metadata": {
406         "id": "kMOhAImzL7Ch"
407       },
408       "source": [
409         "w = demo_model.get_weights()\n",
410         "wx = w[0]\n",
411         "wh = w[1]\n",
412         "bh = w[2]\n",
413         "wy = w[3]\n",
414         "by = w[4]\n",
415         "x = np.array([1, 2, 3])\n",
416         "# Reshape the input to the required sample_size x time_steps x features \n",
417         "x_input = np.reshape(x,(1, 3, 1))\n",
418         "y_pred_model = demo_model.predict(x_input)\n",
419         "\n",
420         "\n",
421         "m = 2\n",
422         "h0 = np.zeros(m)\n",
423         "h1 = np.dot(x[0], wx) + np.dot(h0,wh) + bh\n",
424         "h2 = np.dot(x[1], wx) + np.dot(h1,wh) + bh\n",
425         "h3 = np.dot(x[2], wx) + np.dot(h2,wh) + bh\n",
426         "o3 = np.dot(h3, wy) + by\n",
427         "\n",
428         "print('h1 = ', h1,'h2 = ', h2,'h3 = ', h3)\n",
429         "\n",
430         "print(\"Prediction from network \", y_pred_model)\n",
431         "print(\"Prediction from our computation \", o3)"
432       ],
433       "execution_count": null,
434       "outputs": []
435     },
436     {
437       "cell_type": "code",
438       "source": [
439         "# the same using arrays\n",
440         "demo_model = create_RNN_functional(hidden_units=2, dense_units=1, input_shape=(3,1), \n",
441         "                        activation=['linear', 'linear'],return_sequences=True)\n",
442         "w = demo_model.get_weights()\n",
443         "\n",
444         "x = np.array([1, 2, 3])\n",
445         "# Reshape the input to the required sample_size x time_steps x features \n",
446         "x_input = np.reshape(x,(1, 3, 1))\n",
447         "y_pred_model = demo_model.predict(x_input)\n",
448         "\n",
449         "h = np.zeros(2)\n",
450         "o = np.empty(3)\n",
451         "for i in range(3):\n",
452         "  h = np.dot(x[i], w[0]) + np.dot(h, w[1]) + w[2]\n",
453         "  o[i]=np.dot(h, w[3]) + w[4]\n",
454         "\n",
455         "print(\"Prediction from network \", y_pred_model)\n",
456         "print(\"Prediction from our computation \", o)"
457       ],
458       "metadata": {
459         "id": "Q2kuhi2KBNY4"
460       },
461       "execution_count": null,
462       "outputs": []
463     },
464     {
465       "cell_type": "code",
466       "source": [
467         "# stateful\n",
468         "demo_model = create_RNN_functional(hidden_units=2, dense_units=1, input_shape=(3,1), \n",
469         "                        activation=['linear', 'linear'],return_sequences=True)\n",
470         "w = demo_model.get_weights()\n",
471         "\n",
472         "x = np.array([1, 2, 3])\n",
473         "# Reshape the input to the required sample_size x time_steps x features \n",
474         "x_input = np.reshape(x,(1, 3, 1))\n",
475         "y_pred_model = demo_model.predict(x_input)\n",
476         "\n",
477         "h = np.zeros(2)\n",
478         "o = np.empty(3)\n",
479         "for i in range(3):\n",
480         "  h = np.dot(x[i], w[0]) + np.dot(h, w[1]) + w[2]\n",
481         "  o[i]=np.dot(h, w[3]) + w[4]\n",
482         "\n",
483         "print(\"Prediction from network \", y_pred_model)\n",
484         "print(\"Prediction from our computation \", o)"
485       ],
486       "metadata": {
487         "id": "SLYRVhFGHa4r"
488       },
489       "execution_count": null,
490       "outputs": []
491     },
492     {
493       "cell_type": "markdown",
494       "metadata": {
495         "id": "JopR12ZaVAyS"
496       },
497       "source": [
498         "The predictions came out the same! This confirms that we know what the network is doing."
499       ]
500     },
501     {
502       "cell_type": "markdown",
503       "metadata": {
504         "id": "dHGF-tofMpJP"
505       },
506       "source": [
507         "## Step 1, 2: Reading Data and Splitting Into Train And Test"
508       ]
509     },
510     {
511       "cell_type": "markdown",
512       "metadata": {
513         "id": "5x748YZuY-yL"
514       },
515       "source": [
516         "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."
517       ]
518     },
519     {
520       "cell_type": "code",
521       "metadata": {
522         "id": "JyrxUuiuL8gv"
523       },
524       "source": [
525         "# Parameter split_percent defines the ratio of training examples\n",
526         "def get_train_test(data, split_percent=0.8):\n",
527         "    scaler = MinMaxScaler(feature_range=(0, 1))\n",
528         "    data = scaler.fit_transform(data).flatten()\n",
529         "    n = len(data)\n",
530         "    # Point for splitting data into train and test\n",
531         "    split = int(n*split_percent)\n",
532         "    train_data = data[range(split)]\n",
533         "    test_data = data[split:]\n",
534         "    return train_data, test_data, data\n",
535         "\n",
536         "sunspots_url = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/monthly-sunspots.csv'\n",
537         "df = read_csv(sunspots_url, usecols=[1], engine='python')\n",
538         "train_data, test_data, data = get_train_test(np.array(df.values.astype('float32')))"
539       ],
540       "execution_count": null,
541       "outputs": []
542     },
543     {
544       "cell_type": "markdown",
545       "metadata": {
546         "id": "iCsHwJOcZMJ7"
547       },
548       "source": [
549         "Let's print the data shape so that we know what we got."
550       ]
551     },
552     {
553       "cell_type": "code",
554       "metadata": {
555         "id": "h5AmHug8JViT"
556       },
557       "source": [
558         "data.shape"
559       ],
560       "execution_count": null,
561       "outputs": []
562     },
563     {
564       "cell_type": "markdown",
565       "metadata": {
566         "id": "QHoBV8CSMt44"
567       },
568       "source": [
569         "## Step 3: Reshaping Data For Keras"
570       ]
571     },
572     {
573       "cell_type": "markdown",
574       "metadata": {
575         "id": "B1CW_mu8Zbwb"
576       },
577       "source": [
578         "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)**.\n",
579         "There are many ways of preparing time series data for training. We’ll create input rows with non-overlapping time steps. An example 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. We have for time_steps = 2, features = 1, and the first 6 terms are split total_samples=3 samples: 0, 10 predict the next term 20, then 20, 30 predict the next term 40, etc."
580       ]
581     },
582     {
583       "cell_type": "markdown",
584       "metadata": {
585         "id": "OeEc_dmqZmtx"
586       },
587       "source": [
588         "<img src=\"https://machinelearningmastery.com/wp-content/uploads/2021/09/rnnCode2.png\">"
589       ]
590     },
591     {
592       "cell_type": "markdown",
593       "metadata": {
594         "id": "iLqm8291Pd5X"
595       },
596       "source": [
597         "The following function get_XY() takes a one dimensional array as input and converts it to the required input X and target Y arrays."
598       ]
599     },
600     {
601       "cell_type": "code",
602       "metadata": {
603         "id": "IxJEj52BL__o"
604       },
605       "source": [
606         "# Prepare the input X and target Y\n",
607         "def get_XY(dat, time_steps):\n",
608         "    # Indices of target array\n",
609         "    Y_ind = np.arange(time_steps, len(dat), time_steps)\n",
610         "    Y = dat[Y_ind]\n",
611         "    # Prepare X\n",
612         "    rows_x = len(Y)\n",
613         "    X = dat[range(time_steps*rows_x)]\n",
614         "    X = np.reshape(X, (rows_x, time_steps, 1))    \n",
615         "    return X, Y"
616       ],
617       "execution_count": null,
618       "outputs": []
619     },
620     {
621       "cell_type": "markdown",
622       "metadata": {
623         "id": "RFhadJjzQO7p"
624       },
625       "source": [
626         "For illustration, on the simple example above it returns the expected result: "
627       ]
628     },
629     {
630       "cell_type": "code",
631       "metadata": {
632         "id": "V38oXJ32QiFK"
633       },
634       "source": [
635         "dat = np.linspace(0.,70.,8).reshape(-1,1)\n",
636         "print(\"dat shape=\",dat.shape)\n",
637         "X, Y = get_XY(dat, 2)\n",
638         "print(\"X shape=\",X.shape)\n",
639         "print(\"Y shape=\",Y.shape)\n",
640         "#print('dat=',dat)\n",
641         "print('X=',X)\n",
642         "print('Y=',Y)\n"
643       ],
644       "execution_count": null,
645       "outputs": []
646     },
647     {
648       "cell_type": "markdown",
649       "metadata": {
650         "id": "4V4IE7TvQpDW"
651       },
652       "source": [
653         "Now use it for the sunspot data.  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."
654       ]
655     },
656     {
657       "cell_type": "code",
658       "metadata": {
659         "id": "YBnBPDxiQsjL"
660       },
661       "source": [
662         "time_steps = 24\n",
663         "trainX, trainY = get_XY(train_data, time_steps)\n",
664         "testX, testY = get_XY(test_data, time_steps)\n",
665         "print(\"trainX shape=\",trainX.shape)\n",
666         "print(\"trainY shape=\",trainY.shape)\n",
667         "print(\"testX shape=\",testX.shape)\n",
668         "print(\"testY shape=\",testY.shape)"
669       ],
670       "execution_count": null,
671       "outputs": []
672     },
673     {
674       "cell_type": "markdown",
675       "metadata": {
676         "id": "Xz2JRTGKMzo2"
677       },
678       "source": [
679         "## Step 4: Create RNN Model And Train"
680       ]
681     },
682     {
683       "cell_type": "code",
684       "metadata": {
685         "id": "SyAE6XLnMGDO"
686       },
687       "source": [
688         "model = create_RNN(hidden_units=3, dense_units=1, input_shape=(time_steps,1), \n",
689         "                   activation=['tanh', 'tanh'])\n",
690         "model.fit(trainX, trainY, epochs=20, batch_size=1, verbose=2)"
691       ],
692       "execution_count": null,
693       "outputs": []
694     },
695     {
696       "cell_type": "markdown",
697       "metadata": {
698         "id": "tluiPIaxM9FH"
699       },
700       "source": [
701         "## Step 5: Compute And Print The Root Mean Square Error"
702       ]
703     },
704     {
705       "cell_type": "code",
706       "metadata": {
707         "id": "LnWdCmqJMK-k"
708       },
709       "source": [
710         "def print_error(trainY, testY, train_predict, test_predict):    \n",
711         "    # Error of predictions\n",
712         "    train_rmse = math.sqrt(mean_squared_error(trainY, train_predict))\n",
713         "    test_rmse = math.sqrt(mean_squared_error(testY, test_predict))\n",
714         "    # Print RMSE\n",
715         "    print('Train RMSE: %.3f RMSE' % (train_rmse))\n",
716         "    print('Test RMSE: %.3f RMSE' % (test_rmse))    \n",
717         "\n",
718         "# make predictions\n",
719         "train_predict = model.predict(trainX)\n",
720         "test_predict = model.predict(testX)\n",
721         "# Mean square error\n",
722         "print_error(trainY, testY, train_predict, test_predict)"
723       ],
724       "execution_count": null,
725       "outputs": []
726     },
727     {
728       "cell_type": "markdown",
729       "metadata": {
730         "id": "eed7244NNHs9"
731       },
732       "source": [
733         ""
734       ]
735     },
736     {
737       "cell_type": "markdown",
738       "metadata": {
739         "id": "nDwJvflyNGz3"
740       },
741       "source": [
742         "## Step 6: View The result"
743       ]
744     },
745     {
746       "cell_type": "code",
747       "metadata": {
748         "id": "fQPjWHWvMMGL"
749       },
750       "source": [
751         "# Plot the result\n",
752         "def plot_result(trainY, testY, train_predict, test_predict):\n",
753         "    actual = np.append(trainY, testY)\n",
754         "    predictions = np.append(train_predict, test_predict)\n",
755         "    rows = len(actual)\n",
756         "    plt.figure(figsize=(15, 6), dpi=80)\n",
757         "    plt.plot(range(rows), actual)\n",
758         "    plt.plot(range(rows), predictions)\n",
759         "    plt.axvline(x=len(trainY), color='r')\n",
760         "    plt.legend(['Actual', 'Predictions'])\n",
761         "    plt.xlabel('Observation number after given time steps')\n",
762         "    plt.ylabel('Sunspots scaled')\n",
763         "    plt.title('Actual and Predicted Values. The Red Line Separates The Training And Test Examples')\n",
764         "plot_result(trainY, testY, train_predict, test_predict)"
765       ],
766       "execution_count": null,
767       "outputs": []
768     }
769   ]