Merge "[TOOL] Model Selector update."
[thoth.git] / models / failure_prediction / jnotebooks / Decision_Tree.ipynb
1 {
2  "cells": [
3   {
4    "cell_type": "markdown",
5    "metadata": {
6     "id": "FxPrqgIEVsdg"
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": "markdown",
28    "metadata": {
29     "id": "sV1Drb9ccUFw"
30    },
31    "source": [
32     "We mounted the drive to access the data"
33    ]
34   },
35   {
36    "cell_type": "code",
37    "execution_count": null,
38    "metadata": {
39     "colab": {
40      "base_uri": "https://localhost:8080/"
41     },
42     "id": "YQ6lT1e2hrx4",
43     "outputId": "df8b6b61-66a0-4bca-9ec5-c21216f5b46d"
44    },
45    "outputs": [],
46    "source": [
47     "from google.colab import drive\n",
48     "drive.mount('/content/drive')"
49    ]
50   },
51   {
52    "cell_type": "markdown",
53    "metadata": {
54     "id": "yhhkDCI7cc43"
55    },
56    "source": [
57     "We are importing libraries to read the CSV and to train the models"
58    ]
59   },
60   {
61    "cell_type": "code",
62    "execution_count": null,
63    "metadata": {
64     "id": "tLhroy5BnMnC"
65    },
66    "outputs": [],
67    "source": [
68     "# Importing libraries\n",
69     "import tensorflow as tf\n",
70     "import matplotlib.pyplot as plt\n",
71     "import matplotlib as mpl\n",
72     "import pandas as pd\n",
73     "import numpy as np\n",
74     "import os"
75    ]
76   },
77   {
78    "cell_type": "markdown",
79    "metadata": {
80     "id": "9wFIhTogcl4z"
81    },
82    "source": [
83     "We are reading CSV file using `read_csv` function and dropping the `Timestamp` column and storing it in a DataFrame called `df_Ellis`."
84    ]
85   },
86   {
87    "cell_type": "code",
88    "execution_count": null,
89    "metadata": {
90     "colab": {
91      "base_uri": "https://localhost:8080/",
92      "height": 419
93     },
94     "id": "2-UpMVsSnfCI",
95     "outputId": "38b85609-e8c4-493f-ee6d-43d1b627db7f"
96    },
97    "outputs": [],
98    "source": [
99     "df_Ellis  = pd.read_csv(\"/content/drive/MyDrive/Failure/lstm/Ellis_FinalTwoConditionwithOR.csv\")\n",
100     "df_Ellis=df_Ellis.drop(columns='Timestamp')\n",
101     "df_Ellis"
102    ]
103   },
104   {
105    "cell_type": "markdown",
106    "metadata": {
107     "id": "o9SAQoIodC1V"
108    },
109    "source": [
110     "First we stored the `feature_cols` and defined the `X` matrix and `y` vector where `X` is a matrix and containing all the feature matrix and `y` is a vector which is having target value."
111    ]
112   },
113   {
114    "cell_type": "code",
115    "execution_count": null,
116    "metadata": {
117     "id": "27TqMF9VNQgh"
118    },
119    "outputs": [],
120    "source": [
121     "\n",
122     "# define X and y\n",
123     "feature_cols = ['ellis-cpu.wait_perc',\t'ellis-load.avg_1_min',\t'ellis-net.in_bytes_sec','ellis-cpu.system_perc','ellis-mem.free_mb']\n",
124     "\n",
125     "# X is a matrix, hence we use [] to access the features we want in feature_cols\n",
126     "X = df_Ellis[feature_cols]\n",
127     "\n",
128     "# y is a vector, hence we use dot to access 'label'\n",
129     "y = df_Ellis.Label"
130    ]
131   },
132   {
133    "cell_type": "markdown",
134    "metadata": {
135     "id": "lBGYYW2Fdsra"
136    },
137    "source": [
138     "We splitted `X` and `y` into `X_train`, `X_test`, `y_train`, and `y_test` using `train_test_split` function."
139    ]
140   },
141   {
142    "cell_type": "code",
143    "execution_count": null,
144    "metadata": {
145     "id": "6YiG55Z8NqJR"
146    },
147    "outputs": [],
148    "source": [
149     "# split X and y into training and testing sets\n",
150     "from sklearn.model_selection import train_test_split\n",
151     "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=5)"
152    ]
153   },
154   {
155    "cell_type": "markdown",
156    "metadata": {
157     "id": "UfHBs8eweLT_"
158    },
159    "source": [
160     "We are training the model with Decision Tree."
161    ]
162   },
163   {
164    "cell_type": "code",
165    "execution_count": null,
166    "metadata": {
167     "colab": {
168      "base_uri": "https://localhost:8080/"
169     },
170     "id": "r1LWPgeBNvMA",
171     "outputId": "3fb01e3e-9d22-4547-b5ec-355821675af6"
172    },
173    "outputs": [],
174    "source": [
175     "# train a logistic regression model on the training set\n",
176     "from sklearn.linear_model import LogisticRegression\n",
177     "from sklearn import tree\n",
178     "\n",
179     "# instantiate model\n",
180     "logreg=tree.DecisionTreeClassifier()\n",
181     "\n",
182     "# fit model\n",
183     "logreg.fit(X_train, y_train)"
184    ]
185   },
186   {
187    "cell_type": "markdown",
188    "metadata": {
189     "id": "koopvyUxe1BR"
190    },
191    "source": [
192     "We are making predictions for test set"
193    ]
194   },
195   {
196    "cell_type": "code",
197    "execution_count": null,
198    "metadata": {
199     "id": "YNrCzlWVODRZ"
200    },
201    "outputs": [],
202    "source": [
203     "# make class predictions for the testing set\n",
204     "y_pred_class = logreg.predict(X_test)"
205    ]
206   },
207   {
208    "cell_type": "markdown",
209    "metadata": {
210     "id": "61cWU-hAejuK"
211    },
212    "source": []
213   },
214   {
215    "cell_type": "markdown",
216    "metadata": {
217     "id": "r9XsgzK6e8Sj"
218    },
219    "source": [
220     "Here, we are calculating the accuracy using `sklearn` library"
221    ]
222   },
223   {
224    "cell_type": "code",
225    "execution_count": null,
226    "metadata": {
227     "colab": {
228      "base_uri": "https://localhost:8080/"
229     },
230     "id": "nrmeurYhOF9A",
231     "outputId": "af9f0179-2e24-4b85-e702-09f8cf5dd176"
232    },
233    "outputs": [],
234    "source": [
235     "# calculate accuracy\n",
236     "from sklearn import metrics\n",
237     "print(metrics.accuracy_score(y_test, y_pred_class))"
238    ]
239   },
240   {
241    "cell_type": "markdown",
242    "metadata": {
243     "id": "We67ligTfEyz"
244    },
245    "source": [
246     "We are examining the class distribution of the testing set using a `pandas` series method"
247    ]
248   },
249   {
250    "cell_type": "code",
251    "execution_count": null,
252    "metadata": {
253     "colab": {
254      "base_uri": "https://localhost:8080/"
255     },
256     "id": "zdWWQ7p9OLuA",
257     "outputId": "d30b7eed-a72b-42dc-946b-6ce13f9d46e1"
258    },
259    "outputs": [],
260    "source": [
261     "# examine the class distribution of the testing set (using a Pandas Series method)\n",
262     "y_test.value_counts()"
263    ]
264   },
265   {
266    "cell_type": "markdown",
267    "metadata": {
268     "id": "2mHqdHaOfPHh"
269    },
270    "source": [
271     "We counted the value for each lables"
272    ]
273   },
274   {
275    "cell_type": "code",
276    "execution_count": null,
277    "metadata": {
278     "colab": {
279      "base_uri": "https://localhost:8080/"
280     },
281     "id": "5y6mGyYwOQf4",
282     "outputId": "d8aaf9cc-eb8a-417e-8804-4613e034e8a1"
283    },
284    "outputs": [],
285    "source": [
286     "y_train.value_counts()"
287    ]
288   },
289   {
290    "cell_type": "markdown",
291    "metadata": {
292     "id": "gHYoAXK3fUNr"
293    },
294    "source": [
295     "We are calculating the percentage of ones because `y_test` only contains ones and zeroes, we can simply calculate the mean = percentage of ones"
296    ]
297   },
298   {
299    "cell_type": "code",
300    "execution_count": null,
301    "metadata": {
302     "colab": {
303      "base_uri": "https://localhost:8080/"
304     },
305     "id": "bGLlh0lVOVMp",
306     "outputId": "f389d7cb-bf0b-4cf5-8b5b-6bf962c68717"
307    },
308    "outputs": [],
309    "source": [
310     "# calculate the percentage of ones\n",
311     "# because y_test only contains ones and zeros, we can simply calculate the mean = percentage of ones\n",
312     "y_test.mean()"
313    ]
314   },
315   {
316    "cell_type": "markdown",
317    "metadata": {
318     "id": "vjerEaxJfhAw"
319    },
320    "source": [
321     "We are calculating the percentage of zeros"
322    ]
323   },
324   {
325    "cell_type": "code",
326    "execution_count": null,
327    "metadata": {
328     "colab": {
329      "base_uri": "https://localhost:8080/"
330     },
331     "id": "GbU1cj6OOcGq",
332     "outputId": "8d1936a2-35c3-4813-be8f-9873c680f59f"
333    },
334    "outputs": [],
335    "source": [
336     "# calculate the percentage of zeros\n",
337     "1 - y_test.mean()"
338    ]
339   },
340   {
341    "cell_type": "code",
342    "execution_count": null,
343    "metadata": {
344     "colab": {
345      "base_uri": "https://localhost:8080/"
346     },
347     "id": "t8w_x6f4OgCL",
348     "outputId": "23b3fc85-aa56-4060-922d-cdb04dcbf75e"
349    },
350    "outputs": [],
351    "source": [
352     "# calculate null accuracy in a single line of code\n",
353     "# only for binary classification problems coded as 0/1\n",
354     "max(y_test.mean(), 1 - y_test.mean())"
355    ]
356   },
357   {
358    "cell_type": "code",
359    "execution_count": null,
360    "metadata": {
361     "colab": {
362      "base_uri": "https://localhost:8080/"
363     },
364     "id": "iEsa9XIwOkX5",
365     "outputId": "9f890113-031a-48ef-f497-644550336b88"
366    },
367    "outputs": [],
368    "source": [
369     "# calculate null accuracy (for multi-class classification problems)\n",
370     "y_test.value_counts().head(1) / len(y_test)"
371    ]
372   },
373   {
374    "cell_type": "code",
375    "execution_count": null,
376    "metadata": {
377     "colab": {
378      "base_uri": "https://localhost:8080/"
379     },
380     "id": "uYAoMBHPOqPB",
381     "outputId": "58da15d1-50c6-42cb-d09c-3f719e333b79"
382    },
383    "outputs": [],
384    "source": [
385     "\n",
386     "# print the first 25 true and predicted responses\n",
387     "print('True:', y_test.values[0:50])\n",
388     "print('False:', y_pred_class[0:50])"
389    ]
390   },
391   {
392    "cell_type": "code",
393    "execution_count": null,
394    "metadata": {
395     "colab": {
396      "base_uri": "https://localhost:8080/"
397     },
398     "id": "puC1RxKmOw8C",
399     "outputId": "30df8b66-f7dc-4cb4-c869-179e2630c240"
400    },
401    "outputs": [],
402    "source": [
403     "# IMPORTANT: first argument is true values, second argument is predicted values\n",
404     "# this produces a 2x2 numpy array (matrix)\n",
405     "print(metrics.confusion_matrix(y_test, y_pred_class))"
406    ]
407   },
408   {
409    "cell_type": "code",
410    "execution_count": null,
411    "metadata": {
412     "colab": {
413      "base_uri": "https://localhost:8080/"
414     },
415     "id": "eXqJUVOlPA_z",
416     "outputId": "bbfb9a96-d2fc-4726-e4af-d87fcd9ef7ee"
417    },
418    "outputs": [],
419    "source": [
420     "# save confusion matrix and slice into four pieces\n",
421     "confusion = metrics.confusion_matrix(y_test, y_pred_class)\n",
422     "print(confusion)\n",
423     "#[row, column]\n",
424     "TP = confusion[1, 1]\n",
425     "TN = confusion[0, 0]\n",
426     "FP = confusion[0, 1]\n",
427     "FN = confusion[1, 0]"
428    ]
429   },
430   {
431    "cell_type": "code",
432    "execution_count": null,
433    "metadata": {
434     "colab": {
435      "base_uri": "https://localhost:8080/"
436     },
437     "id": "klBfDQSgPG4C",
438     "outputId": "9928f546-6f0b-4aa9-e647-6a0c0487f798"
439    },
440    "outputs": [],
441    "source": [
442     "\n",
443     "# use float to perform true division, not integer division\n",
444     "print((TP + TN) / float(TP + TN + FP + FN))\n",
445     "print(metrics.accuracy_score(y_test, y_pred_class))"
446    ]
447   },
448   {
449    "cell_type": "markdown",
450    "metadata": {
451     "id": "aeoA5XY_fyfU"
452    },
453    "source": [
454     "We are defining a function `print_results` to print the result of `y_test` and `y_pred`."
455    ]
456   },
457   {
458    "cell_type": "code",
459    "execution_count": null,
460    "metadata": {
461     "id": "D8GDuytFHL0o"
462    },
463    "outputs": [],
464    "source": [
465     "def print_results(y_test, y_pred):\n",
466     "    \n",
467     "    #f1-score\n",
468     "    f1 = metrics.f1_score(y_test, y_pred)\n",
469     "    print(\"F1 Score: \", f1)\n",
470     "    print(classification_report(y_test, y_pred))\n",
471     "    \n",
472     "    conf_matrix = metrics.confusion_matrix(y_test, y_pred)\n",
473     "    plt.figure(figsize=(12,12))\n",
474     "    plt.subplot(221)\n",
475     "    sns.heatmap(conf_matrix, fmt = \"d\",annot=True, cmap='Blues')\n",
476     "    b, t = plt.ylim()\n",
477     "    plt.ylim(b + 0.5, t - 0.5)\n",
478     "    plt.title('Confuion Matrix')\n",
479     "    plt.ylabel('True Values')\n",
480     "    plt.xlabel('Predicted Values')\n",
481     "\n",
482     "    #roc_auc_score\n",
483     "    model_roc_auc = metrics.roc_auc_score(y_test, y_pred) \n",
484     "    print (\"Area under curve : \",model_roc_auc,\"\\n\")\n",
485     "    fpr,tpr,thresholds = metrics.roc_curve(y_test, y_pred)\n",
486     "    gmeans = np.sqrt(tpr * (1-fpr))\n",
487     "    ix = np.argmax(gmeans)\n",
488     "    threshold = np.round(thresholds[ix],3)\n",
489     "\n",
490     "    plt.subplot(222)\n",
491     "    plt.plot(fpr, tpr, color='darkorange', lw=1, label = \"Auc : %.3f\" %model_roc_auc)\n",
492     "    plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')\n",
493     "    plt.scatter(fpr[ix], tpr[ix], marker='o', color='black', label='Best Threshold:' + str(threshold))\n",
494     "    plt.xlim([0.0, 1.0])\n",
495     "    plt.ylim([0.0, 1.05])\n",
496     "    plt.xlabel('False Positive Rate')\n",
497     "    plt.ylabel('True Positive Rate')\n",
498     "    plt.title('Receiver operating characteristic')\n",
499     "    plt.legend(loc=\"lower right\")"
500    ]
501   },
502   {
503    "cell_type": "code",
504    "execution_count": null,
505    "metadata": {
506     "colab": {
507      "base_uri": "https://localhost:8080/",
508      "height": 578
509     },
510     "id": "X2tMErOPHQZQ",
511     "outputId": "f6e44631-e5fe-4423-9cae-b6bed5c7a874"
512    },
513    "outputs": [],
514    "source": [
515     "import sklearn.metrics as metrics\n",
516     "import seaborn as sns\n",
517     "\n",
518     "from sklearn.metrics import classification_report\n",
519     "print_results(y_test, y_pred_class)"
520    ]
521   }
522  ],
523  "metadata": {
524   "colab": {
525    "collapsed_sections": [],
526    "name": "Decision_Tree.ipynb",
527    "provenance": []
528   },
529   "kernelspec": {
530    "display_name": "Python 3 (ipykernel)",
531    "language": "python",
532    "name": "python3"
533   },
534   "language_info": {
535    "codemirror_mode": {
536     "name": "ipython",
537     "version": 3
538    },
539    "file_extension": ".py",
540    "mimetype": "text/x-python",
541    "name": "python",
542    "nbconvert_exporter": "python",
543    "pygments_lexer": "ipython3",
544    "version": "3.9.7"
545   }
546  },
547  "nbformat": 4,
548  "nbformat_minor": 1
549 }