Diff of /Logistic Regression.ipynb [000000] .. [505a55]

Switch to unified view

a b/Logistic Regression.ipynb
1
{
2
 "cells": [
3
  {
4
   "cell_type": "markdown",
5
   "metadata": {},
6
   "source": [
7
    "<h1 align=\"center\">Machine learning-based prediction of early recurrence in glioblastoma patients: a glance towards precision medicine <br><br>[Logistic Regression]</h1>"
8
   ]
9
  },
10
  {
11
   "cell_type": "markdown",
12
   "metadata": {},
13
   "source": [
14
    "## [1] Library"
15
   ]
16
  },
17
  {
18
   "cell_type": "code",
19
   "execution_count": null,
20
   "metadata": {},
21
   "outputs": [],
22
   "source": [
23
    "# OS library\n",
24
    "import os\n",
25
    "import sys\n",
26
    "import argparse\n",
27
    "\n",
28
    "# Analysis\n",
29
    "import numpy as np\n",
30
    "import pandas as pd\n",
31
    "import seaborn as sns\n",
32
    "import matplotlib.pyplot as plt\n",
33
    "\n",
34
    "# Sklearn\n",
35
    "from boruta import BorutaPy\n",
36
    "from sklearn.preprocessing import LabelEncoder\n",
37
    "from sklearn.model_selection import train_test_split\n",
38
    "from sklearn.metrics import confusion_matrix, f1_score, recall_score, classification_report, accuracy_score, auc, roc_curve\n",
39
    "from sklearn.model_selection import GridSearchCV\n",
40
    "from sklearn.linear_model import LogisticRegression\n",
41
    "\n",
42
    "import scikitplot as skplt\n",
43
    "from imblearn.over_sampling import RandomOverSampler, SMOTENC, SMOTE"
44
   ]
45
  },
46
  {
47
   "cell_type": "markdown",
48
   "metadata": {},
49
   "source": [
50
    "## [2] Data Preprocessing"
51
   ]
52
  },
53
  {
54
   "cell_type": "markdown",
55
   "metadata": {},
56
   "source": [
57
    "<h4>[-] Load the database</h4>"
58
   ]
59
  },
60
  {
61
   "cell_type": "code",
62
   "execution_count": null,
63
   "metadata": {},
64
   "outputs": [],
65
   "source": [
66
    "file = os.path.join(sys.path[0], \"db.xlsx\")\n",
67
    "db = pd.read_excel(file)\n",
68
    "\n",
69
    "print(\"N° of patients: {}\".format(len(db)))\n",
70
    "print(\"N° of columns: {}\".format(db.shape[1]))\n",
71
    "db.head()"
72
   ]
73
  },
74
  {
75
   "cell_type": "markdown",
76
   "metadata": {},
77
   "source": [
78
    "<h4>[-] Drop unwanted columns + create <i>'results'</i> column</h4>"
79
   ]
80
  },
81
  {
82
   "cell_type": "code",
83
   "execution_count": null,
84
   "metadata": {},
85
   "outputs": [],
86
   "source": [
87
    "df = db.drop(['Name_Surname', '...'], axis = 'columns')\n",
88
    "\n",
89
    "print(\"Effective features to consider: {} \".format(len(df.columns)-1))\n",
90
    "print(\"Creating 'result' column...\")\n",
91
    "\n",
92
    "# 0 = No relapse\n",
93
    "df.loc[df['PFS'] > 6, 'result'] = 0\n",
94
    "\n",
95
    "# 1 = Early relapse (within 6 months)\n",
96
    "df.loc[df['PFS'] <= 6, 'result'] = 1\n",
97
    "\n",
98
    "df.head()"
99
   ]
100
  },
101
  {
102
   "cell_type": "markdown",
103
   "metadata": {},
104
   "source": [
105
    "<h4>[-] Label encoding of the categorical variables </h4>"
106
   ]
107
  },
108
  {
109
   "cell_type": "code",
110
   "execution_count": null,
111
   "metadata": {},
112
   "outputs": [],
113
   "source": [
114
    "df['sex'] =df['sex'].astype('category')\n",
115
    "df['ceus'] =df['ceus'].astype('category')\n",
116
    "df['ala'] =df['ala'].astype('category')\n",
117
    "\n",
118
    "#df['Ki67'] =df['Ki67'].astype(int)\n",
119
    "df['MGMT'] =df['MGMT'].astype('category')\n",
120
    "df['IDH1'] =df['IDH1'].astype('category')\n",
121
    "\n",
122
    "df['side'] =df['side'].astype('category')\n",
123
    "df['ependima'] =df['ependima'].astype('category')\n",
124
    "df['cc'] =df['cc'].astype('category')\n",
125
    "df['necrotico_cistico'] =df['necrotico_cistico'].astype('category')\n",
126
    "df['shift'] =df['shift'].astype('category')\n",
127
    "\n",
128
    "## VARIABLE TO ONE-HOT-ENCODE\n",
129
    "df['localization'] =df['localization'].astype(int)\n",
130
    "df['clinica_esordio'] =df['clinica_esordio'].astype(int)\n",
131
    "df['immediate_p_o'] =df['immediate_p_o'].astype(int)\n",
132
    "df['onco_Protocol'] =df['onco_Protocol'].astype(int)\n",
133
    "\n",
134
    "df['result'] =df['result'].astype(int)\n",
135
    "\n",
136
    "dummy_v = ['localization', 'clinica_esordio', 'onco_Protocol', 'immediate_p_o']\n",
137
    "\n",
138
    "df = pd.get_dummies(df, columns = dummy_v, prefix = dummy_v)"
139
   ]
140
  },
141
  {
142
   "cell_type": "markdown",
143
   "metadata": {},
144
   "source": [
145
    "## [3] Prediction Models"
146
   ]
147
  },
148
  {
149
   "cell_type": "markdown",
150
   "metadata": {},
151
   "source": [
152
    "<h4> [-] Training and testing set splitting</h4>"
153
   ]
154
  },
155
  {
156
   "cell_type": "code",
157
   "execution_count": null,
158
   "metadata": {},
159
   "outputs": [],
160
   "source": [
161
    "target = df['result']\n",
162
    "inputs = df.drop(['result', 'PFS'], axis = 'columns')"
163
   ]
164
  },
165
  {
166
   "cell_type": "markdown",
167
   "metadata": {},
168
   "source": [
169
    "Select columns (variable) at a univariate analysis ad a p-value lower than 0.05"
170
   ]
171
  },
172
  {
173
   "cell_type": "code",
174
   "execution_count": null,
175
   "metadata": {},
176
   "outputs": [],
177
   "source": [
178
    "cols = ['age', 'EOR', \n",
179
    "        'onco_Protocol_0','onco_Protocol_1', 'onco_Protocol_2', \n",
180
    "        'onco_Protocol_3', 'onco_Protocol_5', 'MGMT', \n",
181
    "        'IDH1', 'edema volume', 'residual_tumor', \n",
182
    "        'KPS_preop', 'KPS_postop']\n",
183
    "\n",
184
    "\n",
185
    "x_train, x_test, y_train, y_test = train_test_split(inputs[cols],target,test_size=0.20, random_state=42)"
186
   ]
187
  },
188
  {
189
   "cell_type": "markdown",
190
   "metadata": {},
191
   "source": [
192
    "<h4> [-] SMOTE-NC</h4>"
193
   ]
194
  },
195
  {
196
   "cell_type": "code",
197
   "execution_count": null,
198
   "metadata": {},
199
   "outputs": [],
200
   "source": [
201
    "os = SMOTENC(categorical_features=[2,3,4,5,6,7,8], k_neighbors=4, random_state= 42)\n",
202
    "smote_x,smote_y= os.fit_sample(x_train, y_train)"
203
   ]
204
  },
205
  {
206
   "cell_type": "markdown",
207
   "metadata": {},
208
   "source": [
209
    "<h4> [-] Grid Search Hyperparameter tuning</h4>"
210
   ]
211
  },
212
  {
213
   "cell_type": "code",
214
   "execution_count": null,
215
   "metadata": {
216
    "scrolled": true
217
   },
218
   "outputs": [],
219
   "source": [
220
    "random_grid = [{'penalty' : ['l1', 'l2', 'elasticnet', 'none'],\n",
221
    "               'C': [0.001, 0.01, 0.1, 1, 10, 100, 1000]}]\n",
222
    "\n",
223
    "# First create the base model to tune\n",
224
    "lg = LogisticRegression(random_state=42)\n",
225
    "\n",
226
    "# Random search of parameters, using 5 fold cross validation, different combinations, and use all available cores\n",
227
    "lg_random = GridSearchCV(estimator = lg, param_grid=random_grid,\n",
228
    "                               cv = 5)\n",
229
    "# Fit the random search model\n",
230
    "lg_random.fit(x_train, y_train)\n",
231
    "lg_random.best_params_"
232
   ]
233
  },
234
  {
235
   "cell_type": "markdown",
236
   "metadata": {},
237
   "source": [
238
    "<h4> [-] Logistic Regression</h4>"
239
   ]
240
  },
241
  {
242
   "cell_type": "code",
243
   "execution_count": null,
244
   "metadata": {},
245
   "outputs": [],
246
   "source": [
247
    "log_pfs = LogisticRegression(random_state=42, penalty='l2', C=10)\n",
248
    "log_pfs.fit(smote_x, smote_y)\n",
249
    "\n",
250
    "score_log = log_pfs.score(x_test, y_test)\n",
251
    "print(\"### TESTING ###\")\n",
252
    "print(\"Logistic Regression's accuracy: \", round(score_log*100,2), \"% \\n\")\n",
253
    "\n",
254
    "y_pred = log_pfs.predict(x_test)\n",
255
    "y_proba = log_pfs.predict_proba(x_test)\n",
256
    "cm_log = confusion_matrix(y_test, y_pred)\n",
257
    "print(cm_log, \"\\n\")\n",
258
    "\n",
259
    "false_positive_rate, true_positive_rate, thresholds = roc_curve(y_test, y_pred)\n",
260
    "roc_auc = auc(false_positive_rate, true_positive_rate)\n",
261
    "\n",
262
    "\n",
263
    "print('1. The F-1 Score of the model {} \\n '.format(round(f1_score(y_test, y_pred, average = 'macro'), 2)))\n",
264
    "print('2. The Recall Score of the model {} \\n '.format(round(recall_score(y_test, y_pred, average = 'macro'), 2)))\n",
265
    "print('3. Classification report \\n {}'.format(classification_report(y_test, y_pred)))\n",
266
    "print('3. AUC: \\n {} \\n'.format(roc_auc))\n",
267
    "\n",
268
    "tn, fp, fn, tp = cm_log.ravel()\n",
269
    "\n",
270
    "# Sensitivity, hit rate, Recall, or true positive rate\n",
271
    "tpr = tp/(tp+fn)\n",
272
    "print(\"Sensitivity (TPR): {}\".format(tpr))\n",
273
    "\n",
274
    "# Specificity or true negative rate\n",
275
    "tnr = tn/(tn+fp)\n",
276
    "print(\"Specificity (TNR): {}\".format(tnr))\n",
277
    "\n",
278
    "# Precision or positive predictive value\n",
279
    "ppv = tp/(tp+fp)\n",
280
    "print(\"Precision (PPV): {}\".format(ppv))\n",
281
    "\n",
282
    "# Negative predictive value\n",
283
    "npv = tn/(tn+fn)\n",
284
    "print(\"Negative Predictive Value (NPV): {}\".format(npv))\n",
285
    "\n",
286
    "# False positive rate\n",
287
    "fpr = fp / (fp + tn)\n",
288
    "print(\"False Positive Rate (FPV): {}\".format(fpr))"
289
   ]
290
  },
291
  {
292
   "cell_type": "code",
293
   "execution_count": null,
294
   "metadata": {},
295
   "outputs": [],
296
   "source": []
297
  },
298
  {
299
   "cell_type": "code",
300
   "execution_count": null,
301
   "metadata": {},
302
   "outputs": [],
303
   "source": []
304
  },
305
  {
306
   "cell_type": "code",
307
   "execution_count": null,
308
   "metadata": {},
309
   "outputs": [],
310
   "source": []
311
  },
312
  {
313
   "cell_type": "code",
314
   "execution_count": null,
315
   "metadata": {},
316
   "outputs": [],
317
   "source": []
318
  }
319
 ],
320
 "metadata": {
321
  "kernelspec": {
322
   "display_name": "Python 3",
323
   "language": "python",
324
   "name": "python3"
325
  },
326
  "language_info": {
327
   "codemirror_mode": {
328
    "name": "ipython",
329
    "version": 3
330
   },
331
   "file_extension": ".py",
332
   "mimetype": "text/x-python",
333
   "name": "python",
334
   "nbconvert_exporter": "python",
335
   "pygments_lexer": "ipython3",
336
   "version": "3.7.4"
337
  }
338
 },
339
 "nbformat": 4,
340
 "nbformat_minor": 2
341
}