Skip to contents

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)
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
cat("Number of validation samples:", nrow(val_df), "\n")
## Number of validation samples: 56961

Analyze class imbalance in the targets

counts <- table(train_df$Class)
counts
##
##      0      1
## 227459    387
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: 387 (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_3 (Dense)                 │ (None, 256)            │         7,936
## ├─────────────────────────────────┼────────────────────────┼───────────────┤
## │ dense_2 (Dense)                 │ (None, 256)            │        65,792
## ├─────────────────────────────────┼────────────────────────┼───────────────┤
## │ dropout_1 (Dropout)             │ (None, 256)            │             0
## ├─────────────────────────────────┼────────────────────────┼───────────────┤
## │ dense_1 (Dense)                 │ (None, 256)            │        65,792
## ├─────────────────────────────────┼────────────────────────┼───────────────┤
## │ dropout (Dropout)               │ (None, 256)            │             0
## ├─────────────────────────────────┼────────────────────────┼───────────────┤
## │ dense (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 - 2s - 21ms/step - fn: 44.0000 - fp: 23999.0000 - loss: 2.2310e-06 - precision: 0.0141 - recall: 0.8863 - tn: 203460.0000 - tp: 343.0000 - val_fn: 6.0000 - val_fp: 3122.0000 - val_loss: 0.1931 - val_precision: 0.0307 - val_recall: 0.9429 - val_tn: 53734.0000 - val_tp: 99.0000
## Epoch 2/30
## 112/112 - 0s - 2ms/step - fn: 32.0000 - fp: 9264.0000 - loss: 1.4367e-06 - precision: 0.0369 - recall: 0.9173 - tn: 218195.0000 - tp: 355.0000 - val_fn: 3.0000 - val_fp: 4081.0000 - val_loss: 0.2209 - val_precision: 0.0244 - val_recall: 0.9714 - val_tn: 52775.0000 - val_tp: 102.0000
## Epoch 3/30
## 112/112 - 0s - 2ms/step - fn: 31.0000 - fp: 8504.0000 - loss: 1.1797e-06 - precision: 0.0402 - recall: 0.9199 - tn: 218955.0000 - tp: 356.0000 - val_fn: 7.0000 - val_fp: 577.0000 - val_loss: 0.0613 - val_precision: 0.1452 - val_recall: 0.9333 - val_tn: 56279.0000 - val_tp: 98.0000
## Epoch 4/30
## 112/112 - 0s - 2ms/step - fn: 31.0000 - fp: 10927.0000 - loss: 1.5436e-06 - precision: 0.0316 - recall: 0.9199 - tn: 216532.0000 - tp: 356.0000 - val_fn: 8.0000 - val_fp: 1432.0000 - val_loss: 0.1177 - val_precision: 0.0634 - val_recall: 0.9238 - val_tn: 55424.0000 - val_tp: 97.0000
## Epoch 5/30
## 112/112 - 0s - 2ms/step - fn: 29.0000 - fp: 9174.0000 - loss: 1.1107e-06 - precision: 0.0376 - recall: 0.9251 - tn: 218285.0000 - tp: 358.0000 - val_fn: 6.0000 - val_fp: 2538.0000 - val_loss: 0.1354 - val_precision: 0.0375 - val_recall: 0.9429 - val_tn: 54318.0000 - val_tp: 99.0000
## Epoch 6/30
## 112/112 - 0s - 2ms/step - fn: 15.0000 - fp: 8220.0000 - loss: 8.1028e-07 - precision: 0.0433 - recall: 0.9612 - tn: 219239.0000 - tp: 372.0000 - val_fn: 7.0000 - val_fp: 1182.0000 - val_loss: 0.0774 - val_precision: 0.0766 - val_recall: 0.9333 - val_tn: 55674.0000 - val_tp: 98.0000
## Epoch 7/30
## 112/112 - 0s - 2ms/step - fn: 13.0000 - fp: 7803.0000 - loss: 8.1749e-07 - precision: 0.0457 - recall: 0.9664 - tn: 219656.0000 - tp: 374.0000 - val_fn: 8.0000 - val_fp: 944.0000 - val_loss: 0.0536 - val_precision: 0.0932 - val_recall: 0.9238 - val_tn: 55912.0000 - val_tp: 97.0000
## Epoch 8/30
## 112/112 - 0s - 2ms/step - fn: 13.0000 - fp: 8117.0000 - loss: 6.9381e-07 - precision: 0.0440 - recall: 0.9664 - tn: 219342.0000 - tp: 374.0000 - val_fn: 9.0000 - val_fp: 794.0000 - val_loss: 0.0396 - val_precision: 0.1079 - val_recall: 0.9143 - val_tn: 56062.0000 - val_tp: 96.0000
## Epoch 9/30
## 112/112 - 0s - 2ms/step - fn: 19.0000 - fp: 9817.0000 - loss: 9.3896e-07 - precision: 0.0361 - recall: 0.9509 - tn: 217642.0000 - tp: 368.0000 - val_fn: 9.0000 - val_fp: 1292.0000 - val_loss: 0.0652 - val_precision: 0.0692 - val_recall: 0.9143 - val_tn: 55564.0000 - val_tp: 96.0000
## Epoch 10/30
## 112/112 - 0s - 2ms/step - fn: 12.0000 - fp: 8198.0000 - loss: 7.3109e-07 - precision: 0.0437 - recall: 0.9690 - tn: 219261.0000 - tp: 375.0000 - val_fn: 4.0000 - val_fp: 3894.0000 - val_loss: 0.1868 - val_precision: 0.0253 - val_recall: 0.9619 - val_tn: 52962.0000 - val_tp: 101.0000
## Epoch 11/30
## 112/112 - 0s - 2ms/step - fn: 15.0000 - fp: 8182.0000 - loss: 8.4644e-07 - precision: 0.0435 - recall: 0.9612 - tn: 219277.0000 - tp: 372.0000 - val_fn: 7.0000 - val_fp: 1779.0000 - val_loss: 0.0909 - val_precision: 0.0522 - val_recall: 0.9333 - val_tn: 55077.0000 - val_tp: 98.0000
## Epoch 12/30
## 112/112 - 0s - 2ms/step - fn: 9.0000 - fp: 7708.0000 - loss: 6.8122e-07 - precision: 0.0467 - recall: 0.9767 - tn: 219751.0000 - tp: 378.0000 - val_fn: 8.0000 - val_fp: 1376.0000 - val_loss: 0.0585 - val_precision: 0.0659 - val_recall: 0.9238 - val_tn: 55480.0000 - val_tp: 97.0000
## Epoch 13/30
## 112/112 - 0s - 2ms/step - fn: 7.0000 - fp: 5156.0000 - loss: 4.5651e-07 - precision: 0.0686 - recall: 0.9819 - tn: 222303.0000 - tp: 380.0000 - val_fn: 7.0000 - val_fp: 1870.0000 - val_loss: 0.0813 - val_precision: 0.0498 - val_recall: 0.9333 - val_tn: 54986.0000 - val_tp: 98.0000
## Epoch 14/30
## 112/112 - 0s - 2ms/step - fn: 5.0000 - fp: 4924.0000 - loss: 3.7919e-07 - precision: 0.0720 - recall: 0.9871 - tn: 222535.0000 - tp: 382.0000 - val_fn: 8.0000 - val_fp: 1144.0000 - val_loss: 0.0494 - val_precision: 0.0782 - val_recall: 0.9238 - val_tn: 55712.0000 - val_tp: 97.0000
## Epoch 15/30
## 112/112 - 0s - 2ms/step - fn: 2.0000 - fp: 4101.0000 - loss: 3.1106e-07 - precision: 0.0858 - recall: 0.9948 - tn: 223358.0000 - tp: 385.0000 - val_fn: 7.0000 - val_fp: 849.0000 - val_loss: 0.0382 - val_precision: 0.1035 - val_recall: 0.9333 - val_tn: 56007.0000 - val_tp: 98.0000
## Epoch 16/30
## 112/112 - 0s - 2ms/step - fn: 5.0000 - fp: 4255.0000 - loss: 5.1135e-07 - precision: 0.0824 - recall: 0.9871 - tn: 223204.0000 - tp: 382.0000 - val_fn: 14.0000 - val_fp: 589.0000 - val_loss: 0.0395 - val_precision: 0.1338 - val_recall: 0.8667 - val_tn: 56267.0000 - val_tp: 91.0000
## Epoch 17/30
## 112/112 - 0s - 2ms/step - fn: 16.0000 - fp: 12359.0000 - loss: 2.4119e-06 - precision: 0.0291 - recall: 0.9587 - tn: 215100.0000 - tp: 371.0000 - val_fn: 8.0000 - val_fp: 4416.0000 - val_loss: 0.4735 - val_precision: 0.0215 - val_recall: 0.9238 - val_tn: 52440.0000 - val_tp: 97.0000
## Epoch 18/30
## 112/112 - 0s - 2ms/step - fn: 25.0000 - fp: 9988.0000 - loss: 1.6301e-06 - precision: 0.0350 - recall: 0.9354 - tn: 217471.0000 - tp: 362.0000 - val_fn: 5.0000 - val_fp: 4161.0000 - val_loss: 0.1967 - val_precision: 0.0235 - val_recall: 0.9524 - val_tn: 52695.0000 - val_tp: 100.0000
## Epoch 19/30
## 112/112 - 0s - 2ms/step - fn: 12.0000 - fp: 8257.0000 - loss: 9.2278e-07 - precision: 0.0434 - recall: 0.9690 - tn: 219202.0000 - tp: 375.0000 - val_fn: 5.0000 - val_fp: 1834.0000 - val_loss: 0.0939 - val_precision: 0.0517 - val_recall: 0.9524 - val_tn: 55022.0000 - val_tp: 100.0000
## Epoch 20/30
## 112/112 - 0s - 2ms/step - fn: 12.0000 - fp: 8497.0000 - loss: 9.5626e-07 - precision: 0.0423 - recall: 0.9690 - tn: 218962.0000 - tp: 375.0000 - val_fn: 8.0000 - val_fp: 1707.0000 - val_loss: 0.1129 - val_precision: 0.0538 - val_recall: 0.9238 - val_tn: 55149.0000 - val_tp: 97.0000
## Epoch 21/30
## 112/112 - 0s - 2ms/step - fn: 9.0000 - fp: 7602.0000 - loss: 9.2171e-07 - precision: 0.0474 - recall: 0.9767 - tn: 219857.0000 - tp: 378.0000 - val_fn: 8.0000 - val_fp: 1326.0000 - val_loss: 0.1349 - val_precision: 0.0682 - val_recall: 0.9238 - val_tn: 55530.0000 - val_tp: 97.0000
## Epoch 22/30
## 112/112 - 0s - 2ms/step - fn: 6.0000 - fp: 5799.0000 - loss: 5.3588e-07 - precision: 0.0617 - recall: 0.9845 - tn: 221660.0000 - tp: 381.0000 - val_fn: 9.0000 - val_fp: 701.0000 - val_loss: 0.0293 - val_precision: 0.1205 - val_recall: 0.9143 - val_tn: 56155.0000 - val_tp: 96.0000
## Epoch 23/30
## 112/112 - 0s - 2ms/step - fn: 3.0000 - fp: 4258.0000 - loss: 4.9946e-07 - precision: 0.0827 - recall: 0.9922 - tn: 223201.0000 - tp: 384.0000 - val_fn: 7.0000 - val_fp: 1142.0000 - val_loss: 0.0481 - val_precision: 0.0790 - val_recall: 0.9333 - val_tn: 55714.0000 - val_tp: 98.0000
## Epoch 24/30
## 112/112 - 0s - 2ms/step - fn: 4.0000 - fp: 4713.0000 - loss: 3.3949e-07 - precision: 0.0752 - recall: 0.9897 - tn: 222746.0000 - tp: 383.0000 - val_fn: 9.0000 - val_fp: 822.0000 - val_loss: 0.0394 - val_precision: 0.1046 - val_recall: 0.9143 - val_tn: 56034.0000 - val_tp: 96.0000
## Epoch 25/30
## 112/112 - 0s - 2ms/step - fn: 10.0000 - fp: 9210.0000 - loss: 1.7289e-06 - precision: 0.0393 - recall: 0.9742 - tn: 218249.0000 - tp: 377.0000 - val_fn: 5.0000 - val_fp: 2974.0000 - val_loss: 0.2395 - val_precision: 0.0325 - val_recall: 0.9524 - val_tn: 53882.0000 - val_tp: 100.0000
## Epoch 26/30
## 112/112 - 0s - 2ms/step - fn: 6.0000 - fp: 7946.0000 - loss: 1.1577e-06 - precision: 0.0458 - recall: 0.9845 - tn: 219513.0000 - tp: 381.0000 - val_fn: 7.0000 - val_fp: 1538.0000 - val_loss: 0.1599 - val_precision: 0.0599 - val_recall: 0.9333 - val_tn: 55318.0000 - val_tp: 98.0000
## Epoch 27/30
## 112/112 - 0s - 2ms/step - fn: 6.0000 - fp: 6427.0000 - loss: 8.6088e-07 - precision: 0.0560 - recall: 0.9845 - tn: 221032.0000 - tp: 381.0000 - val_fn: 9.0000 - val_fp: 1082.0000 - val_loss: 0.0663 - val_precision: 0.0815 - val_recall: 0.9143 - val_tn: 55774.0000 - val_tp: 96.0000
## Epoch 28/30
## 112/112 - 0s - 2ms/step - fn: 6.0000 - fp: 4652.0000 - loss: 4.1927e-07 - precision: 0.0757 - recall: 0.9845 - tn: 222807.0000 - tp: 381.0000 - val_fn: 9.0000 - val_fp: 764.0000 - val_loss: 0.0376 - val_precision: 0.1116 - val_recall: 0.9143 - val_tn: 56092.0000 - val_tp: 96.0000
## Epoch 29/30
## 112/112 - 0s - 2ms/step - fn: 1.0000 - fp: 2879.0000 - loss: 2.4674e-07 - precision: 0.1182 - recall: 0.9974 - tn: 224580.0000 - tp: 386.0000 - val_fn: 10.0000 - val_fp: 570.0000 - val_loss: 0.0317 - val_precision: 0.1429 - val_recall: 0.9048 - val_tn: 56286.0000 - val_tp: 95.0000
## Epoch 30/30
## 112/112 - 0s - 2ms/step - fn: 4.0000 - fp: 5770.0000 - loss: 9.0391e-07 - precision: 0.0622 - recall: 0.9897 - tn: 221689.0000 - tp: 383.0000 - val_fn: 8.0000 - val_fp: 908.0000 - val_loss: 0.1193 - val_precision: 0.0965 - val_recall: 0.9238 - val_tn: 55948.0000 - val_tp: 97.0000
val_pred <- model %>%
  predict(val_features) %>%
  { as.integer(. > 0.5) }
## 1781/1781 - 1s - 344us/step
pred_correct <- val_df$Class == val_pred
cat(sprintf("Validation accuracy: %.2f", mean(pred_correct)))
## Validation accuracy: 0.98
fraudulent <- val_df$Class == 1

n_fraudulent_detected <- sum(fraudulent & pred_correct)
n_fraudulent_missed <- sum(fraudulent & !pred_correct)
n_legitimate_flagged <- sum(!fraudulent & !pred_correct)

Conclusions

At the end of training, out of 56,961 validation transactions, we are:

  • Correctly identifying 97 of them as fraudulent
  • Missing 8 fraudulent transactions
  • At the cost of incorrectly flagging 908 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.