erjonb commited on
Commit
639981e
·
1 Parent(s): cdf635e

Delete P2 - Secom Notebook - Mercury.ipynb

Browse files
Files changed (1) hide show
  1. P2 - Secom Notebook - Mercury.ipynb +0 -1553
P2 - Secom Notebook - Mercury.ipynb DELETED
@@ -1,1553 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "attachments": {},
5
- "cell_type": "markdown",
6
- "metadata": {
7
- "slideshow": {
8
- "slide_type": "skip"
9
- }
10
- },
11
- "source": [
12
- "# **Classifying products in Semiconductor Industry**"
13
- ]
14
- },
15
- {
16
- "attachments": {},
17
- "cell_type": "markdown",
18
- "metadata": {
19
- "slideshow": {
20
- "slide_type": "skip"
21
- }
22
- },
23
- "source": [
24
- "#### **Import the data**"
25
- ]
26
- },
27
- {
28
- "cell_type": "code",
29
- "execution_count": 18,
30
- "metadata": {
31
- "slideshow": {
32
- "slide_type": "skip"
33
- }
34
- },
35
- "outputs": [],
36
- "source": [
37
- "# import pandas for data manipulation\n",
38
- "# import numpy for numerical computation\n",
39
- "# import seaborn for data visualization\n",
40
- "# import matplotlib for data visualization\n",
41
- "# import stats for statistical analysis\n",
42
- "# import train_test_split for splitting data into training and testing sets\n",
43
- "\n",
44
- "\n",
45
- "import pandas as pd\n",
46
- "import numpy as np\n",
47
- "import seaborn as sns\n",
48
- "import matplotlib.pyplot as plt\n",
49
- "from sklearn.model_selection import train_test_split\n",
50
- "import mercury as mr"
51
- ]
52
- },
53
- {
54
- "cell_type": "code",
55
- "execution_count": 19,
56
- "metadata": {
57
- "slideshow": {
58
- "slide_type": "skip"
59
- }
60
- },
61
- "outputs": [
62
- {
63
- "data": {
64
- "application/mercury+json": {
65
- "allow_download": true,
66
- "code_uid": "App.0.40.24.1-rand2c9ab9e7",
67
- "continuous_update": false,
68
- "description": "Recumpute everything dynamically",
69
- "full_screen": true,
70
- "model_id": "mercury-app",
71
- "notify": "{}",
72
- "output": "app",
73
- "schedule": "",
74
- "show_code": false,
75
- "show_prompt": false,
76
- "show_sidebar": true,
77
- "static_notebook": false,
78
- "title": "Secom Web App Demo",
79
- "widget": "App"
80
- },
81
- "text/html": [
82
- "<h3>Mercury Application</h3><small>This output won't appear in the web app.</small>"
83
- ],
84
- "text/plain": [
85
- "mercury.App"
86
- ]
87
- },
88
- "metadata": {},
89
- "output_type": "display_data"
90
- }
91
- ],
92
- "source": [
93
- "app = mr.App(title=\"Secom Web App Demo\", description=\"Recumpute everything dynamically\", continuous_update=False)"
94
- ]
95
- },
96
- {
97
- "cell_type": "code",
98
- "execution_count": 20,
99
- "metadata": {
100
- "slideshow": {
101
- "slide_type": "skip"
102
- }
103
- },
104
- "outputs": [],
105
- "source": [
106
- " \n",
107
- "# Read the features data from the the url of csv into pandas dataframes and rename the columns to F1, F2, F3, etc.\n",
108
- "# Read the labels data from the url of csv into pandas dataframes and rename the columns to pass/fail and date/time\n",
109
- "\n",
110
- "#url_data = 'https://archive.ics.uci.edu/ml/machine-learning-databases/secom/secom.data'\n",
111
- "#url_labels = 'https://archive.ics.uci.edu/ml/machine-learning-databases/secom/secom_labels.data'\n",
112
- "\n",
113
- "url_data = 'secom_data.csv'\n",
114
- "url_labels = 'secom_labels.csv'\n",
115
- "\n",
116
- "features = pd.read_csv(url_data, delimiter=' ', header=None)\n",
117
- "labels = pd.read_csv(url_labels, delimiter=' ', names=['pass/fail', 'date_time'])\n",
118
- "\n",
119
- "prefix = 'F'\n",
120
- "new_column_names = [prefix + str(i) for i in range(1, len(features.columns)+1)]\n",
121
- "features.columns = new_column_names\n",
122
- "\n",
123
- "labels['pass/fail'] = labels['pass/fail'].replace({-1: 0, 1: 1})\n"
124
- ]
125
- },
126
- {
127
- "attachments": {},
128
- "cell_type": "markdown",
129
- "metadata": {
130
- "slideshow": {
131
- "slide_type": "skip"
132
- }
133
- },
134
- "source": [
135
- "#### **Split the data**"
136
- ]
137
- },
138
- {
139
- "cell_type": "code",
140
- "execution_count": 21,
141
- "metadata": {
142
- "slideshow": {
143
- "slide_type": "skip"
144
- }
145
- },
146
- "outputs": [
147
- {
148
- "name": "stdout",
149
- "output_type": "stream",
150
- "text": [
151
- "Dropped date/time column from labels dataframe\n"
152
- ]
153
- }
154
- ],
155
- "source": [
156
- "# if there is a date/time column, drop it from the features and labels dataframes, else continue\n",
157
- "\n",
158
- "if 'date_time' in labels.columns:\n",
159
- " labels = labels.drop(['date_time'], axis=1)\n",
160
- " print('Dropped date/time column from labels dataframe')\n",
161
- "\n",
162
- "\n",
163
- "# Split the dataset and the labels into training and testing sets\n",
164
- "# use stratify to ensure that the training and testing sets have the same percentage of pass and fail labels\n",
165
- "# use random_state to ensure that the same random split is generated each time the code is run\n",
166
- "\n",
167
- "\n",
168
- "X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.25, stratify=labels, random_state=13)"
169
- ]
170
- },
171
- {
172
- "attachments": {},
173
- "cell_type": "markdown",
174
- "metadata": {
175
- "slideshow": {
176
- "slide_type": "skip"
177
- }
178
- },
179
- "source": [
180
- "### **Functions**"
181
- ]
182
- },
183
- {
184
- "attachments": {},
185
- "cell_type": "markdown",
186
- "metadata": {
187
- "slideshow": {
188
- "slide_type": "skip"
189
- }
190
- },
191
- "source": [
192
- "#### **Feature Removal**"
193
- ]
194
- },
195
- {
196
- "cell_type": "code",
197
- "execution_count": 22,
198
- "metadata": {
199
- "slideshow": {
200
- "slide_type": "skip"
201
- }
202
- },
203
- "outputs": [],
204
- "source": [
205
- "def columns_to_drop(df,drop_duplicates='yes', missing_values_threshold=100, variance_threshold=0, \n",
206
- " correlation_threshold=1.1):\n",
207
- " \n",
208
- " print('Shape of the dataframe is: ', df.shape)\n",
209
- "\n",
210
- " # Drop duplicated columns\n",
211
- " if drop_duplicates == 'yes':\n",
212
- " new_column_names = df.columns\n",
213
- " df = df.T.drop_duplicates().T\n",
214
- " print('the number of columns to be dropped due to duplications is: ', len(new_column_names) - len(df.columns))\n",
215
- " drop_duplicated = list(set(new_column_names) - set(df.columns))\n",
216
- "\n",
217
- " elif drop_duplicates == 'no':\n",
218
- " df = df.T.T\n",
219
- " print('No columns were dropped due to duplications') \n",
220
- "\n",
221
- " # Print the percentage of columns in df with missing values more than or equal to threshold\n",
222
- " print('the number of columns to be dropped due to missing values is: ', len(df.isnull().mean()[df.isnull().mean() > missing_values_threshold/100].index))\n",
223
- " \n",
224
- " # Print into a list the columns to be dropped due to missing values\n",
225
- " drop_missing = list(df.isnull().mean()[df.isnull().mean() > missing_values_threshold/100].index)\n",
226
- "\n",
227
- " # Drop columns with more than or equal to threshold missing values from df\n",
228
- " df.drop(drop_missing, axis=1, inplace=True)\n",
229
- " \n",
230
- " # Print the number of columns in df with variance less than threshold\n",
231
- " print('the number of columns to be dropped due to low variance is: ', len(df.var()[df.var() <= variance_threshold].index))\n",
232
- "\n",
233
- " # Print into a list the columns to be dropped due to low variance\n",
234
- " drop_variance = list(df.var()[df.var() <= variance_threshold].index)\n",
235
- "\n",
236
- " # Drop columns with more than or equal to threshold variance from df\n",
237
- " df.drop(drop_variance, axis=1, inplace=True)\n",
238
- "\n",
239
- " # Print the number of columns in df with more than or equal to threshold correlation\n",
240
- " \n",
241
- " # Create correlation matrix and round it to 4 decimal places\n",
242
- " corr_matrix = df.corr().abs().round(4)\n",
243
- " upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(bool))\n",
244
- " to_drop = [column for column in upper.columns if any(upper[column] >= correlation_threshold)]\n",
245
- " print('the number of columns to be dropped due to high correlation is: ', len(to_drop))\n",
246
- "\n",
247
- " # Print into a list the columns to be dropped due to high correlation\n",
248
- " drop_correlation = [column for column in upper.columns if any(upper[column] >= correlation_threshold)]\n",
249
- "\n",
250
- " # Drop columns with more than or equal to threshold correlation from df\n",
251
- " df.drop(to_drop, axis=1, inplace=True)\n",
252
- " \n",
253
- " if drop_duplicates == 'yes':\n",
254
- " dropped = (drop_duplicated+drop_missing+drop_variance+drop_correlation)\n",
255
- "\n",
256
- " elif drop_duplicates =='no':\n",
257
- " dropped = (drop_missing+drop_variance+drop_correlation)\n",
258
- " \n",
259
- " print('Total number of columns to be dropped is: ', len(dropped))\n",
260
- " print('New shape of the dataframe is: ', df.shape)\n",
261
- "\n",
262
- " global drop_duplicates_var\n",
263
- " drop_duplicates_var = drop_duplicates\n",
264
- " \n",
265
- " global missing_values_threshold_var\n",
266
- " missing_values_threshold_var = missing_values_threshold\n",
267
- "\n",
268
- " global variance_threshold_var\n",
269
- " variance_threshold_var = variance_threshold\n",
270
- "\n",
271
- " global correlation_threshold_var\n",
272
- " correlation_threshold_var = correlation_threshold\n",
273
- " \n",
274
- " print(type(dropped))\n",
275
- " return dropped"
276
- ]
277
- },
278
- {
279
- "attachments": {},
280
- "cell_type": "markdown",
281
- "metadata": {
282
- "slideshow": {
283
- "slide_type": "skip"
284
- }
285
- },
286
- "source": [
287
- "#### **Outlier Removal**"
288
- ]
289
- },
290
- {
291
- "cell_type": "code",
292
- "execution_count": 23,
293
- "metadata": {
294
- "slideshow": {
295
- "slide_type": "skip"
296
- }
297
- },
298
- "outputs": [],
299
- "source": [
300
- "def outlier_removal(z_df, z_threshold=4):\n",
301
- " \n",
302
- " global outlier_var\n",
303
- "\n",
304
- " if z_threshold == 'none':\n",
305
- " print('No outliers were removed')\n",
306
- " outlier_var = 'none'\n",
307
- " return z_df\n",
308
- " \n",
309
- " else:\n",
310
- " print('The z-score threshold is:', z_threshold)\n",
311
- "\n",
312
- " z_df_copy = z_df.copy()\n",
313
- "\n",
314
- " z_scores = np.abs(stats.zscore(z_df_copy))\n",
315
- "\n",
316
- " # Identify the outliers in the dataset using the z-score method\n",
317
- " outliers_mask = z_scores > z_threshold\n",
318
- " z_df_copy[outliers_mask] = np.nan\n",
319
- "\n",
320
- " outliers_count = np.count_nonzero(outliers_mask)\n",
321
- " print('The number of outliers in the whole dataset is / was:', outliers_count)\n",
322
- "\n",
323
- " outlier_var = z_threshold\n",
324
- "\n",
325
- " print(type(z_df_copy))\n",
326
- " return z_df_copy"
327
- ]
328
- },
329
- {
330
- "attachments": {},
331
- "cell_type": "markdown",
332
- "metadata": {
333
- "slideshow": {
334
- "slide_type": "skip"
335
- }
336
- },
337
- "source": [
338
- "#### **Scaling Methods**"
339
- ]
340
- },
341
- {
342
- "cell_type": "code",
343
- "execution_count": 24,
344
- "metadata": {
345
- "slideshow": {
346
- "slide_type": "skip"
347
- }
348
- },
349
- "outputs": [],
350
- "source": [
351
- "# define a function to scale the dataframe using different scaling models\n",
352
- "\n",
353
- "def scale_dataframe(scale_model,df_fit, df_transform):\n",
354
- " \n",
355
- " global scale_model_var\n",
356
- "\n",
357
- " if scale_model == 'robust':\n",
358
- " from sklearn.preprocessing import RobustScaler\n",
359
- " scaler = RobustScaler()\n",
360
- " scaler.fit(df_fit)\n",
361
- " df_scaled = scaler.transform(df_transform)\n",
362
- " df_scaled = pd.DataFrame(df_scaled, columns=df_transform.columns)\n",
363
- " print('The dataframe has been scaled using the robust scaling model')\n",
364
- " scale_model_var = 'robust'\n",
365
- " return df_scaled\n",
366
- " \n",
367
- " elif scale_model == 'standard':\n",
368
- " from sklearn.preprocessing import StandardScaler\n",
369
- " scaler = StandardScaler()\n",
370
- " scaler.fit(df_fit)\n",
371
- " df_scaled = scaler.transform(df_transform)\n",
372
- " df_scaled = pd.DataFrame(df_scaled, columns=df_transform.columns)\n",
373
- " print('The dataframe has been scaled using the standard scaling model')\n",
374
- " scale_model_var = 'standard'\n",
375
- " return df_scaled\n",
376
- " \n",
377
- " elif scale_model == 'normal':\n",
378
- " from sklearn.preprocessing import Normalizer\n",
379
- " scaler = Normalizer()\n",
380
- " scaler.fit(df_fit)\n",
381
- " df_scaled = scaler.transform(df_transform)\n",
382
- " df_scaled = pd.DataFrame(df_scaled, columns=df_transform.columns)\n",
383
- " print('The dataframe has been scaled using the normal scaling model')\n",
384
- " scale_model_var = 'normal'\n",
385
- " return df_scaled\n",
386
- " \n",
387
- " elif scale_model == 'minmax':\n",
388
- " from sklearn.preprocessing import MinMaxScaler\n",
389
- " scaler = MinMaxScaler()\n",
390
- " scaler.fit(df_fit)\n",
391
- " df_scaled = scaler.transform(df_transform)\n",
392
- " df_scaled = pd.DataFrame(df_scaled, columns=df_transform.columns)\n",
393
- " print('The dataframe has been scaled using the minmax scaling model')\n",
394
- " scale_model_var = 'minmax'\n",
395
- " return df_scaled\n",
396
- " \n",
397
- " elif scale_model == 'none':\n",
398
- " print('The dataframe has not been scaled')\n",
399
- " scale_model_var = 'none'\n",
400
- " return df_transform\n",
401
- " \n",
402
- " else:\n",
403
- " print('Please choose a valid scaling model: robust, standard, normal, or minmax')\n",
404
- " return None"
405
- ]
406
- },
407
- {
408
- "attachments": {},
409
- "cell_type": "markdown",
410
- "metadata": {
411
- "slideshow": {
412
- "slide_type": "skip"
413
- }
414
- },
415
- "source": [
416
- "#### **Missing Value Imputation**"
417
- ]
418
- },
419
- {
420
- "cell_type": "code",
421
- "execution_count": 25,
422
- "metadata": {
423
- "slideshow": {
424
- "slide_type": "skip"
425
- }
426
- },
427
- "outputs": [],
428
- "source": [
429
- "# define a function to impute missing values using different imputation models\n",
430
- "\n",
431
- "def impute_missing_values(imputation, df_fit, df_transform, n_neighbors=5):\n",
432
- "\n",
433
- " print('Number of missing values before imputation: ', df_transform.isnull().sum().sum())\n",
434
- "\n",
435
- " global imputation_var\n",
436
- "\n",
437
- " if imputation == 'knn':\n",
438
- "\n",
439
- " from sklearn.impute import KNNImputer\n",
440
- " imputer = KNNImputer(n_neighbors=n_neighbors)\n",
441
- " imputer.fit(df_fit)\n",
442
- " df_imputed = imputer.transform(df_transform)\n",
443
- " df_imputed = pd.DataFrame(df_imputed, columns=df_transform.columns)\n",
444
- " print('Number of missing values after imputation: ', df_imputed.isnull().sum().sum())\n",
445
- " imputation_var = 'knn'\n",
446
- " return df_imputed\n",
447
- " \n",
448
- " elif imputation == 'mean':\n",
449
- "\n",
450
- " from sklearn.impute import SimpleImputer\n",
451
- " imputer = SimpleImputer(strategy='mean')\n",
452
- " imputer.fit(df_fit)\n",
453
- " df_imputed = imputer.transform(df_transform)\n",
454
- " df_imputed = pd.DataFrame(df_imputed, columns=df_transform.columns)\n",
455
- " print('Number of missing values after imputation: ', df_imputed.isnull().sum().sum())\n",
456
- " imputation_var = 'mean'\n",
457
- " return df_imputed\n",
458
- " \n",
459
- " elif imputation == 'median':\n",
460
- "\n",
461
- " from sklearn.impute import SimpleImputer\n",
462
- " imputer = SimpleImputer(strategy='median')\n",
463
- " imputer.fit(df_fit)\n",
464
- " df_imputed = imputer.transform(df_transform)\n",
465
- " df_imputed = pd.DataFrame(df_imputed, columns=df_transform.columns)\n",
466
- " print('Number of missing values after imputation: ', df_imputed.isnull().sum().sum())\n",
467
- " imputation_var = 'median'\n",
468
- " return df_imputed\n",
469
- " \n",
470
- " elif imputation == 'most_frequent':\n",
471
- " \n",
472
- " from sklearn.impute import SimpleImputer\n",
473
- " imputer = SimpleImputer(strategy='most_frequent')\n",
474
- " imputer.fit(df_fit)\n",
475
- " df_imputed = imputer.transform(df_transform)\n",
476
- " df_imputed = pd.DataFrame(df_imputed, columns=df_transform.columns)\n",
477
- " print('Number of missing values after imputation: ', df_imputed.isnull().sum().sum())\n",
478
- " imputation_var = 'most_frequent'\n",
479
- " return df_imputed\n",
480
- " \n",
481
- " else:\n",
482
- " print('Please choose an imputation model from the following: knn, mean, median, most_frequent')\n",
483
- " df_imputed = df_transform.copy()\n",
484
- " return df_imputed\n"
485
- ]
486
- },
487
- {
488
- "attachments": {},
489
- "cell_type": "markdown",
490
- "metadata": {
491
- "slideshow": {
492
- "slide_type": "skip"
493
- }
494
- },
495
- "source": [
496
- "#### **Feature Selection**"
497
- ]
498
- },
499
- {
500
- "cell_type": "code",
501
- "execution_count": 26,
502
- "metadata": {
503
- "slideshow": {
504
- "slide_type": "skip"
505
- }
506
- },
507
- "outputs": [],
508
- "source": [
509
- "def feature_selection(method, X_train, y_train):\n",
510
- "\n",
511
- " global feature_selection_var\n",
512
- " global selected_features \n",
513
- "\n",
514
- " if method == 'boruta':\n",
515
- " print('Selected method is: ', method)\n",
516
- " from boruta import BorutaPy\n",
517
- " from sklearn.ensemble import RandomForestClassifier\n",
518
- " rf = RandomForestClassifier(n_estimators=100, n_jobs=-1)\n",
519
- " boruta_selector = BorutaPy(rf,n_estimators='auto', verbose=0, random_state=42)\n",
520
- " boruta_selector.fit(X_train.values, y_train.values.ravel())\n",
521
- " selected_feature_indices = boruta_selector.support_\n",
522
- " selected_columns = X_train.columns[selected_feature_indices]\n",
523
- " X_train_filtered = X_train.iloc[:, selected_feature_indices]\n",
524
- " print('Shape of the training set after feature selection with Boruta: ', X_train_filtered.shape)\n",
525
- " feature_selection_var = 'boruta'\n",
526
- " return X_train_filtered, selected_columns\n",
527
- " \n",
528
- " if method == 'none':\n",
529
- " print('Selected method is: ', method)\n",
530
- " X_train_filtered = X_train\n",
531
- " print('Shape of the training set after no feature selection: ', X_train_filtered.shape)\n",
532
- " feature_selection_var = 'none'\n",
533
- " selected_features = X_train_filtered.columns\n",
534
- " feature_selection_var = 'none'\n",
535
- " return X_train_filtered, selected_features \n",
536
- " \n",
537
- " if method == 'lasso':\n",
538
- " print('Selected method is: ', method)\n",
539
- " from sklearn.linear_model import LassoCV\n",
540
- " from sklearn.feature_selection import SelectFromModel\n",
541
- " lasso = LassoCV().fit(X_train, y_train)\n",
542
- " model = SelectFromModel(lasso, prefit=True)\n",
543
- " X_train_filtered = model.transform(X_train)\n",
544
- " selected_features = X_train.columns[model.get_support()]\n",
545
- " print('Shape of the training set after feature selection with LassoCV: ', X_train_filtered.shape)\n",
546
- " feature_selection_var = 'lasso'\n",
547
- " return X_train_filtered, selected_features\n",
548
- " \n",
549
- " if method == 'pca':\n",
550
- " print('Selected method is: ', method)\n",
551
- " from sklearn.decomposition import PCA\n",
552
- " pca = PCA(n_components=15)\n",
553
- " X_train_pca = pca.fit_transform(X_train)\n",
554
- " selected_features = X_train.columns[pca.explained_variance_ratio_.argsort()[::-1]][:15]\n",
555
- " print('Shape of the training set after feature selection with PCA: ', X_train_pca.shape)\n",
556
- " feature_selection_var = 'pca'\n",
557
- " return X_train_pca, selected_features\n",
558
- " \n",
559
- " if method == 'rfe':\n",
560
- " print('Selected method is: ', method)\n",
561
- " from sklearn.feature_selection import RFE\n",
562
- " from sklearn.ensemble import RandomForestClassifier\n",
563
- " rfe_selector = RFE(estimator=RandomForestClassifier(n_estimators=100, n_jobs=-1), n_features_to_select=15, step=10, verbose=0)\n",
564
- " rfe_selector.fit(X_train, y_train)\n",
565
- " selected_features = X_train.columns[rfe_selector.support_]\n",
566
- " X_train_filtered = X_train.iloc[:, rfe_selector.support_]\n",
567
- " print('Shape of the training set after feature selection with RFE: ', X_train_filtered.shape)\n",
568
- " feature_selection_var = 'rfe'\n",
569
- " return X_train_filtered, selected_features\n",
570
- " "
571
- ]
572
- },
573
- {
574
- "attachments": {},
575
- "cell_type": "markdown",
576
- "metadata": {
577
- "slideshow": {
578
- "slide_type": "skip"
579
- }
580
- },
581
- "source": [
582
- "#### **Imbalance Treatment**"
583
- ]
584
- },
585
- {
586
- "cell_type": "code",
587
- "execution_count": 27,
588
- "metadata": {
589
- "slideshow": {
590
- "slide_type": "skip"
591
- }
592
- },
593
- "outputs": [],
594
- "source": [
595
- "#define a function to oversample and understamble the imbalance in the training set\n",
596
- "\n",
597
- "def imbalance_treatment(method, X_train, y_train):\n",
598
- "\n",
599
- " global imbalance_var\n",
600
- "\n",
601
- " if method == 'smote': \n",
602
- " from imblearn.over_sampling import SMOTE\n",
603
- " sm = SMOTE(random_state=42)\n",
604
- " X_train_res, y_train_res = sm.fit_resample(X_train, y_train)\n",
605
- " imbalance_var = 'smote'\n",
606
- " return X_train_res, y_train_res\n",
607
- " \n",
608
- " if method == 'undersampling':\n",
609
- " from imblearn.under_sampling import RandomUnderSampler\n",
610
- " rus = RandomUnderSampler(random_state=42)\n",
611
- " X_train_res, y_train_res = rus.fit_resample(X_train, y_train)\n",
612
- " imbalance_var = 'random_undersampling'\n",
613
- " return X_train_res, y_train_res\n",
614
- " \n",
615
- " if method == 'rose':\n",
616
- " from imblearn.over_sampling import RandomOverSampler\n",
617
- " ros = RandomOverSampler(random_state=42)\n",
618
- " X_train_res, y_train_res = ros.fit_resample(X_train, y_train)\n",
619
- " imbalance_var = 'rose'\n",
620
- " return X_train_res, y_train_res\n",
621
- " \n",
622
- " \n",
623
- " if method == 'none':\n",
624
- " X_train_res = X_train\n",
625
- " y_train_res = y_train\n",
626
- " imbalance_var = 'none'\n",
627
- " return X_train_res, y_train_res\n",
628
- " \n",
629
- " else:\n",
630
- " print('Please choose a valid resampling method: smote, rose, undersampling or none')\n",
631
- " X_train_res = X_train\n",
632
- " y_train_res = y_train\n",
633
- " return X_train_res, y_train_res"
634
- ]
635
- },
636
- {
637
- "attachments": {},
638
- "cell_type": "markdown",
639
- "metadata": {
640
- "slideshow": {
641
- "slide_type": "skip"
642
- }
643
- },
644
- "source": [
645
- "#### **Training Models**"
646
- ]
647
- },
648
- {
649
- "cell_type": "code",
650
- "execution_count": 28,
651
- "metadata": {
652
- "slideshow": {
653
- "slide_type": "skip"
654
- }
655
- },
656
- "outputs": [],
657
- "source": [
658
- "# define a function where you can choose the model you want to use to train the data\n",
659
- "\n",
660
- "def train_model(model, X_train, y_train, X_test, y_test):\n",
661
- "\n",
662
- " global model_var\n",
663
- "\n",
664
- " if model == 'random_forest':\n",
665
- " from sklearn.ensemble import RandomForestClassifier\n",
666
- " rfc = RandomForestClassifier(n_estimators=100, random_state=13)\n",
667
- " rfc.fit(X_train, y_train)\n",
668
- " y_pred = rfc.predict(X_test)\n",
669
- " model_var = 'random_forest'\n",
670
- " return y_pred\n",
671
- "\n",
672
- " if model == 'logistic_regression':\n",
673
- " from sklearn.linear_model import LogisticRegression\n",
674
- " lr = LogisticRegression()\n",
675
- " lr.fit(X_train, y_train)\n",
676
- " y_pred = lr.predict(X_test)\n",
677
- " model_var = 'logistic_regression'\n",
678
- " return y_pred\n",
679
- " \n",
680
- " if model == 'knn':\n",
681
- " from sklearn.neighbors import KNeighborsClassifier\n",
682
- " knn = KNeighborsClassifier(n_neighbors=5)\n",
683
- " knn.fit(X_train, y_train)\n",
684
- " y_pred = knn.predict(X_test)\n",
685
- " model_var = 'knn'\n",
686
- " return y_pred\n",
687
- " \n",
688
- " if model == 'svm':\n",
689
- " from sklearn.svm import SVC\n",
690
- " svm = SVC()\n",
691
- " svm.fit(X_train, y_train)\n",
692
- " y_pred = svm.predict(X_test)\n",
693
- " model_var = 'svm'\n",
694
- " return y_pred\n",
695
- " \n",
696
- " if model == 'naive_bayes':\n",
697
- " from sklearn.naive_bayes import GaussianNB\n",
698
- " nb = GaussianNB()\n",
699
- " nb.fit(X_train, y_train)\n",
700
- " y_pred = nb.predict(X_test)\n",
701
- " model_var = 'naive_bayes'\n",
702
- " return y_pred\n",
703
- " \n",
704
- " if model == 'decision_tree':\n",
705
- " from sklearn.tree import DecisionTreeClassifier\n",
706
- " dt = DecisionTreeClassifier()\n",
707
- " dt.fit(X_train, y_train)\n",
708
- " y_pred = dt.predict(X_test)\n",
709
- " model_var = 'decision_tree'\n",
710
- " return y_pred\n",
711
- " \n",
712
- " if model == 'xgboost':\n",
713
- " from xgboost import XGBClassifier\n",
714
- " xgb = XGBClassifier()\n",
715
- " xgb.fit(X_train, y_train)\n",
716
- " y_pred = xgb.predict(X_test)\n",
717
- " model_var = 'xgboost'\n",
718
- " return y_pred\n",
719
- " \n",
720
- " else:\n",
721
- " print('Please choose a model from the following: random_forest, logistic_regression, knn, svm, naive_bayes, decision_tree, xgboost')\n",
722
- " return None"
723
- ]
724
- },
725
- {
726
- "attachments": {},
727
- "cell_type": "markdown",
728
- "metadata": {
729
- "slideshow": {
730
- "slide_type": "skip"
731
- }
732
- },
733
- "source": [
734
- "#### **Evaluation Function**"
735
- ]
736
- },
737
- {
738
- "cell_type": "code",
739
- "execution_count": 29,
740
- "metadata": {
741
- "slideshow": {
742
- "slide_type": "skip"
743
- }
744
- },
745
- "outputs": [],
746
- "source": [
747
- "#define a function that prints the strings below\n",
748
- "\n",
749
- "from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score\n",
750
- "\n",
751
- "def evaluate_models(model='random_forest'):\n",
752
- "\n",
753
- " all_models = ['random_forest', 'logistic_regression', 'knn', 'svm', 'naive_bayes', 'decision_tree', 'xgboost']\n",
754
- " evaluation_score_append = []\n",
755
- " evaluation_count_append = []\n",
756
- " \n",
757
- " for selected_model in all_models:\n",
758
- " \n",
759
- " if model == 'all' or model == selected_model:\n",
760
- "\n",
761
- " evaluation_score = []\n",
762
- " evaluation_count = []\n",
763
- "\n",
764
- " y_pred = globals()['y_pred_' + selected_model] # Get the prediction variable dynamically\n",
765
- "\n",
766
- " def namestr(obj, namespace):\n",
767
- " return [name for name in namespace if namespace[name] is obj]\n",
768
- "\n",
769
- " model_name = namestr(y_pred, globals())[0]\n",
770
- " model_name = model_name.replace('y_pred_', '') \n",
771
- "\n",
772
- " cm = confusion_matrix(y_test, y_pred)\n",
773
- "\n",
774
- " # create a dataframe with the results for each model\n",
775
- "\n",
776
- " evaluation_score.append(model_name)\n",
777
- " evaluation_score.append(round(accuracy_score(y_test, y_pred), 2))\n",
778
- " evaluation_score.append(round(precision_score(y_test, y_pred, zero_division=0), 2))\n",
779
- " evaluation_score.append(round(recall_score(y_test, y_pred), 2))\n",
780
- " evaluation_score.append(round(f1_score(y_test, y_pred), 2))\n",
781
- " evaluation_score_append.append(evaluation_score)\n",
782
- "\n",
783
- "\n",
784
- " # create a dataframe with the true positives, true negatives, false positives and false negatives for each model\n",
785
- "\n",
786
- " evaluation_count.append(model_name)\n",
787
- " evaluation_count.append(cm[0][0])\n",
788
- " evaluation_count.append(cm[0][1])\n",
789
- " evaluation_count.append(cm[1][0])\n",
790
- " evaluation_count.append(cm[1][1])\n",
791
- " evaluation_count_append.append(evaluation_count)\n",
792
- "\n",
793
- " \n",
794
- " evaluation_score_append = pd.DataFrame(evaluation_score_append, \n",
795
- " columns=['Model', 'Accuracy', 'Precision', 'Recall', 'F1-score'])\n",
796
- " \n",
797
- " \n",
798
- "\n",
799
- " evaluation_count_append = pd.DataFrame(evaluation_count_append,\n",
800
- " columns=['Model', 'True Negatives', 'False Positives', 'False Negatives', 'True Positives'])\n",
801
- " \n",
802
- " \n",
803
- " return evaluation_score_append, evaluation_count_append"
804
- ]
805
- },
806
- {
807
- "attachments": {},
808
- "cell_type": "markdown",
809
- "metadata": {
810
- "slideshow": {
811
- "slide_type": "skip"
812
- }
813
- },
814
- "source": [
815
- "### **Input Variables**"
816
- ]
817
- },
818
- {
819
- "cell_type": "code",
820
- "execution_count": 30,
821
- "metadata": {
822
- "slideshow": {
823
- "slide_type": "skip"
824
- }
825
- },
826
- "outputs": [
827
- {
828
- "data": {
829
- "application/mercury+json": {
830
- "choices": [
831
- "yes",
832
- "no"
833
- ],
834
- "code_uid": "Select.0.40.16.25-randb785d2a5",
835
- "disabled": false,
836
- "hidden": false,
837
- "label": "Drop Duplicates",
838
- "model_id": "f5c9c8b77b8a4b92bfeaebfd09688f8a",
839
- "url_key": "",
840
- "value": "yes",
841
- "widget": "Select"
842
- },
843
- "application/vnd.jupyter.widget-view+json": {
844
- "model_id": "f5c9c8b77b8a4b92bfeaebfd09688f8a",
845
- "version_major": 2,
846
- "version_minor": 0
847
- },
848
- "text/plain": [
849
- "mercury.Select"
850
- ]
851
- },
852
- "metadata": {},
853
- "output_type": "display_data"
854
- },
855
- {
856
- "data": {
857
- "application/mercury+json": {
858
- "code_uid": "Text.0.40.15.28-rand76290b78",
859
- "disabled": false,
860
- "hidden": false,
861
- "label": "Missing Value Threeshold",
862
- "model_id": "2a1d81490e1e439ba214219a0bfa56b3",
863
- "rows": 1,
864
- "url_key": "",
865
- "value": "80",
866
- "widget": "Text"
867
- },
868
- "application/vnd.jupyter.widget-view+json": {
869
- "model_id": "2a1d81490e1e439ba214219a0bfa56b3",
870
- "version_major": 2,
871
- "version_minor": 0
872
- },
873
- "text/plain": [
874
- "mercury.Text"
875
- ]
876
- },
877
- "metadata": {},
878
- "output_type": "display_data"
879
- },
880
- {
881
- "data": {
882
- "application/mercury+json": {
883
- "code_uid": "Text.0.40.15.31-rand3a34547a",
884
- "disabled": false,
885
- "hidden": false,
886
- "label": "Variance Threshold",
887
- "model_id": "e0e229e9864545099ba169ad272273f5",
888
- "rows": 1,
889
- "url_key": "",
890
- "value": "0",
891
- "widget": "Text"
892
- },
893
- "application/vnd.jupyter.widget-view+json": {
894
- "model_id": "e0e229e9864545099ba169ad272273f5",
895
- "version_major": 2,
896
- "version_minor": 0
897
- },
898
- "text/plain": [
899
- "mercury.Text"
900
- ]
901
- },
902
- "metadata": {},
903
- "output_type": "display_data"
904
- },
905
- {
906
- "data": {
907
- "application/mercury+json": {
908
- "code_uid": "Text.0.40.15.34-rand79b594f6",
909
- "disabled": false,
910
- "hidden": false,
911
- "label": "Correlation Threshold",
912
- "model_id": "3c42c9d218934722a7c2ebcaa9715d34",
913
- "rows": 1,
914
- "url_key": "",
915
- "value": "1",
916
- "widget": "Text"
917
- },
918
- "application/vnd.jupyter.widget-view+json": {
919
- "model_id": "3c42c9d218934722a7c2ebcaa9715d34",
920
- "version_major": 2,
921
- "version_minor": 0
922
- },
923
- "text/plain": [
924
- "mercury.Text"
925
- ]
926
- },
927
- "metadata": {},
928
- "output_type": "display_data"
929
- },
930
- {
931
- "data": {
932
- "application/mercury+json": {
933
- "choices": [
934
- "none",
935
- 3,
936
- 4,
937
- 5
938
- ],
939
- "code_uid": "Select.0.40.16.38-randb65fcc34",
940
- "disabled": false,
941
- "hidden": false,
942
- "label": "Outlier Removal Threshold",
943
- "model_id": "577bf130efe0427f82fbb99a6e6f8796",
944
- "url_key": "",
945
- "value": "none",
946
- "widget": "Select"
947
- },
948
- "application/vnd.jupyter.widget-view+json": {
949
- "model_id": "577bf130efe0427f82fbb99a6e6f8796",
950
- "version_major": 2,
951
- "version_minor": 0
952
- },
953
- "text/plain": [
954
- "mercury.Select"
955
- ]
956
- },
957
- "metadata": {},
958
- "output_type": "display_data"
959
- },
960
- {
961
- "data": {
962
- "application/mercury+json": {
963
- "choices": [
964
- "none",
965
- "standard",
966
- "minmax",
967
- "robust"
968
- ],
969
- "code_uid": "Select.0.40.16.46-rand2e347045",
970
- "disabled": false,
971
- "hidden": false,
972
- "label": "Scaling Variables",
973
- "model_id": "1775424536e64ff899ca0d6ec93ea978",
974
- "url_key": "",
975
- "value": "none",
976
- "widget": "Select"
977
- },
978
- "application/vnd.jupyter.widget-view+json": {
979
- "model_id": "1775424536e64ff899ca0d6ec93ea978",
980
- "version_major": 2,
981
- "version_minor": 0
982
- },
983
- "text/plain": [
984
- "mercury.Select"
985
- ]
986
- },
987
- "metadata": {},
988
- "output_type": "display_data"
989
- },
990
- {
991
- "data": {
992
- "application/mercury+json": {
993
- "choices": [
994
- "mean",
995
- "median",
996
- "knn",
997
- "most_frequent"
998
- ],
999
- "code_uid": "Select.0.40.16.50-randa094eed0",
1000
- "disabled": false,
1001
- "hidden": false,
1002
- "label": "Imputation Methods",
1003
- "model_id": "a35dad0324ce44578f8ce2609662f4ec",
1004
- "url_key": "",
1005
- "value": "mean",
1006
- "widget": "Select"
1007
- },
1008
- "application/vnd.jupyter.widget-view+json": {
1009
- "model_id": "a35dad0324ce44578f8ce2609662f4ec",
1010
- "version_major": 2,
1011
- "version_minor": 0
1012
- },
1013
- "text/plain": [
1014
- "mercury.Select"
1015
- ]
1016
- },
1017
- "metadata": {},
1018
- "output_type": "display_data"
1019
- },
1020
- {
1021
- "data": {
1022
- "application/mercury+json": {
1023
- "choices": [
1024
- "none",
1025
- "lasso",
1026
- "rfe",
1027
- "pca",
1028
- "boruta"
1029
- ],
1030
- "code_uid": "Select.0.40.16.55-rande9681438",
1031
- "disabled": false,
1032
- "hidden": false,
1033
- "label": "Feature Selection",
1034
- "model_id": "ee69abf9627d44c09da90a79fe98c447",
1035
- "url_key": "",
1036
- "value": "none",
1037
- "widget": "Select"
1038
- },
1039
- "application/vnd.jupyter.widget-view+json": {
1040
- "model_id": "ee69abf9627d44c09da90a79fe98c447",
1041
- "version_major": 2,
1042
- "version_minor": 0
1043
- },
1044
- "text/plain": [
1045
- "mercury.Select"
1046
- ]
1047
- },
1048
- "metadata": {},
1049
- "output_type": "display_data"
1050
- },
1051
- {
1052
- "data": {
1053
- "application/mercury+json": {
1054
- "choices": [
1055
- "none",
1056
- "smote",
1057
- "undersampling",
1058
- "rose"
1059
- ],
1060
- "code_uid": "Select.0.40.16.59-randc218b629",
1061
- "disabled": false,
1062
- "hidden": false,
1063
- "label": "Imbalance Treatment",
1064
- "model_id": "d2da0edfb49d45e680d72f1cd59b956d",
1065
- "url_key": "",
1066
- "value": "none",
1067
- "widget": "Select"
1068
- },
1069
- "application/vnd.jupyter.widget-view+json": {
1070
- "model_id": "d2da0edfb49d45e680d72f1cd59b956d",
1071
- "version_major": 2,
1072
- "version_minor": 0
1073
- },
1074
- "text/plain": [
1075
- "mercury.Select"
1076
- ]
1077
- },
1078
- "metadata": {},
1079
- "output_type": "display_data"
1080
- },
1081
- {
1082
- "data": {
1083
- "application/mercury+json": {
1084
- "choices": [
1085
- "random_forest",
1086
- "logistic_regression",
1087
- "knn",
1088
- "svm",
1089
- "naive_bayes",
1090
- "decision_tree",
1091
- "xgboost"
1092
- ],
1093
- "code_uid": "Select.0.40.16.64-rand3f39df1a",
1094
- "disabled": false,
1095
- "hidden": false,
1096
- "label": "Model Selection",
1097
- "model_id": "c277aac8be5a4a21a048ea6cab3b9501",
1098
- "url_key": "",
1099
- "value": "xgboost",
1100
- "widget": "Select"
1101
- },
1102
- "application/vnd.jupyter.widget-view+json": {
1103
- "model_id": "c277aac8be5a4a21a048ea6cab3b9501",
1104
- "version_major": 2,
1105
- "version_minor": 0
1106
- },
1107
- "text/plain": [
1108
- "mercury.Select"
1109
- ]
1110
- },
1111
- "metadata": {},
1112
- "output_type": "display_data"
1113
- }
1114
- ],
1115
- "source": [
1116
- "\n",
1117
- "evaluation_score_df = pd.DataFrame(columns=['Model', 'Accuracy', 'Precision', 'Recall', 'F1-score', 'model_variables'])\n",
1118
- "evaluation_count_df = pd.DataFrame(columns=['Model', 'True Negatives', 'False Positives', 'False Negatives', 'True Positives', 'model_variables'])\n",
1119
- "\n",
1120
- "#############################################################################################################\n",
1121
- "# reset the dataframe containing all results, evaluation_score_df and evaluation_count_df\n",
1122
- "\n",
1123
- "reset_results = 'no' # 'yes' or 'no'\n",
1124
- "\n",
1125
- "#############################################################################################################\n",
1126
- "\n",
1127
- "if reset_results == 'yes':\n",
1128
- " evaluation_score_df = pd.DataFrame(columns=['Model', 'Accuracy', 'Precision', 'Recall', 'F1-score', 'model_variables'])\n",
1129
- " evaluation_count_df = pd.DataFrame(columns=['Model', 'True Negatives', 'False Positives', 'False Negatives', 'True Positives', 'model_variables'])\n",
1130
- " \n",
1131
- "\n",
1132
- "#############################################################################################################\n",
1133
- "\n",
1134
- "# input train and test sets\n",
1135
- "input_train_set = X_train\n",
1136
- "input_test_set = X_test\n",
1137
- "\n",
1138
- "\n",
1139
- "\n",
1140
- "# input feature removal variables\n",
1141
- "input_drop_duplicates = mr.Select(label=\"Drop Duplicates\", value=\"yes\", choices=[\"yes\", \"no\"]) # 'yes' or 'no'\n",
1142
- "input_drop_duplicates = str(input_drop_duplicates.value)\n",
1143
- "\n",
1144
- "input_missing_values_threshold = mr.Text(label=\"Missing Value Threeshold\", value='80') # 0-100 (removes columns with more missing values than the threshold)\n",
1145
- "input_missing_values_threshold = int(input_missing_values_threshold.value)\n",
1146
- "\n",
1147
- "input_variance_threshold = mr.Text(label=\"Variance Threshold\", value='0') # \n",
1148
- "input_variance_threshold = float(input_variance_threshold.value)\n",
1149
- "\n",
1150
- "input_correlation_threshold = mr.Text(label=\"Correlation Threshold\", value='1') # \n",
1151
- "input_correlation_threshold = float(input_correlation_threshold.value)\n",
1152
- "\n",
1153
- "# input outlier removal variables\n",
1154
- "input_outlier_removal_threshold = mr.Select(label=\"Outlier Removal Threshold\", value=\"none\", choices=['none', 3, 4, 5]) # 'none' or zscore from 0 to 100\n",
1155
- "\n",
1156
- "if input_outlier_removal_threshold.value != 'none':\n",
1157
- " input_outlier_removal_threshold = int(input_outlier_removal_threshold.value)\n",
1158
- "elif input_outlier_removal_threshold.value == 'none':\n",
1159
- " input_outlier_removal_threshold = str(input_outlier_removal_threshold.value)\n",
1160
- "\n",
1161
- "# input scaling variables\n",
1162
- "input_scale_model = mr.Select(label=\"Scaling Variables\", value=\"none\", choices=['none', 'standard', 'minmax', 'robust']) # 'none', 'normal', 'standard', 'minmax', 'robust'\n",
1163
- "input_scale_model = str(input_scale_model.value)\n",
1164
- "\n",
1165
- "# input imputation variables\n",
1166
- "input_imputation_method = mr.Select(label=\"Imputation Methods\", value=\"mean\", choices=['mean', 'median', 'knn', 'most_frequent']) # 'mean', 'median', 'knn', 'most_frequent'\n",
1167
- "input_n_neighbors = 5 # only for knn imputation\n",
1168
- "input_imputation_method = str(input_imputation_method.value)\n",
1169
- "\n",
1170
- "# input feature selection variables\n",
1171
- "input_feature_selection = mr.Select(label=\"Feature Selection\", value=\"none\", choices=['none', 'lasso', 'rfe', 'pca', 'boruta']) # 'none', 'lasso', 'rfe', 'pca', 'boruta'\n",
1172
- "input_feature_selection = str(input_feature_selection.value)\n",
1173
- "\n",
1174
- "# input imbalance treatment variables\n",
1175
- "input_imbalance_treatment = mr.Select(label=\"Imbalance Treatment\", value=\"none\", choices=['none', 'smote', 'undersampling', 'rose']) # 'none', 'smote', 'undersampling', 'rose'\n",
1176
- "input_imbalance_treatment = str(input_imbalance_treatment.value)\n",
1177
- "\n",
1178
- "\n",
1179
- "# input model\n",
1180
- "input_model = mr.Select(label=\"Model Selection\", value=\"xgboost\", choices=['random_forest', 'logistic_regression', 'knn', 'svm', 'naive_bayes','decision_tree','xgboost']) # 'all', 'random_forest', 'logistic_regression', 'knn', \n",
1181
- " # 'svm', 'naive_bayes', # 'decision_tree', 'xgboost'\n",
1182
- "input_model = str(input_model.value)\n"
1183
- ]
1184
- },
1185
- {
1186
- "attachments": {},
1187
- "cell_type": "markdown",
1188
- "metadata": {
1189
- "slideshow": {
1190
- "slide_type": "skip"
1191
- }
1192
- },
1193
- "source": [
1194
- "### **Transform Data**"
1195
- ]
1196
- },
1197
- {
1198
- "attachments": {},
1199
- "cell_type": "markdown",
1200
- "metadata": {
1201
- "slideshow": {
1202
- "slide_type": "skip"
1203
- }
1204
- },
1205
- "source": [
1206
- "#### **Remove Features**"
1207
- ]
1208
- },
1209
- {
1210
- "cell_type": "code",
1211
- "execution_count": 31,
1212
- "metadata": {
1213
- "slideshow": {
1214
- "slide_type": "skip"
1215
- }
1216
- },
1217
- "outputs": [
1218
- {
1219
- "name": "stdout",
1220
- "output_type": "stream",
1221
- "text": [
1222
- "Shape of the dataframe is: (1175, 590)\n",
1223
- "the number of columns to be dropped due to duplications is: 104\n",
1224
- "the number of columns to be dropped due to missing values is: 8\n",
1225
- "the number of columns to be dropped due to low variance is: 12\n",
1226
- "the number of columns to be dropped due to high correlation is: 21\n",
1227
- "Total number of columns to be dropped is: 145\n",
1228
- "New shape of the dataframe is: (1175, 445)\n",
1229
- "<class 'list'>\n",
1230
- "No outliers were removed\n",
1231
- "The dataframe has not been scaled\n",
1232
- "The dataframe has not been scaled\n",
1233
- "Number of missing values before imputation: 19977\n",
1234
- "Number of missing values after imputation: 0\n",
1235
- "Number of missing values before imputation: 6954\n",
1236
- "Number of missing values after imputation: 0\n",
1237
- "Selected method is: none\n",
1238
- "Shape of the training set after no feature selection: (1175, 445)\n"
1239
- ]
1240
- }
1241
- ],
1242
- "source": [
1243
- "# remove features using the function list_columns_to_drop\n",
1244
- "\n",
1245
- "dropped = columns_to_drop(input_train_set, \n",
1246
- " input_drop_duplicates, input_missing_values_threshold, \n",
1247
- " input_variance_threshold, input_correlation_threshold)\n",
1248
- "\n",
1249
- "# drop the columns from the training and testing sets and save the new sets as new variables\n",
1250
- "\n",
1251
- "X_train2 = input_train_set.drop(dropped, axis=1)\n",
1252
- "X_test2 = input_test_set.drop(dropped, axis=1)\n",
1253
- "\n",
1254
- "X_train_dropped_outliers = outlier_removal(X_train2, input_outlier_removal_threshold)\n",
1255
- "\n",
1256
- "\n",
1257
- "X_train_scaled = scale_dataframe(input_scale_model, X_train_dropped_outliers, X_train_dropped_outliers)\n",
1258
- "X_test_scaled = scale_dataframe(input_scale_model, X_train_dropped_outliers, X_test2)\n",
1259
- "\n",
1260
- "# impute the missing values in the training and testing sets using the function impute_missing_values\n",
1261
- "\n",
1262
- "X_train_imputed = impute_missing_values(input_imputation_method,X_train_scaled, X_train_scaled, input_n_neighbors)\n",
1263
- "X_test_imputed = impute_missing_values(input_imputation_method,X_train_scaled, X_test_scaled, input_n_neighbors)\n",
1264
- "\n",
1265
- "# select the features using the function feature_selection\n",
1266
- "\n",
1267
- "X_train_selected, selected_features = feature_selection(input_feature_selection, X_train_imputed, y_train)\n",
1268
- "\n",
1269
- "X_train_selected = pd.DataFrame(X_train_selected, columns=selected_features)\n",
1270
- "X_test_selected = X_test_imputed[selected_features]\n",
1271
- "\n",
1272
- "# treat imbalance in the training set using the function oversample\n",
1273
- "\n",
1274
- "X_train_res, y_train_res = imbalance_treatment(input_imbalance_treatment, X_train_selected, y_train)\n",
1275
- "\n"
1276
- ]
1277
- },
1278
- {
1279
- "attachments": {},
1280
- "cell_type": "markdown",
1281
- "metadata": {
1282
- "slideshow": {
1283
- "slide_type": "skip"
1284
- }
1285
- },
1286
- "source": [
1287
- "### **Model Training**"
1288
- ]
1289
- },
1290
- {
1291
- "cell_type": "code",
1292
- "execution_count": 32,
1293
- "metadata": {
1294
- "slideshow": {
1295
- "slide_type": "skip"
1296
- }
1297
- },
1298
- "outputs": [],
1299
- "source": [
1300
- "# train the model using the function train_model and save the predictions as new variables\n",
1301
- "\n",
1302
- "y_pred_random_forest = train_model('random_forest', X_train_res, y_train_res, X_test_imputed, y_test)\n",
1303
- "y_pred_logistic_regression = train_model('logistic_regression', X_train_res, y_train_res, X_test_imputed, y_test)\n",
1304
- "y_pred_knn = train_model('knn', X_train_res, y_train_res, X_test_imputed, y_test)\n",
1305
- "y_pred_svm = train_model('svm', X_train_res, y_train_res, X_test_imputed, y_test)\n",
1306
- "y_pred_naive_bayes = train_model('naive_bayes', X_train_res, y_train_res, X_test_imputed, y_test)\n",
1307
- "y_pred_decision_tree = train_model('decision_tree', X_train_res, y_train_res, X_test_imputed, y_test)\n",
1308
- "y_pred_xgboost = train_model('xgboost', X_train_res, y_train_res, X_test_imputed, y_test)"
1309
- ]
1310
- },
1311
- {
1312
- "attachments": {},
1313
- "cell_type": "markdown",
1314
- "metadata": {
1315
- "slideshow": {
1316
- "slide_type": "skip"
1317
- }
1318
- },
1319
- "source": [
1320
- "#### **Evaluate and Save**"
1321
- ]
1322
- },
1323
- {
1324
- "cell_type": "code",
1325
- "execution_count": 33,
1326
- "metadata": {
1327
- "slideshow": {
1328
- "slide_type": "slide"
1329
- }
1330
- },
1331
- "outputs": [
1332
- {
1333
- "data": {
1334
- "text/html": [
1335
- "<div>\n",
1336
- "<style scoped>\n",
1337
- " .dataframe tbody tr th:only-of-type {\n",
1338
- " vertical-align: middle;\n",
1339
- " }\n",
1340
- "\n",
1341
- " .dataframe tbody tr th {\n",
1342
- " vertical-align: top;\n",
1343
- " }\n",
1344
- "\n",
1345
- " .dataframe thead th {\n",
1346
- " text-align: right;\n",
1347
- " }\n",
1348
- "</style>\n",
1349
- "<table border=\"1\" class=\"dataframe\">\n",
1350
- " <thead>\n",
1351
- " <tr style=\"text-align: right;\">\n",
1352
- " <th></th>\n",
1353
- " <th>Model</th>\n",
1354
- " <th>Accuracy</th>\n",
1355
- " <th>Precision</th>\n",
1356
- " <th>Recall</th>\n",
1357
- " <th>F1-score</th>\n",
1358
- " </tr>\n",
1359
- " </thead>\n",
1360
- " <tbody>\n",
1361
- " <tr>\n",
1362
- " <th>0</th>\n",
1363
- " <td>xgboost</td>\n",
1364
- " <td>0.93</td>\n",
1365
- " <td>0.0</td>\n",
1366
- " <td>0.0</td>\n",
1367
- " <td>0.0</td>\n",
1368
- " </tr>\n",
1369
- " </tbody>\n",
1370
- "</table>\n",
1371
- "</div>"
1372
- ],
1373
- "text/plain": [
1374
- " Model Accuracy Precision Recall F1-score\n",
1375
- "0 xgboost 0.93 0.0 0.0 0.0"
1376
- ]
1377
- },
1378
- "metadata": {},
1379
- "output_type": "display_data"
1380
- },
1381
- {
1382
- "data": {
1383
- "text/html": [
1384
- "<div>\n",
1385
- "<style scoped>\n",
1386
- " .dataframe tbody tr th:only-of-type {\n",
1387
- " vertical-align: middle;\n",
1388
- " }\n",
1389
- "\n",
1390
- " .dataframe tbody tr th {\n",
1391
- " vertical-align: top;\n",
1392
- " }\n",
1393
- "\n",
1394
- " .dataframe thead th {\n",
1395
- " text-align: right;\n",
1396
- " }\n",
1397
- "</style>\n",
1398
- "<table border=\"1\" class=\"dataframe\">\n",
1399
- " <thead>\n",
1400
- " <tr style=\"text-align: right;\">\n",
1401
- " <th></th>\n",
1402
- " <th>Model</th>\n",
1403
- " <th>True Negatives</th>\n",
1404
- " <th>False Positives</th>\n",
1405
- " <th>False Negatives</th>\n",
1406
- " <th>True Positives</th>\n",
1407
- " </tr>\n",
1408
- " </thead>\n",
1409
- " <tbody>\n",
1410
- " <tr>\n",
1411
- " <th>0</th>\n",
1412
- " <td>xgboost</td>\n",
1413
- " <td>364</td>\n",
1414
- " <td>2</td>\n",
1415
- " <td>26</td>\n",
1416
- " <td>0</td>\n",
1417
- " </tr>\n",
1418
- " </tbody>\n",
1419
- "</table>\n",
1420
- "</div>"
1421
- ],
1422
- "text/plain": [
1423
- " Model True Negatives False Positives False Negatives True Positives\n",
1424
- "0 xgboost 364 2 26 0"
1425
- ]
1426
- },
1427
- "metadata": {},
1428
- "output_type": "display_data"
1429
- },
1430
- {
1431
- "data": {
1432
- "image/png": "iVBORw0KGgoAAAANSUhEUgAAAbsAAAHACAYAAAA7jMYcAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjYuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8o6BhiAAAACXBIWXMAAA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Hx8fpuvLz81W1atVLXvdy5RT+WbNmafbs2ZozZ45CQkJUpkwZjRw5Urm5uU7V6uHhoejoaPs/In5XtmxZl9UKXAlhh2Jr+/btBbZvu+22An8h/1mzZs20f/9+1a1b95LvN2jQQBcuXNCOHTvUokULSVJcXNwV71tr3Lix5s2bp7S0tEuO7ry8vGS1WgvUkZKSIk9PT9WqVeuytWzfvl19+vRx+IzO2LRpk+677z499thjki4G16FDh9SgQQOHflf6LkNDQ2W1WpWamqq2bds69fMBV2GCCoqtY8eOafTo0YqLi9OyZcv05ptvasSIEVfcZ8KECdq2bZueeuopxcTE6NChQ1q5cqWGDRsmSapfv766dOmiQYMGKSoqStHR0Xr88cevOHp75JFHVKVKFfXo0UNbtmzRkSNH9Omnn2rbtm2SLs4KPXr0qGJiYnTq1Cnl5OSoU6dOCg8PV48ePfTtt98qPj5eW7du1bPPPqsdO3ZIkkaMGKEFCxZowYIFOnjwoCZPnqz9+/c79R3VrVtXa9as0datWxUbG6shQ4YoJSXFqe+yXr16evTRR9WnTx999tlnOnr0qH766SdNmzZNq1evdqoe4FoRdii2+vTpo+zsbLVo0UJPPfWUhg0bpsGDB19xn8aNG2vDhg06dOiQ2rZtq9DQUE2aNElVq1a191m4cKGCgoJ055136v7777ffHnA5Xl5e+u677+Tv76+7775bISEhmjp1qn2E2bNnT3Xp0kUdOnTQLbfcomXLlslisWj16tVq166dBgwYoHr16unhhx9WfHy8AgICJEm9evXSc889pwkTJigsLEwJCQn697//7dR3NGnSJDVr1kyRkZFq3769PZSd/S4XLlyoPn36aMyYMapfv766d++uqKgoBQUFOVUPcK0sNtufboYBion27duradOmDo/wAmAuRnYAAOMRdgAA43EaEwBgPEZ2AADjEXYAAOMRdgAA4xF2AADjEXYAAOMRdgAA4xF2AADjEXYAAOMRdgAA4/1/xkaefWGzS6YAAAAASUVORK5CYII=",
1433
- "text/plain": [
1434
- "<Figure size 500x500 with 1 Axes>"
1435
- ]
1436
- },
1437
- "metadata": {},
1438
- "output_type": "display_data"
1439
- }
1440
- ],
1441
- "source": [
1442
- "evaluation_score_output, evaluation_counts_output = evaluate_models(input_model)\n",
1443
- "\n",
1444
- "# check if the model has already been evaluated and if not, append the results to the dataframe\n",
1445
- "\n",
1446
- "evaluation_score_df = pd.concat([evaluation_score_output, evaluation_score_df], ignore_index=True) \n",
1447
- "display(pd.DataFrame(evaluation_score_output))\n",
1448
- "\n",
1449
- "evaluation_count_df = pd.concat([evaluation_counts_output, evaluation_count_df], ignore_index=True) \n",
1450
- "display(pd.DataFrame(evaluation_counts_output))\n",
1451
- "\n",
1452
- "from mlxtend.plotting import plot_confusion_matrix\n",
1453
- "\n",
1454
- "# select the model index and filter the row from evaluation_count_df dataframe\n",
1455
- "model_index = 0\n",
1456
- "\n",
1457
- "selected_model = evaluation_count_df[evaluation_count_df.index == model_index]\n",
1458
- "\n",
1459
- "# create a np.array with selected_model values\n",
1460
- "\n",
1461
- "\n",
1462
- "conf_matrix = np.array([[selected_model['True Negatives'].values[0], selected_model['False Positives'].values[0]],\n",
1463
- " [selected_model['False Negatives'].values[0], selected_model['True Positives'].values[0]]])\n",
1464
- "\n",
1465
- "#change the size of the graph\n",
1466
- "\n",
1467
- "plt.rcParams['figure.figsize'] = [5, 5]\n",
1468
- "\n",
1469
- "fig, ax = plot_confusion_matrix(\n",
1470
- " conf_mat=conf_matrix,\n",
1471
- " show_absolute=True,\n",
1472
- " show_normed=True\n",
1473
- ")"
1474
- ]
1475
- },
1476
- {
1477
- "cell_type": "code",
1478
- "execution_count": 34,
1479
- "metadata": {
1480
- "slideshow": {
1481
- "slide_type": "slide"
1482
- }
1483
- },
1484
- "outputs": [
1485
- {
1486
- "name": "stdout",
1487
- "output_type": "stream",
1488
- "text": [
1489
- "Have the duplicates been removed? yes\n",
1490
- "What is the missing values threshold? 80\n",
1491
- "What is the variance threshold? 0.0\n",
1492
- "How many features have been removed? 145\n",
1493
- "---------------------\n",
1494
- "What is the outlier removal threshold? none\n",
1495
- "How many outliers have been removed? 0\n",
1496
- "---------------------\n",
1497
- "What is the scaling method? none\n",
1498
- "---------------------\n",
1499
- "What is the imputation method? mean\n",
1500
- "---------------------\n",
1501
- "What is the feature selection method? none\n",
1502
- "What is the number of features selected? 445\n",
1503
- "---------------------\n",
1504
- "What is the imbalance treatment method? none\n",
1505
- "---------------------\n",
1506
- "What is the model? xgboost\n"
1507
- ]
1508
- }
1509
- ],
1510
- "source": [
1511
- "print('Have the duplicates been removed?', drop_duplicates_var)\n",
1512
- "print('What is the missing values threshold?', missing_values_threshold_var)\n",
1513
- "print('What is the variance threshold?', variance_threshold_var)\n",
1514
- "print('How many features have been removed?', len(dropped))\n",
1515
- "print('---------------------')\n",
1516
- "print('What is the outlier removal threshold?', outlier_var)\n",
1517
- "print('How many outliers have been removed?', len(X_train2) - len(X_train_dropped_outliers))\n",
1518
- "print('---------------------')\n",
1519
- "print('What is the scaling method?', scale_model_var)\n",
1520
- "print('---------------------')\n",
1521
- "print('What is the imputation method?', imputation_var)\n",
1522
- "print('---------------------')\n",
1523
- "print('What is the feature selection method?', feature_selection_var)\n",
1524
- "print('What is the number of features selected?', len(selected_features))\n",
1525
- "print('---------------------')\n",
1526
- "print('What is the imbalance treatment method?', imbalance_var)\n",
1527
- "print('---------------------')\n",
1528
- "print('What is the model?', input_model)"
1529
- ]
1530
- }
1531
- ],
1532
- "metadata": {
1533
- "kernelspec": {
1534
- "display_name": "Python 3 (ipykernel)",
1535
- "language": "python",
1536
- "name": "python3"
1537
- },
1538
- "language_info": {
1539
- "codemirror_mode": {
1540
- "name": "ipython",
1541
- "version": 3
1542
- },
1543
- "file_extension": ".py",
1544
- "mimetype": "text/x-python",
1545
- "name": "python",
1546
- "nbconvert_exporter": "python",
1547
- "pygments_lexer": "ipython3",
1548
- "version": "3.9.16"
1549
- }
1550
- },
1551
- "nbformat": 4,
1552
- "nbformat_minor": 2
1553
- }