-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtidy_fraud_prediction.Rmd
858 lines (683 loc) · 26.5 KB
/
tidy_fraud_prediction.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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
---
title: "Tidymodels workflow example - fraud prediction"
author: "Alex Farach"
date: "9/30/2021"
output: html_document
---
```{r setup, include=FALSE}
library(knitr)
knitr::opts_chunk$set(
cache = TRUE,
cache.lazy = TRUE,
warning = FALSE,
message = FALSE,
dpi = 180,
fig.width = 8,
fig.height = 5,
echo = TRUE
)
library(tidyverse)
theme_set(theme_minimal())
```
# Contact
If you have any questions feel free to reach out to me: [email protected]
Learn more about Accenture Applied Intelligence here: https://www.accenture.com/us-en/services/us-federal-government/artificial-intelligence
# Typical steps in a machine learning project ----------------------------------
Adapted from the excellent "Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow": https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/
1. Get the data (tidyverse)
2. Explore the data (tidyverse, tidymodels)
- Study attributes
- name
- types
- missing values
- noisiness (stochastic, outliers, etc)
- Usefulness
- Distributions (uniform, logarithmic, etc.)
- Identify the dependent variable
- Visualize the data
- Review correlations
3. Prep the data
- Clean-up
- Fix or remove outliers
- Fill in missing values or drop them.
- Feature selection (maybe). Drop features that provide no useful info.
- Feature engineering (maybe). Bucketing continuous variables, add
transformations (log, sqrts, etc.). Create new features like recency if
dealing with time features.
- Feature scaling (maybe). Normalize/standardize
4. Shortlist promising models
- Train a bunch of quick and dirty models from different categories (e.g.
linear, naive Bayes, SVM, random forest, neural net, etc.)
- Measure and compare performance (use validation folds)
- Analyze results
- Significant variables
- Errors
- Quick round of feature selection and engineering.
- Repeat above steps a couple of times.
- Pick best model/s
5. Fine-tuning
- Hyperparameter tuning using cross-validation
- Ensemble methods (maybe)
- Once confident about the final model, measure performance on test set.
6. Present results (Rmarkdown/Shiny dashboard)
7. Deploy model (rplumber/docker)
In the example that follows I slowly add different elements of this whole list
in order to present the tidymodels machine learning approach in a more
digestible form.
I will introduce concepts one by one and slowly build on each topic.
Eventually, most everything above will be covered. This is to say what follows
is not the proper way to build a machine learning model - it's the way I find
it easiest to learn about tidymodels and machine learning pipelines generally.
Some other helpful resources:
-tidymodels.org: https://www.tidymodels.org/
-Tidy Modeling with R: https://www.tmwr.org/
-Supervised Machine Learning for Text Analysis in R: https://smltar.com/
# Tidymodels approach
## Get the data
The following table comes from the kaggle dataset:
https://www.kaggle.com/ntnu-testimon/paysim1
```{r load data}
# Import the data
fraud_data <- read_csv("./example_data/fraud_example.csv")
glimpse(fraud_data)
```
## Explore the data
```{r}
# Look at counts
fraud_data %>%
group_by(isFraud) %>%
summarise(
n = n()
) %>%
ungroup()
# Get percentages
fraud_data %>%
count(isFraud) %>%
mutate(per_n = scales::percent(n/sum(n), accuracy = 0.01))
```
## Format the data
```{r clean data}
library(tidymodels)
# Clean data a bit
fraud_model_data <-
fraud_data %>%
select(
isFraud, step, type, amount, oldbalanceOrg, newbalanceOrig, oldbalanceDest,
newbalanceDest
) %>%
mutate(
isFraud = as.factor(ifelse(isFraud == 1, 0, 1))
) %>%
mutate_if(is.character, as.factor)
# Set seed for reproducibility
set.seed(2021)
# sample the data
fraud_model_data <- fraud_model_data %>%
sample_frac(0.03)
# Get percentages
fraud_model_data %>%
count(isFraud) %>%
mutate(per_n = scales::percent(n/sum(n), accuracy = 0.01))
```
## Create split, train, and test datasets
Here we are just creating a training and testing split. If you wanted to you
could split the training data further to get a validation set using the `mc_cv()`
function in the `rsample` package. This is a good practice but for the sake of
simplicity I am omitting here.
It's also a good practice to split the data earlier so that steps taken in the
cleaning part of the machine learning process could be replicated in a ML
pipeline.
```{r set up train/test}
# Set seed for reproducibility
set.seed(2021)
# Create initial split
fraud_split <- initial_split(fraud_model_data, prop = 0.75, strata = isFraud)
# Assign the trainging set
fraud_train <- training(fraud_split)
# Assign the test set
fraud_test <- testing(fraud_split)
# Print out the size of training and testing sets
print(paste("Size of training data:", nrow(fraud_train)))
print(paste("Size of testing data:", nrow(fraud_test)))
```
# Modeling V1
Ideally you would want to use more than 2 models but here I will just present
2 for the sake of simplicity: a logistic model and a decision tree model. Both
will work for our binary (fraud/not fraud) model. For a multiclass
classification problem we could do xgboost or ranger random forests. If we were
doing text classification models we could look to a regularized regression model.
There are A LOT of options depending on the problem. Here is a useful cheat
sheet for figuring out which machine learning algorithm to use:
"https://blogs.sas.com/content/subconsciousmusings/2020/12/09/machine-learning-algorithm-use/#prettyPhoto/0/"
If you would like to see all the models in Tidymodels you can do so by going to
this link: "https://www.tidymodels.org/find/parsnip/"
## Specify the model - simple logistic regression
```{r specify_lg_simple}
# Specify a logistic regression model
logistic_model <- logistic_reg() %>%
# Set the engine
set_engine('glm') %>%
# Set the mode
set_mode('classification')
# Print the model specification
logistic_model
```
## Fit the model to the training data
```{r fit_lg_simple}
# Fit to training data
logistic_fit <- logistic_model %>%
fit(isFraud ~ ., data = fraud_train)
# Print model fit object
logistic_fit
```
## Combine test dataset results
```{r combine_lg_simple_pred}
# Predict outcome categories
class_preds <- predict(logistic_fit, new_data = fraud_test,
type = 'class')
# Obtain estimated probabilities for each outcome value
prob_preds <- predict(logistic_fit, new_data = fraud_test,
type = 'prob')
# Combine test set results
fraud_results <- fraud_test %>%
select(isFraud) %>%
bind_cols(class_preds, prob_preds)
# View results tibble
fraud_results
```
## Evaluate performance
```{r evaluate_lg_simple}
# Create custom metric set to evaluate performance.
custom_metrics <- metric_set(accuracy, sens, spec, precision, recall, f_meas)
# Print out the custom metrics results
custom_metrics(fraud_results, truth = isFraud, estimate = .pred_class)
# Here are all the available metrics
conf_mat(fraud_results, truth = isFraud, estimate = .pred_class) %>%
summary()
```
## Detour to talk about performance metrics
Which performance metric you decide to optimize has implications for which model
you want to use and how to tune said chosen model. It's worthwhile to do a quick
review of them.
The following was adapted from this excellent post by S.Ghoneim:
https://towardsdatascience.com/accuracy-recall-precision-f-score-specificity-which-to-optimize-on-867d3f11124
### Accuracy
The ratio of the correctly labeled subjects to the whole pool of subjects.
Accuracy = (TP+TN)/(TP+FP+FN+TN)
How many fraudsters did we correctly label out of all the fraudsters?
```{r}
accuracy(fraud_results, truth = isFraud, estimate = .pred_class)
```
### Precision
The ratio of the correctly positive labeled by our program to all positive
labeled.
Precision = TP/(TP+FP)
How many of those who we labeled as fraudsters are actually fraudsters?
```{r}
precision(fraud_results, truth = isFraud, estimate = .pred_class)
```
### Recall (aka Sensitivity)
Recall is the ratio of the correctly positive labeled by our program to all who
are fraudulent in reality.
Recall = TP/(TP+FN)
Of all the transactions that are fraudulent, how many of those did we correctly
predict?
```{r}
recall(fraud_results, truth = isFraud, estimate = .pred_class)
```
### Specificity
Specificity is the correctly negative labeled by the program to all who are
fraudsters in reality.
Specificity = TN/(TN+FP)
Of all the legitimate transactions, how many of those did we correctly predict?
```{r}
specificity(fraud_results, truth = isFraud, estimate = .pred_class)
```
### F1-score (aka F-Score / F-Measure)
F1 Score considers both precision and recall.
It is the harmonic mean(average) of the precision and recall.
F1 Score = 2*(Recall * Precision) / (Recall + Precision)
F1 Score is best if there is some sort of balance between precision (p) & recall
(r) in the system. Oppositely F1 Score isn’t so high if one measure is improved
at the expense of the other.
```{r}
f_meas(fraud_results, truth = isFraud, estimate = .pred_class)
```
So which should we choose? In this case we want to optimize recall and the
f-measure.
A focus on recall because we would rather get some extra false positives over
saving some false negatives. We would rather label some legitimate transactions
as fraudulent over missing actual, real fraudulent transactions.
The f-measure takes into consideration recall but also considers precision.
Precision is how sure we are of our true positives. Recall is how sure we are
that we are not missing any positives.
## Visual evaluation - confusion matrix, ROC curve and area under ROC curve
```{r eval_lg_simple_viz}
# Create confusion matrix to see TP, FP, TN, and FN results
fraud_results %>%
conf_mat(truth = isFraud, estimate = .pred_class) %>%
autoplot('heatmap')
# Plot roc_curve
fraud_results %>%
roc_curve(truth = isFraud, estimate = .pred_0) %>%
autoplot() +
labs(
x = "1-specificity\n(proportion of false positives\namong true negatives)",
y = "sensitivity\n(proportion of all positive cases that\nwere correctly classfied)"
)
# Print out the AUC of the ROC curve
roc_auc(fraud_results, truth = isFraud, .pred_0)
```
## Complete the model training process
Our approach thus far has been really simple. We only used a single training
set. Later on I'll show you how to use validation folds and I mentioned the use
of a validation set above which would add some complications to these first
model training steps.
Let's say we were happy here though. The last fit will fit the best model to the
training set and evaluate on the test set which is why we pass the fraud_split
data to the function and not just the training or the testing set.
```{r lg_simple_wf}
# Train model with last fit
fraud_last_fit <- logistic_model %>%
last_fit(isFraud ~ ., split = fraud_split)
# Collect predictions
last_fit_results <- fraud_last_fit %>%
collect_predictions()
# Custom metrics function
last_fit_metrics <- metric_set(accuracy, sens, spec, precision, recall, f_meas)
# Calculate metrics
last_fit_metrics(last_fit_results,
truth = isFraud,
estimate = .pred_class,
.pred_0)
# Plot roc_curve
last_fit_results %>%
roc_curve(truth = isFraud, .pred_0) %>%
autoplot() +
labs(
x = "1-specificity\n(proportion of false positives\namong true negatives)",
y = "sensitivity\n(proportion of all positive cases that\nwere correctly classfied)"
)
```
## Feature engineering
Here I will introduce how to do feature engineering with tidymodels. Let's start
with an easy example, looking for and removing highly correlated numeric
features.
```{r find correlations}
# Use the cor() function to find the correlated values
fraud_train %>%
select_if(is.numeric) %>%
cor()
```
```{r visualize correlations}
# Visualize the relationship in question
fraud_train %>%
ggplot(aes(oldbalanceDest , newbalanceDest)) +
geom_point(alpha = 0.5) +
theme_minimal()
```
In tidymodels all feature engineering functions start with `step_*()` which makes
it super easy to explore and deal with. Below I also introduce the `prep()` and
`bake()` functions which allows us to apply the feature engineering to the data.
```{r first pass at feature engineering}
# Specify a recipe object
fraud_cor_rec <- recipe(isFraud ~ ., data = fraud_train) %>%
# Remove correlated variables
step_corr(all_numeric(), threshold = 0.9)
# Train the recipe
fraud_cor_rec_prep <- fraud_cor_rec %>%
prep(training = fraud_train)
# Apply to training data
fraud_cor_rec_prep %>%
bake(new_data = NULL)
# Apply to test data
fraud_cor_rec_prep %>%
bake(new_data = fraud_test)
```
We can take it 1 step further and apply normalization, deal with the
non-numeric data, and then lastly deal with the class imbalance - will use the
`themis` library/package to apply SMOTE procedure for class imbalance.
If we wanted to do PCA, we can do it here by using `step_ica()`, `step_kpca()`,
or `step_pca()`
In the next step we bring in the `themis` package within tidymodels to use the
`step_smote()` function. This will address the class balance issue we discovered
when exploring the data.
The `recipes` package is extensive. Please see the documentation for the full
breadth of the recipes it has available. If you want to create your own recipe
instructions to do so are here: https://recipes.tidymodels.org/reference/recipe.html
```{r second pass at feature engineering}
# Load the themis package to use SMOTE (Synthetic Minority Over-sampling
# Technique). This package has add-on steps to deal with class imbalance.
library(themis)
# Specify a recipe object
fraud_norm_rec <- recipe(isFraud ~ ., data = fraud_train) %>%
# Remove correlated variables
step_corr(all_numeric(), threshold = 0.9) %>%
# Add log transformation step
step_log(all_numeric(), base = 10, offset = 0.01) %>%
# Normalize numeric predictors
step_normalize(all_numeric()) %>%
# Encode categorical data into numerical data
step_dummy(all_nominal(), -all_outcomes()) %>%
# Deal with class imbalance
step_smote(isFraud)
# Train the recipe using the new engineered features
fraud_test_prep <- fraud_norm_rec %>%
prep(training = fraud_train) %>%
bake(new_data = fraud_test)
fraud_train_prep <- fraud_norm_rec %>%
prep(training = fraud_train) %>%
bake(new_data = NULL)
fraud_norm_rec
fraud_test_prep
fraud_train_prep
```
## Fit and predict new cleaned up (feature engineered) data
```{r fit ft eng logistic model}
# Train logistic model
logistic_fit <- logistic_model %>%
fit(isFraud ~ ., data = fraud_train_prep)
# Obtain class predictions
class_preds <- predict(logistic_fit, new_data = fraud_test_prep, type = 'class')
# Obtain estimated probabilities
prob_preds <- predict(logistic_fit, new_data = fraud_test_prep, type = 'prob')
# Combine test set results
fraud_results <- fraud_test_prep %>%
select(isFraud) %>%
bind_cols(class_preds, prob_preds)
fraud_results
```
## Evaluate the model with feature engineered data
Here is when the performance metric we want to optimize really matters. Prior to
all the feature engineering, when we used that very basic logistic regression
model our false negatives were 18 and now they are 3,658! Our recall improved
but our f1 score suffered since our precision suffered.
Our true positives went from 24 to 56 though! This becomes a business decision.
Since these are fraudulent transactions we need to think about the difference
between these 2 numbers.
What happens when we suspect a fraudulent transaction? What happens when we miss
an actual fraudulent transaction? What costs more, dealing with the fallout
from cancelling a real transaction or dealing with the fallout of missing a real
fraud event?
Performance metrics matter.
```{r evaluate performance}
# Confusion matrix results
fraud_results %>%
conf_mat(truth = isFraud, estimate = .pred_class)
# Plot the ROC curve
fraud_results %>%
roc_curve(truth = isFraud, estimate = .pred_0) %>%
autoplot() +
labs(
x = "1-specificity\n(proportion of false positives\namong true negatives)",
y = "sensitivity\n(proportion of all positive cases that\nwere correctly classfied)"
)
```
# Modeling V2
We are going to switch models here and use a decision tree as opposed to
logistic regression. Instead of having to redo everything we went through above
we will begin putting together a `workflow()`. Workflows are "ML pipeline" in
the tidymodels world.
To create the workflow we will add a model and a recipe. In this case we will
add the decision tree model and then the feature engineered recipe we did above.
After that we can apply the split data to the workflow and get results.
```{r create new decision tree model}
# Choose model, engine, mode - decision tree
dt_model <- decision_tree() %>%
# Specify the engine
set_engine("rpart") %>%
# Specify the mode
set_mode("classification")
# Create a workflow - combine model and recipe
fraud_dt_wkfl <- workflow() %>%
# Include the model object
add_model(dt_model) %>%
# Include the recipe object we created above
add_recipe(fraud_norm_rec)
# Finish up by training the workflow
fraud_dt_wkfl_fit <- fraud_dt_wkfl %>%
last_fit(split = fraud_split, metrics = last_fit_metrics)
# Calculate performance metrics on test data
fraud_dt_wkfl_fit %>%
collect_metrics()
```
Having the `workflow()` helps us better keep track of things!
## Validation folds
Up until now we have used a single train/test split. We can help our models
less likely to be influenced by outliers and subsequently overfitting the
data by using validation folds.
The rsample package within tidymodels has the `vfold_cv()` function to do just
that.
```{r apply validation folds}
# Use paralleization to improve performance
doParallel::registerDoParallel()
# Create cross validation folds
set.seed(2021)
fraud_folds <- vfold_cv(fraud_train, v = 10, strata = isFraud)
# Print out the folds
fraud_folds
# Now we train a model for every fold
fraud_dt_rs <- fraud_dt_wkfl %>%
fit_resamples(resamples = fraud_folds, metrics = last_fit_metrics)
# And measure the out of sample performance for each
fraud_dt_rs %>% collect_metrics()
```
We can use everything we've put together and done up until now in a more
cohesive single chunk of code so you can see things running together and in
order.
This is closer to looking like what you may typically see in a machine learning
model project.
```{r rerun models and evaluate performance}
# I have left out the train/test split and feature engineering stuff but that
# would go here before the workflow stuff.
# Create decision tree workflow - combine model and recipe
fraud_dt_wkfl <- workflow() %>%
# Include the model object
add_model(dt_model) %>%
# Include the recipe object
add_recipe(fraud_norm_rec)
# Create logistic regression workflow - combine model and recipe
fraud_logistic_wkfl <- workflow() %>%
# Include the model object
add_model(logistic_model) %>%
# Include the recipe object
add_recipe(fraud_norm_rec)
# Fit Resamples - create cross validation folds and metrics
fraud_folds <- vfold_cv(fraud_train, v = 10, strata = isFraud)
fraud_metrics <- metric_set(accuracy, sens, spec, precision, recall, f_meas)
fraud_dt_rs <- fraud_dt_wkfl %>%
fit_resamples(resamples = fraud_folds, metrics = last_fit_metrics)
fraud_logistic_rs <- fraud_logistic_wkfl %>%
fit_resamples(resamples = fraud_folds, metrics = last_fit_metrics)
fraud_dt_rs %>%
collect_metrics() %>%
mutate(model = "decision_tree")
fraud_logistic_rs %>%
collect_metrics() %>%
mutate(model = "logistic_regression")
# Compare model performance
# Detailed cross validation results
dt_rs_results <- fraud_dt_rs %>%
collect_metrics(summarize = FALSE)
logistic_rs_results <- fraud_logistic_rs %>%
collect_metrics(summarize = FALSE)
# Explore model performance for decision tree
dt_rs_results %>%
group_by(.metric) %>%
summarize(min = min(.estimate, na.rm = TRUE),
median = median(.estimate, na.rm = TRUE),
max = max(.estimate, na.rm = TRUE)) %>%
mutate(model = "decision_tree")
# Explore model performance for logistic regression
logistic_rs_results %>%
group_by(.metric) %>%
summarize(min = min(.estimate, na.rm = TRUE),
median = median(.estimate, na.rm = TRUE),
max = max(.estimate, na.rm = TRUE)) %>%
mutate(model = "logistic_regression")
```
## Hyperparameters tuning
The last thing I want to cover is hyperparameter tuning. We can use the `tune()`
function from the `tune` package within tidymodels to do just that.
The default values set by the `parsnip` model in tidymodels for decision trees
is `min_n = 20`, `tree_depth = 30`, and `cost_complexity = 0.01`. min_n is the
minimum number of samples required to split a node, tree_depth is the
maximum allowed depth of the tree, and cost_complexity is the penalty for the
tree complexity.
```{r hyperparameter tuning}
# Set hyperparameters for tuning in the model specification step
dt_tune_model <- decision_tree(
cost_complexity = tune(),
tree_depth = tune(),
min_n = tune()
) %>%
# Specify engine
set_engine('rpart') %>%
# Specify mode
set_mode('classification')
# Crete a tuning workflow
fraud_dt_tune_wkfl <- fraud_dt_wkfl %>%
# Replace model
update_model(dt_tune_model)
# Hyperparameter tuning with grid search
set.seed(2021)
dt_grid <- grid_random(parameters(dt_tune_model), size = 5)
dt_grid
# Hyperparameter tuning
dt_tuning <- fraud_dt_tune_wkfl %>%
tune_grid(
resamples = fraud_folds,
grid = dt_grid,
metrics = fraud_metrics
)
```
```{r view hyperparameter tuning results}
dt_tuning %>%
collect_metrics()
dt_tuning %>%
collect_metrics(summarize = FALSE)
autoplot(dt_tuning) +
geom_line(linetype = "dashed") +
labs(
x = "Hyperparameter values",
y = "Performance metric score"
)
```
Pick the best one!
```{r select best tuned model}
# Collect detailed tuning results
dt_tuning_results <- dt_tuning %>%
collect_metrics(summarize = FALSE, metrics = metric_set(
accuracy, sens, spec, precision, recall, f_meas
))
# Display 5 best performing models
dt_tuning %>%
show_best(metric = 'recall', n = 5)
# Select based on best performance. For a multiclass classification model
# you could add desc(penalty) to get a model where the penalty is taking out
# more of the results - a simpler but effective model.
best_dt_model <- dt_tuning %>%
# Choose the best model based on roc_auc
select_best(metric = 'recall')
# Finalize your workflow
final_fraud_wkfl <- fraud_dt_tune_wkfl %>%
finalize_workflow(best_dt_model)
final_fraud_wkfl
```
At this point if you wanted to combine models you could do so via the `stacks`
package within tidymodels! I will not cover that here.
Almost done - the final train
```{r final model train}
# Train finalized decision tree workflow
fraud_final_fit <- final_fraud_wkfl %>%
last_fit(split = fraud_split)
# Create an ROC curve
fraud_final_fit %>%
# Collect predictions
collect_predictions() %>%
# Calculate ROC curve metrics
roc_curve(truth = isFraud, estimate = .pred_0) %>%
# Plot the ROC curve
autoplot() +
labs(
x = "1-specificity\n(proportion of false positives\namong true negatives)",
y = "sensitivity\n(proportion of all positive cases that\nwere correctly classied)"
)
```
# Bonus!!! Export the model to use in production!!
If you are satisfied with the model you created and are ready to add it to a
wonderful Shiny app you created you would do so by exporting the workflow!
A word of caution, modeling pipelines can take up A LOT OF MEMORY. Guess what?
Tidymodels can help you here too! You can use the `butcher` package within
tidymodels to "axe parts of the fitted output that are no longer needed, without
sacrificing much functionality from the original model object"
```{r extract model and performance metrics}
library(butcher)
# Extract the workflow object to make predictions with
fraud_wf_model <- extract_workflow(fraud_final_fit)
fraud_butcher_model <- butcher(fraud_wf_model)
print(paste("Original workflow size:", lobstr::obj_size(fraud_wf_model), "B"))
print(paste("Butchered workflow size", lobstr::obj_size(fraud_butcher_model), "B"))
```
We can now pass incoming data into our model to get our predictions
```{r make predictions on new data}
# lets go back and take a look at our original data
glimpse(fraud_data)
# We can select some random values to show how the extracted workflow would work
# on incoming data.
preds_res <- predict(fraud_butcher_model, sample_n(fraud_data, 1), type = "class")
preds_res$.pred_class
```
Now that we have our lean and mean model we can export the model to use in prod.
```{r}
# Save the model to be used later
saveRDS(fraud_butcher_model, "./fraud_butcher_model.rds")
# Lets also save the metrics so that we can see how the model performs on new
# Data coming through our Shiny application
collect_metrics(fraud_final_fit) %>%
write_csv("./fraud_model_metrics.csv")
```
From here you could use the `plumber` package to create an API that calls this
model and saves the results of the model to the model metrics csv!
Plumber allows you to create APIs by merely decorating your existing R code with
special annotations. The example below shows an example of the plumber.R file
that we would use to deploy this model.
This file defines two Plumber “endpoints.” One is hosted at the path /predict
and makes the fraud prediction; the other is hosted at the path /metrics and
shows the expected model metrics from the training data.
```{r api example}
## API setup
# Only keep packages you used - so not all of tidyverse and tidymodels to keep
# things small and light.
library(readr) # read csv
library(plumber) # API
library(dplyr) # data manipulation
library(parsnip) # model/engine selection
library(workflows) # machine learning pipeline
library(recipes) # preprocessor
library(themis) # calss imbalance
## Load model + metrics
fraud_butcher_model <- readRDS("./fraud_butcher_model.rds")
fraud_metrics <- read_csv("./fraud_model_metrics.csv")
#* @apiTitle Fraud detection model API
#* @apiDescription Fraud classification model predicting whether credit card transaction is fraud.
#* Submit credit card transaction data to get fraud/not fraud prediction
#* @serializer json
#* @parser json
#* @post /predict
function(req, res) {
preds <- req$body
preds_res <- predict(fraud_butcher_model, preds, type = "class")
preds_res$.pred_class
}
#* Expected model metrics from training
#* @serializer json
#* @get /metrics
function() {
fraud_metrics
}
```
From here you need to find a place where you can host your plumber API. Here is
some information on the variety of ways you can do that:
https://www.rplumber.io/articles/hosting.html
Good luck!