-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPredicting_CC_Fraud_WorkingFile.Rmd
683 lines (450 loc) · 23.4 KB
/
Predicting_CC_Fraud_WorkingFile.Rmd
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
---
title: "Predicting Credit Card Fraud"
output:
html_document:
toc: true
toc_float: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Task 1: Project Objective
* The objective of this project is to predict which credit card transactions in the dataset are fraudulent using three classification algorithms and three synthetic balancing techniques. The three classifier algorithms we will train include Decision Tree, Naive Bayes,and Linear Discriminant Analysis.
* Given that the objective is to evaluate the model performance of the three classifier algorithms and synthetic balancing techniques, we will not be thoroughly reviewing the model output, but rather will be focusing on the classification performance results.
* Lets start by loading the R library packages that will be used in this project, which are the caret, corrplot, and smotefamily packages.
```{r, echo=TRUE, results='hide'}
#Load the packages used in the project
library(caret)
library(corrplot)
library(smotefamily)
```
### Task 1.1: Import the dataset from Dropbox
Next, using the "read.csv" function, we will import the credit card fraud dataset and set the class to a factor. This dataset is a subset of the dataset from sourced from https://www.kaggle.com/mlg-ulb/creditcardfraud, which includes anonymized credit card transactions.
```{r}
#A. Load the dataset
creditcardFraud <- read.csv("Predicting Credit Card Fraud/creditcardFraud.csv")
#B. Change class to factor the as.factor function encodes the vector as a factor or category
creditcardFraud$class<-as.factor(creditcardFraud$class)
```
## Task 2: Explore The Data
* Now that we have downloaded the data we can start the training of the models, but it is important that we first understand and explore our data as it helps us identify potential data quality issues and it provides us the needed context to develop an appropriate model.
* In this project, we will briefly explore the data and perform a high-level exploratory data analysis (EDA) of the dataset
```{r}
#A. Structure of the dataset
str(creditcardFraud)
#B. Missing data?
sum(is.na(creditcardFraud))
#C. Check the imbalance in the dataset
summary(creditcardFraud$class)
prop.table(table(creditcardFraud$class))
#D. Compile histograms for each variable
par(mfrow = c(3,5)) #Change setting to view 3x5 charts
i <- 1
for (i in 1:30)
{hist((creditcardFraud[,i]), main = paste("Distibution of ", colnames(creditcardFraud[i])), xlab = colnames(creditcardFraud[i]), col = "light blue")
}
```
```{r}
#E. Compute the correlations among the variables
r <- cor(creditcardFraud[,1:30])
corrplot(r,type="lower",tl.col = 'black', tl.srt = 15)
```
## Task 3: Split the Data into Training and Test Sets
It is important that when we evaluate the performance of a model, we do so on a dataset that the model has not previously seen. Therefore, we will split our dataset into a training dataset and a test dataset and to maintain the same level of imbalance as in the original dataset, we will use stratified sampling by "class."
```{r}
#A. Split data into training and testing dataset used for model building (training dataset)
set.seed(1337)
train <- createDataPartition(creditcardFraud$class,
p = 0.70,
times = 1,
list = FALSE)
train.orig <- creditcardFraud[train,]
test <- creditcardFraud[-train,]
#B. Check the proportion of observations allocated to each group
dim(train.orig)/dim(creditcardFraud)
dim(test)/dim(creditcardFraud)
#C. Class balance for training dataset
prop.table(table(train.orig$class))
#D. Class balance for test dataset
prop.table(table(test$class))
```
## Task 4: Compile Synthetically Balanced Training Datsets
Now that we have split our dataset into a training and test dataset, lets create three new synthetically balanced datasets from the one imbalanced training dataset. To do this we will be using the "smotefamily" R package and we will be trying out three different techniques: SMOTE, ADASYN, and DB-SMOTE.
```{r, echo=TRUE, results='asis', include=TRUE}
#SMOTE Balanced
train.smote <- SMOTE(train.orig[,-31],train.orig[,31],K=5)
names(train.smote)
train.smote <- train.smote$data
train.smote$class <- as.factor(train.smote$class)
#ADASYN Balanced
train.adas <- ADAS(train.orig[,-31],train.orig[,31],K=5)
train.adas <- train.adas$data
train.adas$class <- as.factor(train.adas$class)
#Density based SMOTE
train.dbsmote <- DBSMOTE(train.orig[,-31],train.orig[,31])
train.dbsmote <- train.dbsmote$data
train.dbsmote$class <- as.factor(train.dbsmote$class)
```
### Task 4.1: Evaluate Class distributions for Synthetic datasets
```{r}
#Class Distribution of SMOTE Balanced Dataset
prop.table(table(train.smote$class))
#Class Distribution of ADASYN Balanced Dataset
prop.table(table(train.adas$class))
#Class Distribution of DB SMOTE Balanced Dataset
prop.table(table(train.dbsmote$class))
```
## Task 5: Original Data: Train Decision Tree, Naive Bayes, and LDA Models
Now that we have our four training datasets;
1. the original imbalanced training dataset,
2. the SMOTE balanced training dataset,
3. the ADASYN balanced training dataset, and
4. the DB-SMOTE balanced training dataset,
We will use the 'caret' package to train three classifier models (decision tree, naive Bayes, linear discriminant analysis). Lets start by fitting the three classifier models using the original imbalanced training dataset. We will use repeated 10x cross validation for our models across all of our trained models.
```{r}
#A. Global options that we will use across all of our trained models
ctrl <- trainControl(method = "cv",
number = 10,
classProbs = TRUE,
summaryFunction = twoClassSummary)
#B. Decision Tree: original data
dt_orig <- train(class~.,
data = train.orig,
method = "rpart",
trControl = ctrl,
metric = "ROC")
#C. Naive Bayes regression: original data
nb_orig <- train(class~.,
data = train.orig,
method = "naive_bayes",
trControl = ctrl,
metric = "ROC")
#D. Linear Discriminant Analysis: original data
lda_orig <- train(class~.,
data = train.orig,
method = "lda",
trControl = ctrl,
metric = "ROC")
```
### Task 5.1: Compile Classifications on Test Data using models trained on the original imbalanced training dataset
Next, we will use the models we have trained using the original imbalanced training dataset to generate predictions on the test dataset.
We will then compile three measures of performance, which we will use to compare the performance of the models across all of our trained models.
```{r}
###################################################
#Decision Tree Model - Trained on original dataset#
###################################################
#A. Decision Tree Model predictions
dt_orig_pred <- predict(dt_orig, test, type = "prob")
#B. Decision Tree - Assign class to probabilities
dt_orig_test <- factor(ifelse(dt_orig_pred$yes>0.50, "yes", "no"))
#C. Decision Tree Save Precision/Recall/F
precision_dtOrig <- posPredValue(dt_orig_test,test$class, positive = "yes")
recall_dtOrig <- sensitivity(dt_orig_test, test$class, positive = "yes")
F1_dtOrig <- (2*precision_dtOrig*recall_dtOrig)/(precision_dtOrig+recall_dtOrig)
#################################################
#Naive Bayes Model - Trained on original dataset#
#################################################
#A. NB Model predictions
nb_orig_pred <- predict(nb_orig, test, type = "prob")
#B. NB - Assign class to probabilities
nb_orig_test <- factor(ifelse(nb_orig_pred$yes>0.50, "yes", "no"))
#C. NB Save Precision/Recall/F
precision_nbOrig <- posPredValue(nb_orig_test,test$class, positive = "yes")
recall_nbOrig <- sensitivity(nb_orig_test, test$class, positive = "yes")
F1_nbOrig <- (2*precision_nbOrig*recall_nbOrig)/(precision_nbOrig+recall_nbOrig)
#########################################
#LDA Model - Trained on original dataset#
#########################################
#A. LDA Model predictions
lda_orig_pred <- predict(lda_orig, test, type = "prob")
#B. LDA - Assign class to probabilities
lda_orig_test <- factor(ifelse(lda_orig_pred$yes>0.50, "yes", "no"))
#C. LDA Save Precision/Recall/F
precision_ldaOrig <- posPredValue(lda_orig_test,test$class, positive = "yes")
recall_ldaOrig <- sensitivity(lda_orig_test, test$class, positive = "yes")
F1_ldaOrig <- (2*precision_ldaOrig*recall_ldaOrig)/(precision_ldaOrig+recall_ldaOrig)
```
## Task 6: SMOTE Balanced Data: Train Decision Tree, Naive Bayes, and LDA Models
Next, We will train the three classifier models using the SMOTE balanced training dataset.
```{r}
#A. Decision Tree: SMOTE data
dt_smote <- train(class~.,
data = train.smote,
method = "rpart",
trControl = ctrl,
metric = "ROC")
#B. Naive Bayes regression: SMOTE data
nb_smote <- train(class~.,
data = train.smote,
method = "naive_bayes",
trControl = ctrl,
metric = "ROC")
#C. Linear Discriminant Analysis: SMOTE data
lda_smote <- train(class~.,
data = train.smote,
method = "lda",
trControl = ctrl,
metric = "ROC")
```
### Task 6.1: Compile predictions using models trained on the SMOTE balanced training dataset
Next, we will use the models we have trained using the SMOTE balanced training dataset to generate predictions on the test dataset, and we will compute our three performance measures.
```{r}
################################################
#Decision Tree Model - Trained on SMOTE dataset#
################################################
#A. Decision Tree Model predictions
dt_smote_pred <- predict(dt_smote, test, type = "prob")
#B. Decision Tree - Assign class to probabilities
dt_smote_test <- factor(ifelse(dt_smote_pred$yes>0.50, "yes", "no"))
#C. Decision Tree Save Precision/Recall/F
precision_dtsmote <- posPredValue(dt_smote_test,test$class, positive = "yes")
recall_dtsmote <- sensitivity(dt_smote_test, test$class, positive = "yes")
F1_dtsmote <- (2*precision_dtsmote*recall_dtsmote)/(precision_dtsmote+recall_dtsmote)
##############################################
#Naive Bayes Model - Trained on SMOTE dataset#
##############################################
#A. NB Model predictions
nb_smote_pred <- predict(nb_smote, test, type = "prob")
#B. NB - Assign class to probabilities
nb_smote_test <- factor(ifelse(nb_smote_pred$yes>0.50, "yes", "no"))
#C. NB Save Precision/Recall/F
precision_nbsmote <- posPredValue(nb_smote_test,test$class, positive = "yes")
recall_nbsmote <- sensitivity(nb_smote_test, test$class, positive = "yes")
F1_nbsmote <- (2*precision_nbsmote*recall_nbsmote)/(precision_nbsmote+recall_nbsmote)
######################################
#LDA Model - Trained on SMOTE dataset#
######################################
#A. LDA Model predictions
lda_smote_pred <- predict(lda_smote, test, type = "prob")
#B. LDA - Assign class to probabilities
lda_smote_test <- factor(ifelse(lda_smote_pred$yes>0.50, "yes", "no"))
#C. LDA Save Precision/Recall/F
precision_ldasmote <- posPredValue(lda_smote_test,test$class, positive = "yes")
recall_ldasmote <- sensitivity(lda_smote_test, test$class, positive = "yes")
F1_ldasmote <- (2*precision_ldasmote*recall_ldasmote)/(precision_ldasmote+recall_ldasmote)
```
## Task 7: ADASYN Balanced Data: Train Decision Tree, Naive Bayes, and LDA Models
We will train the three classifier models using the ADASYN balanced training dataset.
```{r}
#A. Decision Tree: ADASYN data
dt_adas <- train(class~.,
data = train.adas,
method = "rpart",
trControl = ctrl,
metric = "ROC")
#B. Naive Bayes regression: ADASYN data
nb_adas <- train(class~.,
data = train.adas,
method = "naive_bayes",
trControl = ctrl,
metric = "ROC")
#C. Linear Discriminant Analysis: ADASYN data
lda_adas <- train(class~.,
data = train.adas,
method = "lda",
trControl = ctrl,
metric = "ROC")
```
### Task 7.1: Compile predictions using models trained on the ADASYN balanced training dataset
Next, we will use the models we have trained using the ADASYN balanced training dataset to generate predictions on the test dataset, and we will compute our three performance measures.
```{r}
#################################################
#Decision Tree Model - Trained on ADASYN dataset#
#################################################
#A. Decision Tree Model predictions
dt_adas_pred <- predict(dt_adas, test, type = "prob")
#B. Decision Tree - Assign class to probabilities
dt_adas_test <- factor(ifelse(dt_adas_pred$yes>0.50, "yes", "no"))
#C. Decision Tree Save Precision/Recall/F
precision_dtadas <- posPredValue(dt_adas_test,test$class, positive = "yes")
recall_dtadas <- sensitivity(dt_adas_test, test$class, positive = "yes")
F1_dtadas <- (2*precision_dtadas*recall_dtadas)/(precision_dtadas+recall_dtadas)
###############################################
#Naive Bayes Model - Trained on ADASYN dataset#
###############################################
#A. NB Model predictions
nb_adas_pred <- predict(nb_adas, test, type = "prob")
#B. NB - Assign class to probabilities
nb_adas_test <- factor(ifelse(nb_adas_pred$yes>0.50, "yes", "no"))
#C. NB Save Precision/Recall/F
precision_nbadas <- posPredValue(nb_adas_test,test$class, positive = "yes")
recall_nbadas <- sensitivity(nb_adas_test, test$class, positive = "yes")
F1_nbadas <- (2*precision_nbadas*recall_nbadas)/(precision_nbadas+recall_nbadas)
#######################################
#LDA Model - Trained on ADASYN dataset#
#######################################
#A. LDA Model predictions
lda_adas_pred <- predict(lda_adas, test, type = "prob")
#B. LDA - Assign class to probabilities
lda_adas_test <- factor(ifelse(lda_adas_pred$yes>0.50, "yes", "no"))
#C. LDA Save Precision/Recall/F
precision_ldaadas <- posPredValue(lda_adas_test,test$class, positive = "yes")
recall_ldaadas <- sensitivity(lda_adas_test, test$class, positive = "yes")
F1_ldaadas <- (2*precision_ldaadas*recall_ldaadas)/(precision_ldaadas+recall_ldaadas)
```
## Task 8: DB-SMOTE Balanced Data: Train Decision Tree, Naive Bayes, and LDA Models
In task 8, we will train the three classifier models using the DB-SMOTE balanced training dataset.
```{r}
#A. Decision Tree: dbsmote data
dt_dbsmote <- train(class~.,
data = train.dbsmote,
method = "rpart",
trControl = ctrl,
metric = "ROC")
#B. Naive Bayes regression: dbsmote data
nb_dbsmote <- train(class~.,
data = train.dbsmote,
method = "naive_bayes",
trControl = ctrl,
metric = "ROC")
#C. Linear Discriminant Analysis: dbsmote data
lda_dbsmote <- train(class~.,
data = train.dbsmote,
method = "lda",
trControl = ctrl,
metric = "ROC")
```
### Task 8.1: Compile predictions using models trained on the DB SMOTE balanced training dataset
Next, we will use the models we have trained using the DB-SMOTE balanced training dataset to generate predictions on the test dataset, and we will compute our three performance measures.
```{r}
###################################################
#Decision Tree Model - Trained on DB SMOTE dataset#
###################################################
#A. Decision Tree Model predictions
dt_dbsmote_pred <- predict(dt_dbsmote, test, type = "prob")
#B. Decision Tree - Assign class to probabilities
dt_dbsmote_test <- factor(ifelse(dt_dbsmote_pred$yes>0.50, "yes", "no"))
#C. Decision Tree Save Precision/Recall/F
precision_dtdbsmote <- posPredValue(dt_dbsmote_test,test$class, positive = "yes")
recall_dtdbsmote <- sensitivity(dt_dbsmote_test, test$class, positive = "yes")
F1_dtdbsmote <- (2*precision_dtdbsmote*recall_dtdbsmote)/(precision_dtdbsmote+recall_dtdbsmote)
###############################################
#Naive Bayes Model - Trained on DB SMOTE dataset#
###############################################
#A. NB Model predictions
nb_dbsmote_pred <- predict(nb_dbsmote, test, type = "prob")
#B. NB - Assign class to probabilities
nb_dbsmote_test <- factor(ifelse(nb_dbsmote_pred$yes>0.50, "yes", "no"))
#C. NB Save Precision/Recall/F
precision_nbdbsmote <- posPredValue(nb_dbsmote_test,test$class, positive = "yes")
recall_nbdbsmote <- sensitivity(nb_dbsmote_test, test$class, positive = "yes")
F1_nbdbsmote <- (2*precision_nbdbsmote*recall_nbdbsmote)/(precision_nbdbsmote+recall_nbdbsmote)
#######################################
#LDA Model - Trained on DB SMOTE dataset#
#######################################
#A. LDA Model predictions
lda_dbsmote_pred <- predict(lda_dbsmote, test, type = "prob")
#B. LDA - Assign class to probabilities
lda_dbsmote_test <- factor(ifelse(lda_dbsmote_pred$yes>0.50, "yes", "no"))
#C. LDA Save Precision/Recall/F
precision_ldadbsmote <- posPredValue(lda_dbsmote_test,test$class, positive = "yes")
recall_ldadbsmote <- sensitivity(lda_dbsmote_test, test$class, positive = "yes")
F1_ldadbsmote <- (2*precision_ldadbsmote*recall_ldadbsmote)/(precision_ldadbsmote+recall_ldadbsmote)
```
## Task 9: Compare the model performance
We will compare the recall, precision, and F1 performance measures for each of the three models we trained using the four training datasets:
1. original imbalanced,
2. SMOTE balanced,
3. ADASYN balanced, and
4. DB SMOTE balanced.
Recall that the most important performance measure for the fraud problem is the recall, which measures how complete our results are indicating the model captures more of the fraudulent transactions.
```{r}
#Lets reset the chart settings so we see one chart at a time
par(mfrow = c(1,1))
#Compare the Recall of the models: TP / TP + FN.
model_compare_recall <- data.frame(Model = c('DT-Orig',
'NB-Orig',
'LDA-Orig',
'DT-SMOTE',
'NB-SMOTE',
'LDA-SMOTE',
'DT-ADASYN',
'NB-ADASYN',
'LDA-ADASYN',
'DT-DBSMOTE',
'NB-DBSMOTE',
'LDA-DBSMOTE' ),
Recall = c(recall_dtOrig,
recall_nbOrig,
recall_ldaOrig,
recall_dtsmote,
recall_nbsmote,
recall_ldasmote,
recall_dtadas,
recall_nbadas,
recall_ldaadas,
recall_dtdbsmote,
recall_nbdbsmote,
recall_ldadbsmote))
ggplot(aes(x=reorder(Model,-Recall) , y=Recall), data=model_compare_recall) +
geom_bar(stat='identity', fill = 'light blue') +
ggtitle('Comparative Recall of Models on Test Data') +
xlab('Models') +
ylab('Recall Measure')+
geom_text(aes(label=round(Recall,2)))+
theme(axis.text.x = element_text(angle = 40))
#Compare the Precision of the models: TP/TP+FP
model_compare_precision <- data.frame(Model = c('DT-Orig',
'NB-Orig',
'LDA-Orig',
'DT-SMOTE',
'NB-SMOTE',
'LDA-SMOTE',
'DT-ADASYN',
'NB-ADASYN',
'LDA-ADASYN',
'DT-DBSMOTE',
'NB-DBSMOTE',
'LDA-DBSMOTE' ),
Precision = c(precision_dtOrig,
precision_nbOrig,
precision_ldaOrig,
precision_dtsmote,
precision_nbsmote,
precision_ldasmote,
precision_dtadas,
precision_nbadas,
precision_ldaadas,
precision_dtdbsmote,
precision_nbdbsmote,
precision_ldadbsmote))
ggplot(aes(x=reorder(Model,-Precision) , y=Precision), data=model_compare_precision) +
geom_bar(stat='identity', fill = 'light green') +
ggtitle('Comparative Precision of Models on Test Data') +
xlab('Models') +
ylab('Precision Measure')+
geom_text(aes(label=round(Precision,2)))+
theme(axis.text.x = element_text(angle = 40))
#Compare the F1 of the models: 2*((Precision*Recall) / (Precision + Recall))
model_compare_f1 <- data.frame(Model = c('DT-Orig',
'NB-Orig',
'LDA-Orig',
'DT-SMOTE',
'NB-SMOTE',
'LDA-SMOTE',
'DT-ADASYN',
'NB-ADASYN',
'LDA-ADASYN',
'DT-DBSMOTE',
'NB-DBSMOTE',
'LDA-DBSMOTE' ),
F1 = c(F1_dtOrig,
F1_nbOrig,
F1_ldaOrig,
F1_dtsmote,
F1_nbsmote,
F1_ldasmote,
F1_dtadas,
F1_nbadas,
F1_ldaadas,
F1_dtdbsmote,
F1_nbdbsmote,
F1_ldadbsmote))
ggplot(aes(x=reorder(Model,-F1) , y=F1), data=model_compare_f1) +
geom_bar(stat='identity', fill = 'light grey') +
ggtitle('Comparative F1 of Models on Test Data') +
xlab('Models') +
ylab('F1 Measure')+
geom_text(aes(label=round(F1,2)))+
theme(axis.text.x = element_text(angle = 40))
```