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