Imbalanced classification: credit card fraud detection
Source:vignettes/examples/structured_data/imbalanced_classification.Rmd
imbalanced_classification.Rmd
library(keras3)
use_backend("jax")
Introduction
This example looks at the Kaggle Credit
Card Fraud Detection dataset to demonstrate how to train a
classification model on data with highly imbalanced classes. You can
download the data by clicking “Download” at the link, or if you’re setup
with a kaggle API key at "~/.kaggle/kagle.json"
, you can
run the following:
reticulate::py_install("kaggle", pip = TRUE)
reticulate::py_available(TRUE) # ensure 'kaggle' is on the PATH
system("kaggle datasets download -d mlg-ulb/creditcardfraud")
zip::unzip("creditcardfraud.zip", files = "creditcard.csv")
First, load the data
library(readr)
df <- read_csv("creditcard.csv", col_types = cols(
Class = col_integer(),
.default = col_double()
))
tibble::glimpse(df)
## Rows: 284,807
## Columns: 31
## $ Time <dbl> 0, 0, 1, 1, 2, 2, 4, 7, 7, 9, 10, 10, 10, 11, 12, 12, 12, 1…
## $ V1 <dbl> -1.3598071, 1.1918571, -1.3583541, -0.9662717, -1.1582331, …
## $ V2 <dbl> -0.07278117, 0.26615071, -1.34016307, -0.18522601, 0.877736…
## $ V3 <dbl> 2.53634674, 0.16648011, 1.77320934, 1.79299334, 1.54871785,…
## $ V4 <dbl> 1.37815522, 0.44815408, 0.37977959, -0.86329128, 0.40303393…
## $ V5 <dbl> -0.33832077, 0.06001765, -0.50319813, -0.01030888, -0.40719…
## $ V6 <dbl> 0.46238778, -0.08236081, 1.80049938, 1.24720317, 0.09592146…
## $ V7 <dbl> 0.239598554, -0.078802983, 0.791460956, 0.237608940, 0.5929…
## $ V8 <dbl> 0.098697901, 0.085101655, 0.247675787, 0.377435875, -0.2705…
## $ V9 <dbl> 0.3637870, -0.2554251, -1.5146543, -1.3870241, 0.8177393, -…
## $ V10 <dbl> 0.09079417, -0.16697441, 0.20764287, -0.05495192, 0.7530744…
## $ V11 <dbl> -0.55159953, 1.61272666, 0.62450146, -0.22648726, -0.822842…
## $ V12 <dbl> -0.61780086, 1.06523531, 0.06608369, 0.17822823, 0.53819555…
## $ V13 <dbl> -0.99138985, 0.48909502, 0.71729273, 0.50775687, 1.34585159…
## $ V14 <dbl> -0.31116935, -0.14377230, -0.16594592, -0.28792375, -1.1196…
## $ V15 <dbl> 1.468176972, 0.635558093, 2.345864949, -0.631418118, 0.1751…
## $ V16 <dbl> -0.47040053, 0.46391704, -2.89008319, -1.05964725, -0.45144…
## $ V17 <dbl> 0.207971242, -0.114804663, 1.109969379, -0.684092786, -0.23…
## $ V18 <dbl> 0.02579058, -0.18336127, -0.12135931, 1.96577500, -0.038194…
## $ V19 <dbl> 0.40399296, -0.14578304, -2.26185710, -1.23262197, 0.803486…
## $ V20 <dbl> 0.25141210, -0.06908314, 0.52497973, -0.20803778, 0.4085423…
## $ V21 <dbl> -0.018306778, -0.225775248, 0.247998153, -0.108300452, -0.0…
## $ V22 <dbl> 0.277837576, -0.638671953, 0.771679402, 0.005273597, 0.7982…
## $ V23 <dbl> -0.110473910, 0.101288021, 0.909412262, -0.190320519, -0.13…
## $ V24 <dbl> 0.06692807, -0.33984648, -0.68928096, -1.17557533, 0.141266…
## $ V25 <dbl> 0.12853936, 0.16717040, -0.32764183, 0.64737603, -0.2060095…
## $ V26 <dbl> -0.18911484, 0.12589453, -0.13909657, -0.22192884, 0.502292…
## $ V27 <dbl> 0.133558377, -0.008983099, -0.055352794, 0.062722849, 0.219…
## $ V28 <dbl> -0.021053053, 0.014724169, -0.059751841, 0.061457629, 0.215…
## $ Amount <dbl> 149.62, 2.69, 378.66, 123.50, 69.99, 3.67, 4.99, 40.80, 93.…
## $ Class <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,…
Prepare a validation set
val_idx <- nrow(df) %>% sample.int(., round( . * 0.2))
val_df <- df[val_idx, ]
train_df <- df[-val_idx, ]
cat("Number of training samples:", nrow(train_df), "\n")
## Number of training samples: 227846
## Number of validation samples: 56961
Analyze class imbalance in the targets
counts <- table(train_df$Class)
counts
##
## 0 1
## 227449 397
cat(sprintf("Number of positive samples in training data: %i (%.2f%% of total)",
counts["1"], 100 * counts["1"] / sum(counts)))
## Number of positive samples in training data: 397 (0.17% of total)
weight_for_0 = 1 / counts["0"]
weight_for_1 = 1 / counts["1"]
Normalize the data using training set statistics
feature_names <- colnames(train_df) %>% setdiff("Class")
train_features <- as.matrix(train_df[feature_names])
train_targets <- as.matrix(train_df$Class)
val_features <- as.matrix(val_df[feature_names])
val_targets <- as.matrix(val_df$Class)
train_features %<>% scale()
val_features %<>% scale(center = attr(train_features, "scaled:center"),
scale = attr(train_features, "scaled:scale"))
Build a binary classification model
model <-
keras_model_sequential(input_shape = ncol(train_features)) |>
layer_dense(256, activation = "relu") |>
layer_dense(256, activation = "relu") |>
layer_dropout(0.3) |>
layer_dense(256, activation = "relu") |>
layer_dropout(0.3) |>
layer_dense(1, activation = "sigmoid")
model
## Model: "sequential"
## ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
## ┃ Layer (type) ┃ Output Shape ┃ Param # ┃
## ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩
## │ dense (Dense) │ (None, 256) │ 7,936 │
## ├─────────────────────────────────┼────────────────────────┼───────────────┤
## │ dense_1 (Dense) │ (None, 256) │ 65,792 │
## ├─────────────────────────────────┼────────────────────────┼───────────────┤
## │ dropout (Dropout) │ (None, 256) │ 0 │
## ├─────────────────────────────────┼────────────────────────┼───────────────┤
## │ dense_2 (Dense) │ (None, 256) │ 65,792 │
## ├─────────────────────────────────┼────────────────────────┼───────────────┤
## │ dropout_1 (Dropout) │ (None, 256) │ 0 │
## ├─────────────────────────────────┼────────────────────────┼───────────────┤
## │ dense_3 (Dense) │ (None, 1) │ 257 │
## └─────────────────────────────────┴────────────────────────┴───────────────┘
## Total params: 139,777 (546.00 KB)
## Trainable params: 139,777 (546.00 KB)
## Non-trainable params: 0 (0.00 B)
Train the model with class_weight
argument
metrics <- list(
metric_false_negatives(name = "fn"),
metric_false_positives(name = "fp"),
metric_true_negatives(name = "tn"),
metric_true_positives(name = "tp"),
metric_precision(name = "precision"),
metric_recall(name = "recall")
)
model |> compile(
optimizer = optimizer_adam(1e-2),
loss = "binary_crossentropy",
metrics = metrics
)
callbacks <- list(
callback_model_checkpoint("fraud_model_at_epoch_{epoch}.keras")
)
class_weight <- list("0" = weight_for_0,
"1" = weight_for_1)
model |> fit(
train_features, train_targets,
validation_data = list(val_features, val_targets),
class_weight = class_weight,
batch_size = 2048,
epochs = 30,
callbacks = callbacks,
verbose = 2
)
## Epoch 1/30
## 112/112 - 4s - 32ms/step - fn: 43.0000 - fp: 28453.0000 - loss: 2.3315e-06 - precision: 0.0123 - recall: 0.8917 - tn: 198996.0000 - tp: 354.0000 - val_fn: 10.0000 - val_fp: 810.0000 - val_loss: 0.0895 - val_precision: 0.0950 - val_recall: 0.8947 - val_tn: 56056.0000 - val_tp: 85.0000
## Epoch 2/30
## 112/112 - 1s - 6ms/step - fn: 32.0000 - fp: 7212.0000 - loss: 1.3946e-06 - precision: 0.0482 - recall: 0.9194 - tn: 220237.0000 - tp: 365.0000 - val_fn: 12.0000 - val_fp: 476.0000 - val_loss: 0.0620 - val_precision: 0.1485 - val_recall: 0.8737 - val_tn: 56390.0000 - val_tp: 83.0000
## Epoch 3/30
## 112/112 - 0s - 2ms/step - fn: 30.0000 - fp: 7984.0000 - loss: 1.2208e-06 - precision: 0.0439 - recall: 0.9244 - tn: 219465.0000 - tp: 367.0000 - val_fn: 4.0000 - val_fp: 2047.0000 - val_loss: 0.1110 - val_precision: 0.0426 - val_recall: 0.9579 - val_tn: 54819.0000 - val_tp: 91.0000
## Epoch 4/30
## 112/112 - 0s - 2ms/step - fn: 22.0000 - fp: 6610.0000 - loss: 9.2594e-07 - precision: 0.0537 - recall: 0.9446 - tn: 220839.0000 - tp: 375.0000 - val_fn: 6.0000 - val_fp: 1467.0000 - val_loss: 0.0786 - val_precision: 0.0572 - val_recall: 0.9368 - val_tn: 55399.0000 - val_tp: 89.0000
## Epoch 5/30
## 112/112 - 0s - 2ms/step - fn: 21.0000 - fp: 8401.0000 - loss: 1.0244e-06 - precision: 0.0428 - recall: 0.9471 - tn: 219048.0000 - tp: 376.0000 - val_fn: 8.0000 - val_fp: 917.0000 - val_loss: 0.0602 - val_precision: 0.0867 - val_recall: 0.9158 - val_tn: 55949.0000 - val_tp: 87.0000
## Epoch 6/30
## 112/112 - 0s - 2ms/step - fn: 24.0000 - fp: 9729.0000 - loss: 1.1093e-06 - precision: 0.0369 - recall: 0.9395 - tn: 217720.0000 - tp: 373.0000 - val_fn: 10.0000 - val_fp: 867.0000 - val_loss: 0.0722 - val_precision: 0.0893 - val_recall: 0.8947 - val_tn: 55999.0000 - val_tp: 85.0000
## Epoch 7/30
## 112/112 - 0s - 2ms/step - fn: 18.0000 - fp: 6700.0000 - loss: 7.7501e-07 - precision: 0.0535 - recall: 0.9547 - tn: 220749.0000 - tp: 379.0000 - val_fn: 12.0000 - val_fp: 1046.0000 - val_loss: 0.0466 - val_precision: 0.0735 - val_recall: 0.8737 - val_tn: 55820.0000 - val_tp: 83.0000
## Epoch 8/30
## 112/112 - 0s - 2ms/step - fn: 13.0000 - fp: 5736.0000 - loss: 7.3415e-07 - precision: 0.0627 - recall: 0.9673 - tn: 221713.0000 - tp: 384.0000 - val_fn: 8.0000 - val_fp: 1086.0000 - val_loss: 0.0551 - val_precision: 0.0742 - val_recall: 0.9158 - val_tn: 55780.0000 - val_tp: 87.0000
## Epoch 9/30
## 112/112 - 0s - 2ms/step - fn: 10.0000 - fp: 6234.0000 - loss: 7.5539e-07 - precision: 0.0585 - recall: 0.9748 - tn: 221215.0000 - tp: 387.0000 - val_fn: 6.0000 - val_fp: 2159.0000 - val_loss: 0.0923 - val_precision: 0.0396 - val_recall: 0.9368 - val_tn: 54707.0000 - val_tp: 89.0000
## Epoch 10/30
## 112/112 - 0s - 2ms/step - fn: 19.0000 - fp: 7946.0000 - loss: 1.0142e-06 - precision: 0.0454 - recall: 0.9521 - tn: 219503.0000 - tp: 378.0000 - val_fn: 11.0000 - val_fp: 1069.0000 - val_loss: 0.0584 - val_precision: 0.0729 - val_recall: 0.8842 - val_tn: 55797.0000 - val_tp: 84.0000
## Epoch 11/30
## 112/112 - 0s - 2ms/step - fn: 13.0000 - fp: 6436.0000 - loss: 7.5913e-07 - precision: 0.0563 - recall: 0.9673 - tn: 221013.0000 - tp: 384.0000 - val_fn: 11.0000 - val_fp: 1202.0000 - val_loss: 0.0475 - val_precision: 0.0653 - val_recall: 0.8842 - val_tn: 55664.0000 - val_tp: 84.0000
## Epoch 12/30
## 112/112 - 0s - 2ms/step - fn: 10.0000 - fp: 5914.0000 - loss: 7.4638e-07 - precision: 0.0614 - recall: 0.9748 - tn: 221535.0000 - tp: 387.0000 - val_fn: 8.0000 - val_fp: 2845.0000 - val_loss: 0.1117 - val_precision: 0.0297 - val_recall: 0.9158 - val_tn: 54021.0000 - val_tp: 87.0000
## Epoch 13/30
## 112/112 - 0s - 2ms/step - fn: 13.0000 - fp: 7164.0000 - loss: 9.3897e-07 - precision: 0.0509 - recall: 0.9673 - tn: 220285.0000 - tp: 384.0000 - val_fn: 10.0000 - val_fp: 2110.0000 - val_loss: 0.2167 - val_precision: 0.0387 - val_recall: 0.8947 - val_tn: 54756.0000 - val_tp: 85.0000
## Epoch 14/30
## 112/112 - 0s - 2ms/step - fn: 24.0000 - fp: 11932.0000 - loss: 2.8804e-06 - precision: 0.0303 - recall: 0.9395 - tn: 215517.0000 - tp: 373.0000 - val_fn: 8.0000 - val_fp: 1633.0000 - val_loss: 0.1923 - val_precision: 0.0506 - val_recall: 0.9158 - val_tn: 55233.0000 - val_tp: 87.0000
## Epoch 15/30
## 112/112 - 0s - 2ms/step - fn: 14.0000 - fp: 7278.0000 - loss: 1.0593e-06 - precision: 0.0500 - recall: 0.9647 - tn: 220171.0000 - tp: 383.0000 - val_fn: 12.0000 - val_fp: 1248.0000 - val_loss: 0.0668 - val_precision: 0.0624 - val_recall: 0.8737 - val_tn: 55618.0000 - val_tp: 83.0000
## Epoch 16/30
## 112/112 - 0s - 2ms/step - fn: 10.0000 - fp: 4882.0000 - loss: 6.4745e-07 - precision: 0.0734 - recall: 0.9748 - tn: 222567.0000 - tp: 387.0000 - val_fn: 12.0000 - val_fp: 762.0000 - val_loss: 0.0390 - val_precision: 0.0982 - val_recall: 0.8737 - val_tn: 56104.0000 - val_tp: 83.0000
## Epoch 17/30
## 112/112 - 0s - 2ms/step - fn: 5.0000 - fp: 3787.0000 - loss: 6.2951e-07 - precision: 0.0938 - recall: 0.9874 - tn: 223662.0000 - tp: 392.0000 - val_fn: 11.0000 - val_fp: 2377.0000 - val_loss: 0.1353 - val_precision: 0.0341 - val_recall: 0.8842 - val_tn: 54489.0000 - val_tp: 84.0000
## Epoch 18/30
## 112/112 - 0s - 2ms/step - fn: 9.0000 - fp: 4289.0000 - loss: 6.9113e-07 - precision: 0.0830 - recall: 0.9773 - tn: 223160.0000 - tp: 388.0000 - val_fn: 7.0000 - val_fp: 2406.0000 - val_loss: 0.1228 - val_precision: 0.0353 - val_recall: 0.9263 - val_tn: 54460.0000 - val_tp: 88.0000
## Epoch 19/30
## 112/112 - 0s - 2ms/step - fn: 6.0000 - fp: 4104.0000 - loss: 6.4491e-07 - precision: 0.0870 - recall: 0.9849 - tn: 223345.0000 - tp: 391.0000 - val_fn: 9.0000 - val_fp: 2327.0000 - val_loss: 0.1659 - val_precision: 0.0356 - val_recall: 0.9053 - val_tn: 54539.0000 - val_tp: 86.0000
## Epoch 20/30
## 112/112 - 0s - 2ms/step - fn: 3.0000 - fp: 3397.0000 - loss: 5.1585e-07 - precision: 0.1039 - recall: 0.9924 - tn: 224052.0000 - tp: 394.0000 - val_fn: 16.0000 - val_fp: 430.0000 - val_loss: 0.0236 - val_precision: 0.1552 - val_recall: 0.8316 - val_tn: 56436.0000 - val_tp: 79.0000
## Epoch 21/30
## 112/112 - 0s - 2ms/step - fn: 3.0000 - fp: 2878.0000 - loss: 4.7408e-07 - precision: 0.1204 - recall: 0.9924 - tn: 224571.0000 - tp: 394.0000 - val_fn: 12.0000 - val_fp: 840.0000 - val_loss: 0.0500 - val_precision: 0.0899 - val_recall: 0.8737 - val_tn: 56026.0000 - val_tp: 83.0000
## Epoch 22/30
## 112/112 - 0s - 2ms/step - fn: 2.0000 - fp: 2265.0000 - loss: 3.9213e-07 - precision: 0.1485 - recall: 0.9950 - tn: 225184.0000 - tp: 395.0000 - val_fn: 13.0000 - val_fp: 409.0000 - val_loss: 0.0244 - val_precision: 0.1670 - val_recall: 0.8632 - val_tn: 56457.0000 - val_tp: 82.0000
## Epoch 23/30
## 112/112 - 0s - 2ms/step - fn: 6.0000 - fp: 2457.0000 - loss: 4.2171e-07 - precision: 0.1373 - recall: 0.9849 - tn: 224992.0000 - tp: 391.0000 - val_fn: 11.0000 - val_fp: 978.0000 - val_loss: 0.0530 - val_precision: 0.0791 - val_recall: 0.8842 - val_tn: 55888.0000 - val_tp: 84.0000
## Epoch 24/30
## 112/112 - 0s - 2ms/step - fn: 4.0000 - fp: 2892.0000 - loss: 4.3122e-07 - precision: 0.1196 - recall: 0.9899 - tn: 224557.0000 - tp: 393.0000 - val_fn: 11.0000 - val_fp: 1289.0000 - val_loss: 0.0621 - val_precision: 0.0612 - val_recall: 0.8842 - val_tn: 55577.0000 - val_tp: 84.0000
## Epoch 25/30
## 112/112 - 0s - 2ms/step - fn: 3.0000 - fp: 3003.0000 - loss: 4.6385e-07 - precision: 0.1160 - recall: 0.9924 - tn: 224446.0000 - tp: 394.0000 - val_fn: 13.0000 - val_fp: 504.0000 - val_loss: 0.0326 - val_precision: 0.1399 - val_recall: 0.8632 - val_tn: 56362.0000 - val_tp: 82.0000
## Epoch 26/30
## 112/112 - 0s - 2ms/step - fn: 4.0000 - fp: 3021.0000 - loss: 4.9493e-07 - precision: 0.1151 - recall: 0.9899 - tn: 224428.0000 - tp: 393.0000 - val_fn: 13.0000 - val_fp: 491.0000 - val_loss: 0.0263 - val_precision: 0.1431 - val_recall: 0.8632 - val_tn: 56375.0000 - val_tp: 82.0000
## Epoch 27/30
## 112/112 - 0s - 2ms/step - fn: 1.0000 - fp: 1760.0000 - loss: 3.2630e-07 - precision: 0.1837 - recall: 0.9975 - tn: 225689.0000 - tp: 396.0000 - val_fn: 12.0000 - val_fp: 548.0000 - val_loss: 0.0330 - val_precision: 0.1315 - val_recall: 0.8737 - val_tn: 56318.0000 - val_tp: 83.0000
## Epoch 28/30
## 112/112 - 0s - 2ms/step - fn: 4.0000 - fp: 2210.0000 - loss: 3.8747e-07 - precision: 0.1510 - recall: 0.9899 - tn: 225239.0000 - tp: 393.0000 - val_fn: 14.0000 - val_fp: 635.0000 - val_loss: 0.0360 - val_precision: 0.1131 - val_recall: 0.8526 - val_tn: 56231.0000 - val_tp: 81.0000
## Epoch 29/30
## 112/112 - 0s - 2ms/step - fn: 2.0000 - fp: 1455.0000 - loss: 3.2271e-07 - precision: 0.2135 - recall: 0.9950 - tn: 225994.0000 - tp: 395.0000 - val_fn: 13.0000 - val_fp: 420.0000 - val_loss: 0.0280 - val_precision: 0.1633 - val_recall: 0.8632 - val_tn: 56446.0000 - val_tp: 82.0000
## Epoch 30/30
## 112/112 - 0s - 2ms/step - fn: 1.0000 - fp: 1647.0000 - loss: 3.2797e-07 - precision: 0.1938 - recall: 0.9975 - tn: 225802.0000 - tp: 396.0000 - val_fn: 14.0000 - val_fp: 377.0000 - val_loss: 0.0237 - val_precision: 0.1769 - val_recall: 0.8526 - val_tn: 56489.0000 - val_tp: 81.0000
val_pred <- model %>%
predict(val_features) %>%
{ as.integer(. > 0.5) }
## 1781/1781 - 0s - 257us/step
pred_correct <- val_df$Class == val_pred
cat(sprintf("Validation accuracy: %.2f", mean(pred_correct)))
## Validation accuracy: 0.99
Conclusions
At the end of training, out of 56,961 validation transactions, we are:
- Correctly identifying 81 of them as fraudulent
- Missing 14 fraudulent transactions
- At the cost of incorrectly flagging 377 legitimate transactions
In the real world, one would put an even higher weight on class 1, so as to reflect that False Negatives are more costly than False Positives.
Next time your credit card gets declined in an online purchase – this is why.