[MODELS] Cleanup Jupyter Notebooks.
[thoth.git] / models / failure_prediction / jnotebooks / Bi_LSTMstacked_LSTM_Correlation.ipynb
1 {
2  "cells": [
3   {
4    "cell_type": "markdown",
5    "metadata": {
6     "id": "l43uL109ZssB"
7    },
8    "source": [
9     "Contributors: **Rohit Singh Rathaur, Girish L.** \n",
10     "\n",
11     "Copyright [2021](2021) [*Rohit Singh Rathaur, BIT Mesra and Girish L., CIT GUBBI, Karnataka*]\n",
12     "\n",
13     "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
14     "you may not use this file except in compliance with the License.\n",
15     "You may obtain a copy of the License at\n",
16     "\n",
17     "    http://www.apache.org/licenses/LICENSE-2.0\n",
18     "\n",
19     "Unless required by applicable law or agreed to in writing, software\n",
20     "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
21     "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
22     "See the License for the specific language governing permissions and\n",
23     "limitations under the License."
24    ]
25   },
26   {
27    "cell_type": "code",
28    "execution_count": null,
29    "metadata": {
30     "colab": {
31      "base_uri": "https://localhost:8080/"
32     },
33     "id": "YQ6lT1e2hrx4",
34     "outputId": "14ee2b60-05d7-4163-d420-58970bc4e4b0"
35    },
36    "outputs": [],
37    "source": [
38     "from google.colab import drive\n",
39     "drive.mount('/content/drive')"
40    ]
41   },
42   {
43    "cell_type": "code",
44    "execution_count": null,
45    "metadata": {
46     "id": "tLhroy5BnMnC"
47    },
48    "outputs": [],
49    "source": [
50     "# Importing libraries\n",
51     "import tensorflow as tf\n",
52     "import matplotlib.pyplot as plt\n",
53     "import matplotlib as mpl\n",
54     "import pandas as pd\n",
55     "import numpy as np\n",
56     "import os"
57    ]
58   },
59   {
60    "cell_type": "code",
61    "execution_count": null,
62    "metadata": {
63     "colab": {
64      "base_uri": "https://localhost:8080/",
65      "height": 521
66     },
67     "id": "2-UpMVsSnfCI",
68     "outputId": "87e645f2-f2f9-4e8e-e0b9-fd807224892a"
69    },
70    "outputs": [],
71    "source": [
72     "df_Ellis  = pd.read_csv(\"/content/drive/MyDrive/LFN Anuket/Analysis/data/Final/Ellis_FinalTwoConditionwithOR.csv\")\n",
73     "df_Ellis"
74    ]
75   },
76   {
77    "cell_type": "code",
78    "execution_count": null,
79    "metadata": {
80     "colab": {
81      "base_uri": "https://localhost:8080/",
82      "height": 293
83     },
84     "id": "92xBt43BnjAo",
85     "outputId": "747e6ee9-2da1-43af-c751-1261f54d6c2c"
86    },
87    "outputs": [],
88    "source": [
89     "df_Ellis.plot()"
90    ]
91   },
92   {
93    "cell_type": "markdown",
94    "metadata": {
95     "id": "46U0FXYB6AbD"
96    },
97    "source": [
98     "We showed here the histograms of Ellis data"
99    ]
100   },
101   {
102    "cell_type": "code",
103    "execution_count": null,
104    "metadata": {
105     "colab": {
106      "base_uri": "https://localhost:8080/",
107      "height": 879
108     },
109     "id": "RSo-aa-SIoBR",
110     "outputId": "eeead93b-89b4-4798-976c-1b065bbbc4a3"
111    },
112    "outputs": [],
113    "source": [
114     "# we show here the hist\n",
115     "df_Ellis.hist(bins=100,figsize=(20,15))\n",
116     "#save_fig(\"attribute_histogram_plots\")\n",
117     "plt.show()"
118    ]
119   },
120   {
121    "cell_type": "code",
122    "execution_count": null,
123    "metadata": {
124     "colab": {
125      "base_uri": "https://localhost:8080/",
126      "height": 634
127     },
128     "id": "gggaMJ_2LtFs",
129     "outputId": "c3ac6c2e-c7f3-48ae-c562-23bb7b60c5b4"
130    },
131    "outputs": [],
132    "source": [
133     "cpu_system_perc = df_Ellis[['ellis-cpu.system_perc']] \n",
134     "cpu_system_perc.rolling(12).mean().plot(figsize=(20,10), linewidth=5, fontsize=20) \n",
135     "plt.xlabel('Timestamp', fontsize=30);"
136    ]
137   },
138   {
139    "cell_type": "code",
140    "execution_count": null,
141    "metadata": {
142     "colab": {
143      "base_uri": "https://localhost:8080/",
144      "height": 634
145     },
146     "id": "R_ctvXcQL1Xf",
147     "outputId": "d553c7b1-3a00-40dd-ad5f-cc695d3ecbae"
148    },
149    "outputs": [],
150    "source": [
151     "load_avg_1_min = df_Ellis[['ellis-load.avg_1_min']] \n",
152     "load_avg_1_min.rolling(12).mean().plot(figsize=(20,10), linewidth=5, fontsize=20) \n",
153     "plt.xlabel('Timestamp', fontsize=30);"
154    ]
155   },
156   {
157    "cell_type": "markdown",
158    "metadata": {
159     "id": "9jTOMzOqEQEZ"
160    },
161    "source": [
162     "## Identifying trends in Time Series data\n",
163     "There are several ways to think about identifying trends in time series. One popular way is by taking a rolling average, which means that, for each time point, we take the average of the points on either side of it. Note that the number of points is specified by a window size, which we need to choose.\n",
164     "\n",
165     "What happens then because we take the average is it tends to smooth out noise and seasonality. We will see that below right now. Check out this rolling average of `'ellis-cpu.wait_perc'` using the built-in `pandas` methods.\n",
166     "\n",
167     "When it comes to determining the window size, here, it makes sense to first try out one of twelve months, as we're talking about yearly seasonality.\n",
168     "\n",
169     "Note that in the code chunk above we used two sets of squared brackets to extract the `'ellis-cpu.wait_perc'` column as a DataFrame; If we would have used one set, like `df_Ellis['ellis-cpu.wait_perc']`, we would have created a pandas Series.\n",
170     "\n",
171     "In the code chunk above, you also chained methods: you called methods on an object one after another. Method chaining is pretty popular and pandas is one of the packages that really allows you to use that style of programming to the max!"
172    ]
173   },
174   {
175    "cell_type": "code",
176    "execution_count": null,
177    "metadata": {
178     "colab": {
179      "base_uri": "https://localhost:8080/",
180      "height": 634
181     },
182     "id": "Gkd5ecCmL6Bw",
183     "outputId": "c8f8cd9a-8477-46b9-e350-9b501f8bf55b"
184    },
185    "outputs": [],
186    "source": [
187     "cpu_wait_perc = df_Ellis[['ellis-cpu.wait_perc']] \n",
188     "cpu_wait_perc.rolling(12).mean().plot(figsize=(20,10), linewidth=5, fontsize=20) \n",
189     "plt.xlabel('Year', fontsize=30);"
190    ]
191   },
192   {
193    "cell_type": "markdown",
194    "metadata": {
195     "id": "JKNmf5TeFvQt"
196    },
197    "source": [
198     "We have successfully removed the seasonality and we saw an upward trend for `ellis-cpu.wait_perc`! But how do these two search terms compare?\n",
199     "\n",
200     "We can figure this out by plotting the trends of `'ellis-cpu.wait_perc'`, `cpu_system_perc` and `'load_avg_1_min'` on a single figure:"
201    ]
202   },
203   {
204    "cell_type": "code",
205    "execution_count": null,
206    "metadata": {
207     "colab": {
208      "base_uri": "https://localhost:8080/",
209      "height": 624
210     },
211     "id": "EycZrQU0MBSX",
212     "outputId": "02683682-38ad-4745-c7bb-99a9058bb755"
213    },
214    "outputs": [],
215    "source": [
216     "df_dg = pd.concat([cpu_system_perc.rolling(12).mean(), load_avg_1_min.rolling(12).mean(),cpu_wait_perc.rolling(12).mean()], axis=1) \n",
217     "df_dg.plot(figsize=(20,10), linewidth=5, fontsize=20) \n",
218     "plt.xlabel('Year', fontsize=20); "
219    ]
220   },
221   {
222    "cell_type": "markdown",
223    "metadata": {
224     "id": "PTkbQPa_6MNb"
225    },
226    "source": [
227     "We established the correlation matrix for Ellis data.\n",
228     "Seaborn has five built-in themes to style its plots: `darkgrid`, `whitegrid`, `dark`, `white`, and `ticks`. Seaborn defaults to using the darkgrid theme for its plots, but we can change this styling to better suit our presentation needs.\n",
229     "\n",
230     "To use any of the preset themes pass the name of it to `sns.set_style()`."
231    ]
232   },
233   {
234    "cell_type": "code",
235    "execution_count": null,
236    "metadata": {
237     "colab": {
238      "base_uri": "https://localhost:8080/",
239      "height": 710
240     },
241     "id": "Pi8UMMitMa3Q",
242     "outputId": "6e2c3c3c-5a69-42ef-87a8-7dfdd65e7ceb"
243    },
244    "outputs": [],
245    "source": [
246     "# we establish the corrmartrice\n",
247     "import seaborn as sns\n",
248     "color = sns.color_palette()\n",
249     "sns.set_style('darkgrid')\n",
250     "\n",
251     "correaltionMatrice = df_Ellis.corr()\n",
252     "f, ax = plt.subplots(figsize=(20, 10))\n",
253     "sns.heatmap(correaltionMatrice, cbar=True, vmin=0, vmax=1, square=True, annot=True);\n",
254     "plt.show()"
255    ]
256   },
257   {
258    "cell_type": "markdown",
259    "metadata": {
260     "id": "tdg8lD0OHEtH"
261    },
262    "source": [
263     "Correlation between rows or columns of two DataFrame objectsCompute pairwise"
264    ]
265   },
266   {
267    "cell_type": "code",
268    "execution_count": null,
269    "metadata": {
270     "colab": {
271      "base_uri": "https://localhost:8080/"
272     },
273     "id": "rkYwyKtXMvpy",
274     "outputId": "ab6efc64-5329-4ad2-e5a8-acecf7c79eff"
275    },
276    "outputs": [],
277    "source": [
278     "df_Ellis.corrwith(df_Ellis['ellis-load.avg_1_min'])"
279    ]
280   },
281   {
282    "cell_type": "code",
283    "execution_count": null,
284    "metadata": {
285     "colab": {
286      "base_uri": "https://localhost:8080/",
287      "height": 235
288     },
289     "id": "5oQK-ddinvCM",
290     "outputId": "3e1fc354-aefb-496b-9e08-d05a458f9c23"
291    },
292    "outputs": [],
293    "source": [
294     "## ## using multivariate feature \n",
295     "\n",
296     "features_3 = ['ellis-cpu.wait_perc', 'ellis-load.avg_1_min', 'ellis-net.in_bytes_sec', 'Label']\n",
297     "\n",
298     "features = df_Ellis[features_3]\n",
299     "features.index = df_Ellis['Timestamp']\n",
300     "features.head()"
301    ]
302   },
303   {
304    "cell_type": "code",
305    "execution_count": null,
306    "metadata": {
307     "colab": {
308      "base_uri": "https://localhost:8080/",
309      "height": 386
310     },
311     "id": "qbqn755fo81g",
312     "outputId": "a8c2999d-5fd1-4de3-f8fd-05cd6ff14622"
313    },
314    "outputs": [],
315    "source": [
316     "features.plot(subplots=True)"
317    ]
318   },
319   {
320    "cell_type": "code",
321    "execution_count": null,
322    "metadata": {
323     "id": "jJQD1x9psWCH"
324    },
325    "outputs": [],
326    "source": [
327     "features = features.values"
328    ]
329   },
330   {
331    "cell_type": "markdown",
332    "metadata": {
333     "id": "Q23ry_WpH6tt"
334    },
335    "source": [
336     "train test split for simple time series moving window average"
337    ]
338   },
339   {
340    "cell_type": "code",
341    "execution_count": null,
342    "metadata": {
343     "colab": {
344      "base_uri": "https://localhost:8080/"
345     },
346     "id": "xf8WCiykpUzN",
347     "outputId": "6375471f-a7ec-4416-95e0-4f9a82872168"
348    },
349    "outputs": [],
350    "source": [
351     "### standardize data\n",
352     "train_split = 141600\n",
353     "tf.random.set_seed(13)\n",
354     "\n",
355     "### standardize data\n",
356     "features_mean = features[:train_split].mean()\n",
357     "features_std = features[:train_split].std()\n",
358     "features  = (features - features_mean)/ features_std\n",
359     "\n",
360     "print(type(features))\n",
361     "print(features.shape)\n"
362    ]
363   },
364   {
365    "cell_type": "markdown",
366    "metadata": {
367     "id": "22Y4ztlZIpFG"
368    },
369    "source": [
370     "Created multivariate data"
371    ]
372   },
373   {
374    "cell_type": "code",
375    "execution_count": null,
376    "metadata": {
377     "id": "1a0hNDmppnLB"
378    },
379    "outputs": [],
380    "source": [
381     "### create mutlivariate data\n",
382     "\n",
383     "def mutlivariate_data(features , target , start_idx , end_idx , history_size , target_size,\n",
384     "                      step ,  single_step = False):\n",
385     "  data = []\n",
386     "  labels = []\n",
387     "  start_idx = start_idx + history_size\n",
388     "  if end_idx is None:\n",
389     "    end_idx = len(features)- target_size\n",
390     "  for i in range(start_idx , end_idx ):\n",
391     "    idxs = range(i-history_size, i, step) ### using step\n",
392     "    data.append(features[idxs])\n",
393     "    if single_step:\n",
394     "      labels.append(target[i+target_size])\n",
395     "    else:\n",
396     "      labels.append(target[i:i+target_size])\n",
397     "\n",
398     "  return np.array(data) , np.array(labels)"
399    ]
400   },
401   {
402    "cell_type": "code",
403    "execution_count": null,
404    "metadata": {
405     "colab": {
406      "base_uri": "https://localhost:8080/"
407     },
408     "id": "Z0CivgkitfgE",
409     "outputId": "3f2a841e-eec2-4cf9-e370-4ab5a8bcc725"
410    },
411    "outputs": [],
412    "source": [
413     "### generate multivariate data\n",
414     "\n",
415     "history = 720\n",
416     "future_target = 72\n",
417     "STEP = 6\n",
418     "\n",
419     "x_train_ss , y_train_ss = mutlivariate_data(features , features[:, 1], 0, train_split, history,\n",
420     "                                            future_target, STEP , single_step = True)\n",
421     "\n",
422     "x_val_ss , y_val_ss = mutlivariate_data(features , features[:,1] , train_split , None , history ,\n",
423     "                                        future_target, STEP, single_step = True)\n",
424     "\n",
425     "print(x_train_ss.shape , y_train_ss.shape)\n",
426     "print(x_val_ss.shape , y_val_ss.shape)"
427    ]
428   },
429   {
430    "cell_type": "markdown",
431    "metadata": {
432     "id": "MMSskyxNaMj3"
433    },
434    "source": [
435     "The `tf.data.Dataset` API supports writing descriptive and efficient input pipelines. Dataset usage following a common pattern:\n",
436     "- Creating a source dataset from our input data.\n",
437     "- Applied dataset transformations to preprocess the data.\n",
438     "- Iterate over the dataset and process the elements.\n",
439     "Note: Iteration happens in a streaming fashion, so the full dataset does not need to fit into memory.\n",
440     "Once we have a dataset, we can apply transformations to prepare the data for our model:"
441    ]
442   },
443   {
444    "cell_type": "code",
445    "execution_count": null,
446    "metadata": {
447     "colab": {
448      "base_uri": "https://localhost:8080/"
449     },
450     "id": "VBdr2epGu3aq",
451     "outputId": "719a1cea-6548-4597-fc05-b183cc485387"
452    },
453    "outputs": [],
454    "source": [
455     "## tensorflow dataset\n",
456     "batch_size = 256\n",
457     "buffer_size = 10000\n",
458     "\n",
459     "train_ss = tf.data.Dataset.from_tensor_slices((x_train_ss, y_train_ss))\n",
460     "train_ss = train_ss.cache().shuffle(buffer_size).batch(batch_size).repeat()\n",
461     "\n",
462     "val_ss = tf.data.Dataset.from_tensor_slices((x_val_ss, y_val_ss))\n",
463     "val_ss = val_ss.cache().shuffle(buffer_size).batch(batch_size).repeat()\n",
464     "\n",
465     "print(train_ss)\n",
466     "print(val_ss)"
467    ]
468   },
469   {
470    "cell_type": "code",
471    "execution_count": null,
472    "metadata": {
473     "colab": {
474      "base_uri": "https://localhost:8080/"
475     },
476     "id": "IN6IQykaEzcF",
477     "outputId": "f7877fba-a745-4f3e-f654-c8cdeed5181e"
478    },
479    "outputs": [],
480    "source": [
481     "x_train_ss.shape[-2:]"
482    ]
483   },
484   {
485    "cell_type": "code",
486    "execution_count": null,
487    "metadata": {
488     "id": "9eQpwUyGglu_"
489    },
490    "outputs": [],
491    "source": [
492     "def root_mean_squared_error(y_true, y_pred):\n",
493     "        return K.sqrt(K.mean(K.square(y_pred - y_true))) "
494    ]
495   },
496   {
497    "cell_type": "code",
498    "execution_count": null,
499    "metadata": {
500     "colab": {
501      "base_uri": "https://localhost:8080/"
502     },
503     "id": "1cKtTAzqyiyL",
504     "outputId": "004c1521-5b4c-4304-fa58-76bd01a9dcca"
505    },
506    "outputs": [],
507    "source": [
508     "from keras.layers import Activation, Dense, Dropout\n",
509     "from keras.utils.vis_utils import plot_model\n",
510     "### Modelling using LSTM\n",
511     "steps = 50\n",
512     "\n",
513     "EPOCHS =20\n",
514     "\n",
515     "single_step_model = tf.keras.models.Sequential()\n",
516     "\n",
517     "single_step_model.add(tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32, return_sequences=True, input_shape = x_train_ss.shape[-2:])))\n",
518     "#single_step_model.add(tf.keras.layers.Dropout(0.3))\n",
519     "single_step_model.add(tf.keras.layers.LSTM(units=100,return_sequences=False))\n",
520     "#single_step_model.add(tf.keras.layers.Dropout(0.2))\n",
521     "#model.add(Dense(units=1, activation='relu'))\n",
522     "single_step_model.add(tf.keras.layers.Activation(\"relu\"))\n",
523     "single_step_model.add(tf.keras.layers.Dense(1))\n",
524     "single_step_model.compile(optimizer = tf.keras.optimizers.Adam(), loss = 'mae',metrics=[tf.keras.metrics.RootMeanSquaredError(name='rmse')])\n",
525     "#single_step_model.compile(loss='mse', optimizer='rmsprop')\n",
526     "\n",
527     "single_step_model_history = single_step_model.fit(train_ss, epochs = EPOCHS , \n",
528     "                                                  steps_per_epoch =steps, validation_data = val_ss,\n",
529     "                                                  validation_steps = 50)\n",
530     "\n",
531     "plot_model(single_step_model, to_file='/content/drive/MyDrive/LFN Anuket/Analysis/data/Final/Bi-LSTM.png', show_shapes=True, show_layer_names=True)\n",
532     "single_step_model.summary()\n",
533     "\n"
534    ]
535   },
536   {
537    "cell_type": "code",
538    "execution_count": null,
539    "metadata": {
540     "id": "rePzISUuFmlM"
541    },
542    "outputs": [],
543    "source": []
544   },
545   {
546    "cell_type": "code",
547    "execution_count": null,
548    "metadata": {
549     "colab": {
550      "base_uri": "https://localhost:8080/",
551      "height": 281
552     },
553     "id": "Pgev0dgzzBVx",
554     "outputId": "90d76f79-4228-4f67-ef58-eb0c6f9e9390"
555    },
556    "outputs": [],
557    "source": [
558     "## plot train test loss \n",
559     "\n",
560     "def plot_loss(history , title):\n",
561     "  loss = history.history['loss']\n",
562     "  val_loss = history.history['val_loss']\n",
563     "\n",
564     "  epochs = range(len(loss))\n",
565     "  plt.figure()\n",
566     "  plt.plot(epochs, loss , 'b' , label = 'Train Loss')\n",
567     "  plt.plot(epochs, val_loss , 'r' , label = 'Validation Loss')\n",
568     "  plt.title(title)\n",
569     "  plt.legend()\n",
570     "  plt.grid()\n",
571     "  plt.show()\n",
572     "\n",
573     "plot_loss(single_step_model_history , 'Single Step Training and validation loss')"
574    ]
575   },
576   {
577    "cell_type": "code",
578    "execution_count": null,
579    "metadata": {
580     "colab": {
581      "base_uri": "https://localhost:8080/",
582      "height": 281
583     },
584     "id": "EnYf6j4okEoC",
585     "outputId": "16fab4ff-15d9-424a-a599-6f03e1ad0e8b"
586    },
587    "outputs": [],
588    "source": [
589     "## plot train test loss \n",
590     "\n",
591     "def plot_loss(history , title):\n",
592     "  loss = history.history['rmse']\n",
593     "  val_loss = history.history['val_rmse']\n",
594     "\n",
595     "  epochs = range(len(loss))\n",
596     "  plt.figure()\n",
597     "  plt.plot(epochs, loss , 'b' , label = 'Train RMSE')\n",
598     "  plt.plot(epochs, val_loss , 'r' , label = 'Validation RMSE')\n",
599     "  plt.title(title)\n",
600     "  plt.legend()\n",
601     "  plt.grid()\n",
602     "  plt.show()\n",
603     "\n",
604     "plot_loss(single_step_model_history , 'Single Step Training and validation loss')"
605    ]
606   },
607   {
608    "cell_type": "code",
609    "execution_count": null,
610    "metadata": {
611     "id": "WMegV8mNAwe_"
612    },
613    "outputs": [],
614    "source": [
615     "### fucntion to create time steps\n",
616     "def create_time_steps(length):\n",
617     "  return list(range(-length,0))\n",
618     "\n",
619     "### function to plot time series data\n",
620     "\n",
621     "def plot_time_series(plot_data, delta , title):\n",
622     "  labels = [\"History\" , 'True Future' , 'Model Predcited']\n",
623     "  marker = ['.-' , 'rx' , 'go']\n",
624     "  time_steps = create_time_steps(plot_data[0].shape[0])\n",
625     "\n",
626     "  if delta:\n",
627     "    future = delta\n",
628     "  else:\n",
629     "    future = 0\n",
630     "  plt.title(title)\n",
631     "  for i , x in enumerate(plot_data):\n",
632     "    if i :\n",
633     "      plt.plot(future , plot_data[i] , marker[i], markersize = 10 , label = labels[i])\n",
634     "    else:\n",
635     "      plt.plot(time_steps, plot_data[i].flatten(), marker[i], label = labels[i])\n",
636     "  plt.legend()\n",
637     "  plt.xlim([time_steps[0], (future+5) *2])\n",
638     "\n",
639     "  plt.xlabel('Time_Step')\n",
640     "  return plt"
641    ]
642   },
643   {
644    "cell_type": "code",
645    "execution_count": null,
646    "metadata": {
647     "id": "q99i2c-9XKF3"
648    },
649    "outputs": [],
650    "source": [
651     "### Moving window average\n",
652     "\n",
653     "def MWA(history):\n",
654     "  return np.mean(history)"
655    ]
656   },
657   {
658    "cell_type": "code",
659    "execution_count": null,
660    "metadata": {
661     "colab": {
662      "base_uri": "https://localhost:8080/",
663      "height": 1000
664     },
665     "id": "xFJT1rZDAUVL",
666     "outputId": "d0dc9e7a-bc96-4f19-815f-da9ed8a82408"
667    },
668    "outputs": [],
669    "source": [
670     "# plot time series and predicted values\n",
671     "\n",
672     "for x, y in val_ss.take(5):\n",
673     "  plot = plot_time_series([x[0][:, 1].numpy(), y[0].numpy(),\n",
674     "                    single_step_model.predict(x)[0]], 12,\n",
675     "                   'Single Step Prediction')\n",
676     "  plot.show()"
677    ]
678   },
679   {
680    "cell_type": "markdown",
681    "metadata": {
682     "id": "_KXWQVmyCSix"
683    },
684    "source": [
685     "# **MultiStep Forcasting**"
686    ]
687   },
688   {
689    "cell_type": "code",
690    "execution_count": null,
691    "metadata": {
692     "colab": {
693      "base_uri": "https://localhost:8080/"
694     },
695     "id": "Lu7m2Rr4AbMK",
696     "outputId": "e0d07c10-c644-4a91-8723-5fc94e35c3a5"
697    },
698    "outputs": [],
699    "source": [
700     "future_target = 72 # 72 future values\n",
701     "x_train_multi, y_train_multi = mutlivariate_data(features, features[:, 1], 0,\n",
702     "                                                 train_split, history,\n",
703     "                                                 future_target, STEP)\n",
704     "x_val_multi, y_val_multi = mutlivariate_data(features, features[:, 1],\n",
705     "                                             train_split, None, history,\n",
706     "                                             future_target, STEP)\n",
707     "\n",
708     "print(x_train_multi.shape)\n",
709     "print(y_train_multi.shape)"
710    ]
711   },
712   {
713    "cell_type": "code",
714    "execution_count": null,
715    "metadata": {
716     "id": "GLRv5D16CrHj"
717    },
718    "outputs": [],
719    "source": [
720     "#  TF DATASET\n",
721     "\n",
722     "train_data_multi = tf.data.Dataset.from_tensor_slices((x_train_multi, y_train_multi))\n",
723     "train_data_multi = train_data_multi.cache().shuffle(buffer_size).batch(batch_size).repeat()\n",
724     "\n",
725     "val_data_multi = tf.data.Dataset.from_tensor_slices((x_val_multi, y_val_multi))\n",
726     "val_data_multi = val_data_multi.batch(batch_size).repeat()"
727    ]
728   },
729   {
730    "cell_type": "code",
731    "execution_count": null,
732    "metadata": {
733     "colab": {
734      "base_uri": "https://localhost:8080/"
735     },
736     "id": "fjXexah9C8yg",
737     "outputId": "8e521731-9e70-48b3-b630-44adc32f93fb"
738    },
739    "outputs": [],
740    "source": [
741     "print(train_data_multi)\n",
742     "print(val_data_multi)"
743    ]
744   },
745   {
746    "cell_type": "code",
747    "execution_count": null,
748    "metadata": {
749     "colab": {
750      "base_uri": "https://localhost:8080/",
751      "height": 385
752     },
753     "id": "7mtLZ6S-DPU-",
754     "outputId": "c6ae5f81-b61d-47e6-cd05-f96a5658ae2d"
755    },
756    "outputs": [],
757    "source": [
758     "#plotting function\n",
759     "def multi_step_plot(history, true_future, prediction):\n",
760     "  plt.figure(figsize=(12, 6))\n",
761     "  num_in = create_time_steps(len(history))\n",
762     "  num_out = len(true_future)\n",
763     "  plt.grid()\n",
764     "  plt.plot(num_in, np.array(history[:, 1]), label='History')\n",
765     "  plt.plot(np.arange(num_out)/STEP, np.array(true_future), 'bo',\n",
766     "           label='True Future')\n",
767     "  if prediction.any():\n",
768     "    plt.plot(np.arange(num_out)/STEP, np.array(prediction), 'ro',\n",
769     "             label='Predicted Future')\n",
770     "  plt.legend(loc='upper left')\n",
771     "  plt.show()\n",
772     "  \n",
773     "\n",
774     "\n",
775     "for x, y in train_data_multi.take(1):\n",
776     "  multi_step_plot(x[0], y[0], np.array([0]))"
777    ]
778   },
779   {
780    "cell_type": "markdown",
781    "metadata": {
782     "id": "eaIjVnzCJwCS"
783    },
784    "source": [
785     "Bi-directional LSTM:\n",
786     "On some sequence prediction problems, it can be beneficial to allow the LSTM model to learn the input sequence both forward and backwards and concatenate both interpretations. This is known as bidirectional.\n",
787     "\n",
788     "Here, `tf.keras.layers.Bidirectional` is a bidirectional wrapper for RNNs which inherits from `Wrapper`, `Layer`, and `module`"
789    ]
790   },
791   {
792    "cell_type": "code",
793    "execution_count": null,
794    "metadata": {
795     "colab": {
796      "base_uri": "https://localhost:8080/"
797     },
798     "id": "snN_Flr5DWQN",
799     "outputId": "be27d60a-53b9-4e83-f1e3-45bf9b751196"
800    },
801    "outputs": [],
802    "source": [
803     "multi_step_model = tf.keras.models.Sequential()\n",
804     "multi_step_model.add(tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32,\n",
805     "                                          return_sequences=True,\n",
806     "                                          input_shape=x_train_multi.shape[-2:])))\n",
807     "multi_step_model.add(tf.keras.layers.Dropout(0.2))\n",
808     "multi_step_model.add(tf.keras.layers.LSTM(units=100,return_sequences=False))\n",
809     "multi_step_model.add(tf.keras.layers.Dropout(0.2))\n",
810     "#model.add(Dense(units=1, activation='relu'))\n",
811     "multi_step_model.add(tf.keras.layers.Activation(\"relu\"))\n",
812     "#aDD dropout layer (0.3)\n",
813     "multi_step_model.add(tf.keras.layers.Dense(72)) # for 72 outputs\n",
814     "\n",
815     "multi_step_model.compile(optimizer=tf.keras.optimizers.RMSprop(clipvalue=1.0), loss='mae',metrics=[tf.keras.metrics.RootMeanSquaredError(name='rmse')])\n",
816     "\n",
817     "multi_step_history = multi_step_model.fit(train_data_multi, epochs=EPOCHS,\n",
818     "                                          steps_per_epoch=steps,\n",
819     "                                          validation_data=val_data_multi,\n",
820     "                                          validation_steps=50)"
821    ]
822   },
823   {
824    "cell_type": "code",
825    "execution_count": null,
826    "metadata": {
827     "colab": {
828      "base_uri": "https://localhost:8080/",
829      "height": 281
830     },
831     "id": "Ay5m27doDsTt",
832     "outputId": "74bc7df8-2315-401b-8cd8-d7632c14abb7"
833    },
834    "outputs": [],
835    "source": [
836     "plot_loss(multi_step_history, 'Multi-Step Training and validation loss')"
837    ]
838   },
839   {
840    "cell_type": "code",
841    "execution_count": null,
842    "metadata": {
843     "colab": {
844      "base_uri": "https://localhost:8080/",
845      "height": 1000
846     },
847     "id": "6ZFP49W4D2wp",
848     "outputId": "cdd29cbc-c26e-46d0-aaaf-0d2a8a4cb047"
849    },
850    "outputs": [],
851    "source": [
852     "for x, y in val_data_multi.take(5):\n",
853     "  multi_step_plot(x[0], y[0], multi_step_model.predict(x)[0])"
854    ]
855   },
856   {
857    "cell_type": "code",
858    "execution_count": null,
859    "metadata": {
860     "colab": {
861      "base_uri": "https://localhost:8080/"
862     },
863     "id": "DNKMjVoAVqZP",
864     "outputId": "befefa8a-e8e1-4147-d23f-db668c092471"
865    },
866    "outputs": [],
867    "source": [
868     "scores = multi_step_model.evaluate(x_train_multi, y_train_multi, verbose=1, batch_size=200)\n",
869     "print('MAE: {}'.format(scores[1]))"
870    ]
871   },
872   {
873    "cell_type": "code",
874    "execution_count": null,
875    "metadata": {
876     "id": "YXcsNZ8yu9Ay"
877    },
878    "outputs": [],
879    "source": [
880     "scores_test = multi_step_model.evaluate(x_val_multi, y_val_multi, verbose=1, batch_size=200)\n",
881     "print('MAE: {}'.format(scores[1]))\n"
882    ]
883   },
884   {
885    "cell_type": "code",
886    "execution_count": null,
887    "metadata": {
888     "id": "uCFgbZEOvZ9A"
889    },
890    "outputs": [],
891    "source": [
892     "y_pred_test = multi_step_model.predict(x_val_multi, verbose=0)\n",
893     "\n",
894     "plt.figure(figsize=(10,5))\n",
895     "plt.plot(y_pred_test)\n",
896     "plt.plot(y_val_multi)\n",
897     "plt.ylabel(\"Value\")\n",
898     "plt.xlabel(\"Timestap\")\n",
899     "plt.legend(loc='upper left')\n",
900     "plt.show()"
901    ]
902   }
903  ],
904  "metadata": {
905   "colab": {
906    "collapsed_sections": [],
907    "name": "Bi-LSTMstacked-LSTM_Correlation.ipynb",
908    "provenance": []
909   },
910   "kernelspec": {
911    "display_name": "Python 3 (ipykernel)",
912    "language": "python",
913    "name": "python3"
914   },
915   "language_info": {
916    "codemirror_mode": {
917     "name": "ipython",
918     "version": 3
919    },
920    "file_extension": ".py",
921    "mimetype": "text/x-python",
922    "name": "python",
923    "nbconvert_exporter": "python",
924    "pygments_lexer": "ipython3",
925    "version": "3.9.7"
926   }
927  },
928  "nbformat": 4,
929  "nbformat_minor": 1
930 }