Classification on imbalanced data

Stay organized with collections Save and categorize content based on your preferences.

View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook

This tutorial demonstrates how to classify a highly imbalanced dataset in which the number of examples in one class greatly outnumbers the examples in another. You will work with the Credit Card Fraud Detection dataset hosted on Kaggle. The aim is to detect a mere 492 fraudulent transactions from 284,807 transactions in total. You will use Keras to define the model and class weights to help the model learn from the imbalanced data. .

This tutorial contains complete code to:

  • Load a CSV file using Pandas.
  • Create train, validation, and test sets.
  • Define and train a model using Keras (including setting class weights).
  • Evaluate the model using various metrics (including precision and recall).
  • Try common techniques for dealing with imbalanced data like:
    • Class weighting
    • Oversampling

Setup

import tensorflow as tf
from tensorflow import keras

import os
import tempfile

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

import sklearn
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
2022-09-07 03:44:59.219616: E tensorflow/stream_executor/cuda/cuda_blas.cc:2981] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
2022-09-07 03:44:59.924116: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvrtc.so.11.1: cannot open shared object file: No such file or directory
2022-09-07 03:44:59.924378: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvrtc.so.11.1: cannot open shared object file: No such file or directory
2022-09-07 03:44:59.924390: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
mpl.rcParams['figure.figsize'] = (12, 10)
colors = plt.rcParams['axes.prop_cycle'].by_key()['color']

Data processing and exploration

Download the Kaggle Credit Card Fraud data set

Pandas is a Python library with many helpful utilities for loading and working with structured data. It can be used to download CSVs into a Pandas DataFrame.

file = tf.keras.utils
raw_df = pd.read_csv('https://storage.googleapis.com/download.tensorflow.org/data/creditcard.csv')
raw_df.head()
raw_df[['Time', 'V1', 'V2', 'V3', 'V4', 'V5', 'V26', 'V27', 'V28', 'Amount', 'Class']].describe()

Examine the class label imbalance

Let's look at the dataset imbalance:

neg, pos = np.bincount(raw_df['Class'])
total = neg + pos
print('Examples:\n    Total: {}\n    Positive: {} ({:.2f}% of total)\n'.format(
    total, pos, 100 * pos / total))
Examples:
    Total: 284807
    Positive: 492 (0.17% of total)

This shows the small fraction of positive samples.

Clean, split and normalize the data

The raw data has a few issues. First the Time and Amount columns are too variable to use directly. Drop the Time column (since it's not clear what it means) and take the log of the Amount column to reduce its range.

cleaned_df = raw_df.copy()

# You don't want the `Time` column.
cleaned_df.pop('Time')

# The `Amount` column covers a huge range. Convert to log-space.
eps = 0.001 # 0 => 0.1¢
cleaned_df['Log Amount'] = np.log(cleaned_df.pop('Amount')+eps)

Split the dataset into train, validation, and test sets. The validation set is used during the model fitting to evaluate the loss and any metrics, however the model is not fit with this data. The test set is completely unused during the training phase and is only used at the end to evaluate how well the model generalizes to new data. This is especially important with imbalanced datasets where overfitting is a significant concern from the lack of training data.

# Use a utility from sklearn to split and shuffle your dataset.
train_df, test_df = train_test_split(cleaned_df, test_size=0.2)
train_df, val_df = train_test_split(train_df, test_size=0.2)

# Form np arrays of labels and features.
train_labels = np.array(train_df.pop('Class'))
bool_train_labels = train_labels != 0
val_labels = np.array(val_df.pop('Class'))
test_labels = np.array(test_df.pop('Class'))

train_features = np.array(train_df)
val_features = np.array(val_df)
test_features = np.array(test_df)

Normalize the input features using the sklearn StandardScaler. This will set the mean to 0 and standard deviation to 1.

scaler = StandardScaler()
train_features = scaler.fit_transform(train_features)

val_features = scaler.transform(val_features)
test_features = scaler.transform(test_features)

train_features = np.clip(train_features, -5, 5)
val_features = np.clip(val_features, -5, 5)
test_features = np.clip(test_features, -5, 5)


print('Training labels shape:', train_labels.shape)
print('Validation labels shape:', val_labels.shape)
print('Test labels shape:', test_labels.shape)

print('Training features shape:', train_features.shape)
print('Validation features shape:', val_features.shape)
print('Test features shape:', test_features.shape)
Training labels shape: (182276,)
Validation labels shape: (45569,)
Test labels shape: (56962,)
Training features shape: (182276, 29)
Validation features shape: (45569, 29)
Test features shape: (56962, 29)

Look at the data distribution

Next compare the distributions of the positive and negative examples over a few features. Good questions to ask yourself at this point are:

  • Do these distributions make sense?
    • Yes. You've normalized the input and these are mostly concentrated in the +/- 2 range.
  • Can you see the difference between the distributions?
    • Yes the positive examples contain a much higher rate of extreme values.
pos_df = pd.DataFrame(train_features[ bool_train_labels], columns=train_df.columns)
neg_df = pd.DataFrame(train_features[~bool_train_labels], columns=train_df.columns)

sns.jointplot(x=pos_df['V5'], y=pos_df['V6'],
              kind='hex', xlim=(-5,5), ylim=(-5,5))
plt.suptitle("Positive distribution")

sns.jointplot(x=neg_df['V5'], y=neg_df['V6'],
              kind='hex', xlim=(-5,5), ylim=(-5,5))
_ = plt.suptitle("Negative distribution")

png

png

Define the model and metrics

Define a function that creates a simple neural network with a densly connected hidden layer, a dropout layer to reduce overfitting, and an output sigmoid layer that returns the probability of a transaction being fraudulent:

METRICS = [
      keras.metrics.TruePositives(name='tp'),
      keras.metrics.FalsePositives(name='fp'),
      keras.metrics.TrueNegatives(name='tn'),
      keras.metrics.FalseNegatives(name='fn'), 
      keras.metrics.BinaryAccuracy(name='accuracy'),
      keras.metrics.Precision(name='precision'),
      keras.metrics.Recall(name='recall'),
      keras.metrics.AUC(name='auc'),
      keras.metrics.AUC(name='prc', curve='PR'), # precision-recall curve
]

def make_model(metrics=METRICS, output_bias=None):
  if output_bias is not None:
    output_bias = tf.keras.initializers.Constant(output_bias)
  model = keras.Sequential([
      keras.layers.Dense(
          16, activation='relu',
          input_shape=(train_features.shape[-1],)),
      keras.layers.Dropout(0.5),
      keras.layers.Dense(1, activation='sigmoid',
                         bias_initializer=output_bias),
  ])

  model.compile(
      optimizer=keras.optimizers.Adam(learning_rate=1e-3),
      loss=keras.losses.BinaryCrossentropy(),
      metrics=metrics)

  return model

Understanding useful metrics

Notice that there are a few metrics defined above that can be computed by the model that will be helpful when evaluating the performance.

  • False negatives and false positives are samples that were incorrectly classified
  • True negatives and true positives are samples that were correctly classified
  • Accuracy is the percentage of examples correctly classified > \(\frac{\text{true samples} }{\text{total samples} }\)
  • Precision is the percentage of predicted positives that were correctly classified > \(\frac{\text{true positives} }{\text{true positives + false positives} }\)
  • Recall is the percentage of actual positives that were correctly classified > \(\frac{\text{true positives} }{\text{true positives + false negatives} }\)
  • AUC refers to the Area Under the Curve of a Receiver Operating Characteristic curve (ROC-AUC). This metric is equal to the probability that a classifier will rank a random positive sample higher than a random negative sample.
  • AUPRC refers to Area Under the Curve of the Precision-Recall Curve. This metric computes precision-recall pairs for different probability thresholds.

Read more:

Baseline model

Build the model

Now create and train your model using the function that was defined earlier. Notice that the model is fit using a larger than default batch size of 2048, this is important to ensure that each batch has a decent chance of containing a few positive samples. If the batch size was too small, they would likely have no fraudulent transactions to learn from.

EPOCHS = 100
BATCH_SIZE = 2048

early_stopping = tf.keras.callbacks.EarlyStopping(
    monitor='val_prc', 
    verbose=1,
    patience=10,
    mode='max',
    restore_best_weights=True)
model = make_model()
model.summary()
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 dense (Dense)               (None, 16)                480       
                                                                 
 dropout (Dropout)           (None, 16)                0         
                                                                 
 dense_1 (Dense)             (None, 1)                 17        
                                                                 
=================================================================
Total params: 497
Trainable params: 497
Non-trainable params: 0
_________________________________________________________________

Test run the model:

model.predict(train_features[:10])
1/1 [==============================] - 0s 357ms/step
array([[0.45439944],
       [0.81378055],
       [0.9119205 ],
       [0.66936404],
       [0.70673376],
       [0.8674103 ],
       [0.79077727],
       [0.4855406 ],
       [0.55787843],
       [0.7984147 ]], dtype=float32)

Optional: Set the correct initial bias.

These initial guesses are not great. You know the dataset is imbalanced. Set the output layer's bias to reflect that (See: A Recipe for Training Neural Networks: "init well"). This can help with initial convergence.

With the default bias initialization the loss should be about math.log(2) = 0.69314

results = model.evaluate(train_features, train_labels, batch_size=BATCH_SIZE, verbose=0)
print("Loss: {:0.4f}".format(results[0]))
Loss: 1.3385

The correct bias to set can be derived from:

\[ p_0 = pos/(pos + neg) = 1/(1+e^{-b_0}) \]

\[ b_0 = -log_e(1/p_0 - 1) \]

\[ b_0 = log_e(pos/neg)\]

initial_bias = np.log([pos/neg])
initial_bias
array([-6.35935934])

Set that as the initial bias, and the model will give much more reasonable initial guesses.

It should be near: pos/total = 0.0018

model = make_model(output_bias=initial_bias)
model.predict(train_features[:10])
1/1 [==============================] - 0s 46ms/step
array([[0.00456044],
       [0.00204489],
       [0.00121967],
       [0.00177023],
       [0.00160178],
       [0.00078203],
       [0.00039386],
       [0.00107281],
       [0.00019184],
       [0.00032823]], dtype=float32)

With this initialization the initial loss should be approximately:

\[-p_0log(p_0)-(1-p_0)log(1-p_0) = 0.01317\]

results = model.evaluate(train_features, train_labels, batch_size=BATCH_SIZE, verbose=0)
print("Loss: {:0.4f}".format(results[0]))
Loss: 0.0151

This initial loss is about 50 times less than if would have been with naive initialization.

This way the model doesn't need to spend the first few epochs just learning that positive examples are unlikely. This also makes it easier to read plots of the loss during training.

Checkpoint the initial weights

To make the various training runs more comparable, keep this initial model's weights in a checkpoint file, and load them into each model before training:

initial_weights = os.path.join(tempfile.mkdtemp(), 'initial_weights')
model.save_weights(initial_weights)

Confirm that the bias fix helps

Before moving on, confirm quick that the careful bias initialization actually helped.

Train the model for 20 epochs, with and without this careful initialization, and compare the losses:

model = make_model()
model.load_weights(initial_weights)
model.layers[-1].bias.assign([0.0])
zero_bias_history = model.fit(
    train_features,
    train_labels,
    batch_size=BATCH_SIZE,
    epochs=20,
    validation_data=(val_features, val_labels), 
    verbose=0)
model = make_model()
model.load_weights(initial_weights)
careful_bias_history = model.fit(
    train_features,
    train_labels,
    batch_size=BATCH_SIZE,
    epochs=20,
    validation_data=(val_features, val_labels), 
    verbose=0)
def plot_loss(history, label, n):
  # Use a log scale on y-axis to show the wide range of values.
  plt.semilogy(history.epoch, history.history['loss'],
               color=colors[n], label='Train ' + label)
  plt.semilogy(history.epoch, history.history['val_loss'],
               color=colors[n], label='Val ' + label,
               linestyle="--")
  plt.xlabel('Epoch')
  plt.ylabel('Loss')
plot_loss(zero_bias_history, "Zero Bias", 0)
plot_loss(careful_bias_history, "Careful Bias", 1)

png

The above figure makes it clear: In terms of validation loss, on this problem, this careful initialization gives a clear advantage.

Train the model

model = make_model()
model.load_weights(initial_weights)
baseline_history = model.fit(
    train_features,
    train_labels,
    batch_size=BATCH_SIZE,
    epochs=EPOCHS,
    callbacks=[early_stopping],
    validation_data=(val_features, val_labels))
Epoch 1/100
90/90 [==============================] - 2s 10ms/step - loss: 0.0110 - tp: 120.0000 - fp: 27.0000 - tn: 227423.0000 - fn: 275.0000 - accuracy: 0.9987 - precision: 0.8163 - recall: 0.3038 - auc: 0.7785 - prc: 0.3665 - val_loss: 0.0053 - val_tp: 26.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 63.0000 - val_accuracy: 0.9986 - val_precision: 0.9286 - val_recall: 0.2921 - val_auc: 0.9491 - val_prc: 0.8426
Epoch 2/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0071 - tp: 125.0000 - fp: 30.0000 - tn: 181940.0000 - fn: 181.0000 - accuracy: 0.9988 - precision: 0.8065 - recall: 0.4085 - auc: 0.8498 - prc: 0.4945 - val_loss: 0.0037 - val_tp: 49.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 40.0000 - val_accuracy: 0.9991 - val_precision: 0.9423 - val_recall: 0.5506 - val_auc: 0.9493 - val_prc: 0.8561
Epoch 3/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0061 - tp: 149.0000 - fp: 35.0000 - tn: 181935.0000 - fn: 157.0000 - accuracy: 0.9989 - precision: 0.8098 - recall: 0.4869 - auc: 0.8872 - prc: 0.5586 - val_loss: 0.0033 - val_tp: 57.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 32.0000 - val_accuracy: 0.9992 - val_precision: 0.9500 - val_recall: 0.6404 - val_auc: 0.9493 - val_prc: 0.8623
Epoch 4/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0057 - tp: 151.0000 - fp: 34.0000 - tn: 181936.0000 - fn: 155.0000 - accuracy: 0.9990 - precision: 0.8162 - recall: 0.4935 - auc: 0.8950 - prc: 0.5986 - val_loss: 0.0031 - val_tp: 60.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 29.0000 - val_accuracy: 0.9993 - val_precision: 0.9524 - val_recall: 0.6742 - val_auc: 0.9493 - val_prc: 0.8665
Epoch 5/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0054 - tp: 157.0000 - fp: 37.0000 - tn: 181933.0000 - fn: 149.0000 - accuracy: 0.9990 - precision: 0.8093 - recall: 0.5131 - auc: 0.9003 - prc: 0.6018 - val_loss: 0.0029 - val_tp: 63.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 26.0000 - val_accuracy: 0.9994 - val_precision: 0.9545 - val_recall: 0.7079 - val_auc: 0.9493 - val_prc: 0.8704
Epoch 6/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0052 - tp: 158.0000 - fp: 34.0000 - tn: 181936.0000 - fn: 148.0000 - accuracy: 0.9990 - precision: 0.8229 - recall: 0.5163 - auc: 0.9005 - prc: 0.6216 - val_loss: 0.0028 - val_tp: 67.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 22.0000 - val_accuracy: 0.9995 - val_precision: 0.9571 - val_recall: 0.7528 - val_auc: 0.9493 - val_prc: 0.8713
Epoch 7/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0049 - tp: 167.0000 - fp: 34.0000 - tn: 181936.0000 - fn: 139.0000 - accuracy: 0.9991 - precision: 0.8308 - recall: 0.5458 - auc: 0.9005 - prc: 0.6560 - val_loss: 0.0026 - val_tp: 70.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 19.0000 - val_accuracy: 0.9995 - val_precision: 0.9589 - val_recall: 0.7865 - val_auc: 0.9493 - val_prc: 0.8728
Epoch 8/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0051 - tp: 165.0000 - fp: 38.0000 - tn: 181932.0000 - fn: 141.0000 - accuracy: 0.9990 - precision: 0.8128 - recall: 0.5392 - auc: 0.8958 - prc: 0.6207 - val_loss: 0.0026 - val_tp: 70.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 19.0000 - val_accuracy: 0.9995 - val_precision: 0.9589 - val_recall: 0.7865 - val_auc: 0.9493 - val_prc: 0.8726
Epoch 9/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0049 - tp: 162.0000 - fp: 35.0000 - tn: 181935.0000 - fn: 144.0000 - accuracy: 0.9990 - precision: 0.8223 - recall: 0.5294 - auc: 0.9039 - prc: 0.6456 - val_loss: 0.0026 - val_tp: 70.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 19.0000 - val_accuracy: 0.9995 - val_precision: 0.9589 - val_recall: 0.7865 - val_auc: 0.9605 - val_prc: 0.8876
Epoch 10/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0050 - tp: 159.0000 - fp: 33.0000 - tn: 181937.0000 - fn: 147.0000 - accuracy: 0.9990 - precision: 0.8281 - recall: 0.5196 - auc: 0.9007 - prc: 0.6274 - val_loss: 0.0025 - val_tp: 70.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 19.0000 - val_accuracy: 0.9995 - val_precision: 0.9589 - val_recall: 0.7865 - val_auc: 0.9605 - val_prc: 0.8866
Epoch 11/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0048 - tp: 172.0000 - fp: 27.0000 - tn: 181943.0000 - fn: 134.0000 - accuracy: 0.9991 - precision: 0.8643 - recall: 0.5621 - auc: 0.8958 - prc: 0.6523 - val_loss: 0.0024 - val_tp: 71.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 18.0000 - val_accuracy: 0.9995 - val_precision: 0.9595 - val_recall: 0.7978 - val_auc: 0.9605 - val_prc: 0.8880
Epoch 12/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0044 - tp: 176.0000 - fp: 28.0000 - tn: 181942.0000 - fn: 130.0000 - accuracy: 0.9991 - precision: 0.8627 - recall: 0.5752 - auc: 0.8991 - prc: 0.6816 - val_loss: 0.0024 - val_tp: 72.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 17.0000 - val_accuracy: 0.9996 - val_precision: 0.9600 - val_recall: 0.8090 - val_auc: 0.9605 - val_prc: 0.8949
Epoch 13/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0044 - tp: 168.0000 - fp: 33.0000 - tn: 181937.0000 - fn: 138.0000 - accuracy: 0.9991 - precision: 0.8358 - recall: 0.5490 - auc: 0.9139 - prc: 0.6705 - val_loss: 0.0023 - val_tp: 71.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 18.0000 - val_accuracy: 0.9995 - val_precision: 0.9595 - val_recall: 0.7978 - val_auc: 0.9605 - val_prc: 0.8958
Epoch 14/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0045 - tp: 173.0000 - fp: 36.0000 - tn: 181934.0000 - fn: 133.0000 - accuracy: 0.9991 - precision: 0.8278 - recall: 0.5654 - auc: 0.9138 - prc: 0.6656 - val_loss: 0.0023 - val_tp: 71.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 18.0000 - val_accuracy: 0.9995 - val_precision: 0.9595 - val_recall: 0.7978 - val_auc: 0.9605 - val_prc: 0.8977
Epoch 15/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0045 - tp: 165.0000 - fp: 34.0000 - tn: 181936.0000 - fn: 141.0000 - accuracy: 0.9990 - precision: 0.8291 - recall: 0.5392 - auc: 0.9123 - prc: 0.6612 - val_loss: 0.0023 - val_tp: 72.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 17.0000 - val_accuracy: 0.9996 - val_precision: 0.9600 - val_recall: 0.8090 - val_auc: 0.9605 - val_prc: 0.8994
Epoch 16/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0042 - tp: 173.0000 - fp: 28.0000 - tn: 181942.0000 - fn: 133.0000 - accuracy: 0.9991 - precision: 0.8607 - recall: 0.5654 - auc: 0.9222 - prc: 0.6900 - val_loss: 0.0022 - val_tp: 76.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 13.0000 - val_accuracy: 0.9996 - val_precision: 0.9620 - val_recall: 0.8539 - val_auc: 0.9605 - val_prc: 0.8999
Epoch 17/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0050 - tp: 151.0000 - fp: 34.0000 - tn: 181936.0000 - fn: 155.0000 - accuracy: 0.9990 - precision: 0.8162 - recall: 0.4935 - auc: 0.9024 - prc: 0.6179 - val_loss: 0.0022 - val_tp: 71.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 18.0000 - val_accuracy: 0.9995 - val_precision: 0.9595 - val_recall: 0.7978 - val_auc: 0.9605 - val_prc: 0.9010
Epoch 18/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0042 - tp: 162.0000 - fp: 27.0000 - tn: 181943.0000 - fn: 144.0000 - accuracy: 0.9991 - precision: 0.8571 - recall: 0.5294 - auc: 0.9157 - prc: 0.6893 - val_loss: 0.0021 - val_tp: 78.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 11.0000 - val_accuracy: 0.9997 - val_precision: 0.9630 - val_recall: 0.8764 - val_auc: 0.9605 - val_prc: 0.9027
Epoch 19/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0043 - tp: 177.0000 - fp: 33.0000 - tn: 181937.0000 - fn: 129.0000 - accuracy: 0.9991 - precision: 0.8429 - recall: 0.5784 - auc: 0.9172 - prc: 0.6904 - val_loss: 0.0021 - val_tp: 77.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 12.0000 - val_accuracy: 0.9997 - val_precision: 0.9625 - val_recall: 0.8652 - val_auc: 0.9605 - val_prc: 0.9015
Epoch 20/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0043 - tp: 166.0000 - fp: 38.0000 - tn: 181932.0000 - fn: 140.0000 - accuracy: 0.9990 - precision: 0.8137 - recall: 0.5425 - auc: 0.9239 - prc: 0.6868 - val_loss: 0.0021 - val_tp: 76.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 13.0000 - val_accuracy: 0.9996 - val_precision: 0.9620 - val_recall: 0.8539 - val_auc: 0.9605 - val_prc: 0.9043
Epoch 21/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0041 - tp: 172.0000 - fp: 32.0000 - tn: 181938.0000 - fn: 134.0000 - accuracy: 0.9991 - precision: 0.8431 - recall: 0.5621 - auc: 0.9239 - prc: 0.7053 - val_loss: 0.0021 - val_tp: 74.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9610 - val_recall: 0.8315 - val_auc: 0.9605 - val_prc: 0.9052
Epoch 22/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0041 - tp: 183.0000 - fp: 27.0000 - tn: 181943.0000 - fn: 123.0000 - accuracy: 0.9992 - precision: 0.8714 - recall: 0.5980 - auc: 0.9190 - prc: 0.6971 - val_loss: 0.0020 - val_tp: 78.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 11.0000 - val_accuracy: 0.9997 - val_precision: 0.9630 - val_recall: 0.8764 - val_auc: 0.9606 - val_prc: 0.9041
Epoch 23/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0040 - tp: 186.0000 - fp: 30.0000 - tn: 181940.0000 - fn: 120.0000 - accuracy: 0.9992 - precision: 0.8611 - recall: 0.6078 - auc: 0.9239 - prc: 0.7045 - val_loss: 0.0020 - val_tp: 77.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 12.0000 - val_accuracy: 0.9997 - val_precision: 0.9625 - val_recall: 0.8652 - val_auc: 0.9605 - val_prc: 0.9049
Epoch 24/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0039 - tp: 178.0000 - fp: 36.0000 - tn: 181934.0000 - fn: 128.0000 - accuracy: 0.9991 - precision: 0.8318 - recall: 0.5817 - auc: 0.9256 - prc: 0.7247 - val_loss: 0.0020 - val_tp: 74.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9610 - val_recall: 0.8315 - val_auc: 0.9606 - val_prc: 0.9055
Epoch 25/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0042 - tp: 168.0000 - fp: 27.0000 - tn: 181943.0000 - fn: 138.0000 - accuracy: 0.9991 - precision: 0.8615 - recall: 0.5490 - auc: 0.9173 - prc: 0.6823 - val_loss: 0.0019 - val_tp: 77.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 12.0000 - val_accuracy: 0.9997 - val_precision: 0.9625 - val_recall: 0.8652 - val_auc: 0.9605 - val_prc: 0.9047
Epoch 26/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0041 - tp: 179.0000 - fp: 33.0000 - tn: 181937.0000 - fn: 127.0000 - accuracy: 0.9991 - precision: 0.8443 - recall: 0.5850 - auc: 0.9174 - prc: 0.7056 - val_loss: 0.0020 - val_tp: 74.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9737 - val_recall: 0.8315 - val_auc: 0.9605 - val_prc: 0.9056
Epoch 27/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0040 - tp: 187.0000 - fp: 28.0000 - tn: 181942.0000 - fn: 119.0000 - accuracy: 0.9992 - precision: 0.8698 - recall: 0.6111 - auc: 0.9125 - prc: 0.7169 - val_loss: 0.0020 - val_tp: 74.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9737 - val_recall: 0.8315 - val_auc: 0.9605 - val_prc: 0.9054
Epoch 28/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0040 - tp: 180.0000 - fp: 32.0000 - tn: 181938.0000 - fn: 126.0000 - accuracy: 0.9991 - precision: 0.8491 - recall: 0.5882 - auc: 0.9223 - prc: 0.7077 - val_loss: 0.0019 - val_tp: 76.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 13.0000 - val_accuracy: 0.9996 - val_precision: 0.9620 - val_recall: 0.8539 - val_auc: 0.9605 - val_prc: 0.9056
Epoch 29/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0041 - tp: 184.0000 - fp: 32.0000 - tn: 181938.0000 - fn: 122.0000 - accuracy: 0.9992 - precision: 0.8519 - recall: 0.6013 - auc: 0.9239 - prc: 0.6938 - val_loss: 0.0020 - val_tp: 74.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9737 - val_recall: 0.8315 - val_auc: 0.9605 - val_prc: 0.9065
Epoch 30/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0041 - tp: 172.0000 - fp: 34.0000 - tn: 181936.0000 - fn: 134.0000 - accuracy: 0.9991 - precision: 0.8350 - recall: 0.5621 - auc: 0.9272 - prc: 0.7012 - val_loss: 0.0019 - val_tp: 74.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9737 - val_recall: 0.8315 - val_auc: 0.9605 - val_prc: 0.9075
Epoch 31/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0040 - tp: 177.0000 - fp: 27.0000 - tn: 181943.0000 - fn: 129.0000 - accuracy: 0.9991 - precision: 0.8676 - recall: 0.5784 - auc: 0.9289 - prc: 0.7080 - val_loss: 0.0019 - val_tp: 76.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 13.0000 - val_accuracy: 0.9996 - val_precision: 0.9620 - val_recall: 0.8539 - val_auc: 0.9605 - val_prc: 0.9071
Epoch 32/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0040 - tp: 186.0000 - fp: 34.0000 - tn: 181936.0000 - fn: 120.0000 - accuracy: 0.9992 - precision: 0.8455 - recall: 0.6078 - auc: 0.9174 - prc: 0.7118 - val_loss: 0.0019 - val_tp: 74.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9737 - val_recall: 0.8315 - val_auc: 0.9605 - val_prc: 0.9074
Epoch 33/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0040 - tp: 185.0000 - fp: 37.0000 - tn: 181933.0000 - fn: 121.0000 - accuracy: 0.9991 - precision: 0.8333 - recall: 0.6046 - auc: 0.9256 - prc: 0.6967 - val_loss: 0.0020 - val_tp: 74.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9737 - val_recall: 0.8315 - val_auc: 0.9605 - val_prc: 0.9068
Epoch 34/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0040 - tp: 177.0000 - fp: 30.0000 - tn: 181940.0000 - fn: 129.0000 - accuracy: 0.9991 - precision: 0.8551 - recall: 0.5784 - auc: 0.9224 - prc: 0.7091 - val_loss: 0.0019 - val_tp: 74.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9737 - val_recall: 0.8315 - val_auc: 0.9605 - val_prc: 0.9069
Epoch 35/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0039 - tp: 180.0000 - fp: 30.0000 - tn: 181940.0000 - fn: 126.0000 - accuracy: 0.9991 - precision: 0.8571 - recall: 0.5882 - auc: 0.9240 - prc: 0.7232 - val_loss: 0.0019 - val_tp: 74.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9737 - val_recall: 0.8315 - val_auc: 0.9605 - val_prc: 0.9081
Epoch 36/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0038 - tp: 191.0000 - fp: 30.0000 - tn: 181940.0000 - fn: 115.0000 - accuracy: 0.9992 - precision: 0.8643 - recall: 0.6242 - auc: 0.9223 - prc: 0.7275 - val_loss: 0.0019 - val_tp: 74.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9737 - val_recall: 0.8315 - val_auc: 0.9605 - val_prc: 0.9087
Epoch 37/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0040 - tp: 177.0000 - fp: 32.0000 - tn: 181938.0000 - fn: 129.0000 - accuracy: 0.9991 - precision: 0.8469 - recall: 0.5784 - auc: 0.9256 - prc: 0.7132 - val_loss: 0.0019 - val_tp: 74.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9737 - val_recall: 0.8315 - val_auc: 0.9605 - val_prc: 0.9076
Epoch 38/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0038 - tp: 192.0000 - fp: 28.0000 - tn: 181942.0000 - fn: 114.0000 - accuracy: 0.9992 - precision: 0.8727 - recall: 0.6275 - auc: 0.9223 - prc: 0.7206 - val_loss: 0.0020 - val_tp: 74.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9737 - val_recall: 0.8315 - val_auc: 0.9605 - val_prc: 0.9083
Epoch 39/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0040 - tp: 172.0000 - fp: 27.0000 - tn: 181943.0000 - fn: 134.0000 - accuracy: 0.9991 - precision: 0.8643 - recall: 0.5621 - auc: 0.9126 - prc: 0.7024 - val_loss: 0.0019 - val_tp: 74.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9737 - val_recall: 0.8315 - val_auc: 0.9605 - val_prc: 0.9083
Epoch 40/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0039 - tp: 173.0000 - fp: 35.0000 - tn: 181935.0000 - fn: 133.0000 - accuracy: 0.9991 - precision: 0.8317 - recall: 0.5654 - auc: 0.9370 - prc: 0.7154 - val_loss: 0.0018 - val_tp: 74.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9737 - val_recall: 0.8315 - val_auc: 0.9605 - val_prc: 0.9080
Epoch 41/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0037 - tp: 186.0000 - fp: 26.0000 - tn: 181944.0000 - fn: 120.0000 - accuracy: 0.9992 - precision: 0.8774 - recall: 0.6078 - auc: 0.9289 - prc: 0.7233 - val_loss: 0.0018 - val_tp: 74.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9737 - val_recall: 0.8315 - val_auc: 0.9605 - val_prc: 0.9084
Epoch 42/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0039 - tp: 178.0000 - fp: 28.0000 - tn: 181942.0000 - fn: 128.0000 - accuracy: 0.9991 - precision: 0.8641 - recall: 0.5817 - auc: 0.9239 - prc: 0.7220 - val_loss: 0.0019 - val_tp: 74.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9737 - val_recall: 0.8315 - val_auc: 0.9605 - val_prc: 0.9078
Epoch 43/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0037 - tp: 180.0000 - fp: 25.0000 - tn: 181945.0000 - fn: 126.0000 - accuracy: 0.9992 - precision: 0.8780 - recall: 0.5882 - auc: 0.9305 - prc: 0.7387 - val_loss: 0.0018 - val_tp: 76.0000 - val_fp: 3.0000 - val_tn: 45477.0000 - val_fn: 13.0000 - val_accuracy: 0.9996 - val_precision: 0.9620 - val_recall: 0.8539 - val_auc: 0.9605 - val_prc: 0.9080
Epoch 44/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0037 - tp: 184.0000 - fp: 31.0000 - tn: 181939.0000 - fn: 122.0000 - accuracy: 0.9992 - precision: 0.8558 - recall: 0.6013 - auc: 0.9321 - prc: 0.7271 - val_loss: 0.0018 - val_tp: 74.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9737 - val_recall: 0.8315 - val_auc: 0.9605 - val_prc: 0.9083
Epoch 45/100
90/90 [==============================] - 0s 5ms/step - loss: 0.0037 - tp: 184.0000 - fp: 34.0000 - tn: 181936.0000 - fn: 122.0000 - accuracy: 0.9991 - precision: 0.8440 - recall: 0.6013 - auc: 0.9305 - prc: 0.7363 - val_loss: 0.0018 - val_tp: 76.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 13.0000 - val_accuracy: 0.9997 - val_precision: 0.9744 - val_recall: 0.8539 - val_auc: 0.9605 - val_prc: 0.9084
Epoch 46/100
81/90 [==========================>...] - ETA: 0s - loss: 0.0039 - tp: 167.0000 - fp: 27.0000 - tn: 165574.0000 - fn: 120.0000 - accuracy: 0.9991 - precision: 0.8608 - recall: 0.5819 - auc: 0.9330 - prc: 0.7267Restoring model weights from the end of the best epoch: 36.
90/90 [==============================] - 0s 5ms/step - loss: 0.0037 - tp: 182.0000 - fp: 30.0000 - tn: 181940.0000 - fn: 124.0000 - accuracy: 0.9992 - precision: 0.8585 - recall: 0.5948 - auc: 0.9322 - prc: 0.7271 - val_loss: 0.0018 - val_tp: 74.0000 - val_fp: 2.0000 - val_tn: 45478.0000 - val_fn: 15.0000 - val_accuracy: 0.9996 - val_precision: 0.9737 - val_recall: 0.8315 - val_auc: 0.9605 - val_prc: 0.9086
Epoch 46: early stopping

Check training history

In this section, you will produce plots of your model's accuracy and loss on the training and validation set. These are useful to check for overfitting, which you can learn more about in the Overfit and underfit tutorial.

Additionally, you can produce these plots for any of the metrics you created above. False negatives are included as an example.

def plot_metrics(history):
  metrics = ['loss', 'prc', 'precision', 'recall']
  for n, metric in enumerate(metrics):
    name = metric.replace("_"," ").capitalize()
    plt.subplot(2,2,n+1)
    plt.plot(history.epoch, history.history[metric], color=colors[0], label='Train')
    plt.plot(history.epoch, history.history['val_'+metric],
             color=colors[0], linestyle="--", label='Val')
    plt.xlabel('Epoch')
    plt.ylabel(name)
    if metric == 'loss':
      plt.ylim([0, plt.ylim()[1]])
    elif metric == 'auc':
      plt.ylim([0.8,1])
    else:
      plt.ylim([0,1])

    plt.legend()
plot_metrics(baseline_history)

png

Evaluate metrics

You can use a confusion matrix to summarize the actual vs. predicted labels, where the X axis is the predicted label and the Y axis is the actual label:

train_predictions_baseline = model.predict(train_features, batch_size=BATCH_SIZE)
test_predictions_baseline = model.predict(test_features, batch_size=BATCH_SIZE)
90/90 [==============================] - 0s 1ms/step
28/28 [==============================] - 0s 1ms/step
def plot_cm(labels, predictions, p=0.5):
  cm = confusion_matrix(labels, predictions > p)
  plt.figure(figsize=(5,5))
  sns.heatmap(cm, annot=True, fmt="d")
  plt.title('Confusion matrix @{:.2f}'.format(p))
  plt.ylabel('Actual label')
  plt.xlabel('Predicted label')

  print('Legitimate Transactions Detected (True Negatives): ', cm[0][0])
  print('Legitimate Transactions Incorrectly Detected (False Positives): ', cm[0][1])
  print('Fraudulent Transactions Missed (False Negatives): ', cm[1][0])
  print('Fraudulent Transactions Detected (True Positives): ', cm[1][1])
  print('Total Fraudulent Transactions: ', np.sum(cm[1]))

Evaluate your model on the test dataset and display the results for the metrics you created above:

baseline_results = model.evaluate(test_features, test_labels,
                                  batch_size=BATCH_SIZE, verbose=0)
for name, value in zip(model.metrics_names, baseline_results):
  print(name, ': ', value)
print()

plot_cm(test_labels, test_predictions_baseline)
loss :  0.0027010489720851183
tp :  75.0
fp :  12.0
tn :  56853.0
fn :  22.0
accuracy :  0.9994031190872192
precision :  0.8620689511299133
recall :  0.7731958627700806
auc :  0.9430035948753357
prc :  0.8401006460189819

Legitimate Transactions Detected (True Negatives):  56853
Legitimate Transactions Incorrectly Detected (False Positives):  12
Fraudulent Transactions Missed (False Negatives):  22
Fraudulent Transactions Detected (True Positives):  75
Total Fraudulent Transactions:  97

png

If the model had predicted everything perfectly, this would be a diagonal matrix where values off the main diagonal, indicating incorrect predictions, would be zero. In this case the matrix shows that you have relatively few false positives, meaning that there were relatively few legitimate transactions that were incorrectly flagged. However, you would likely want to have even fewer false negatives despite the cost of increasing the number of false positives. This trade off may be preferable because false negatives would allow fraudulent transactions to go through, whereas false positives may cause an email to be sent to a customer to ask them to verify their card activity.

Plot the ROC

Now plot the ROC. This plot is useful because it shows, at a glance, the range of performance the model can reach just by tuning the output threshold.

def plot_roc(name, labels, predictions, **kwargs):
  fp, tp, _ = sklearn.metrics.roc_curve(labels, predictions)

  plt.plot(100*fp, 100*tp, label=name, linewidth=2, **kwargs)
  plt.xlabel('False positives [%]')
  plt.ylabel('True positives [%]')
  plt.xlim([-0.5,20])
  plt.ylim([80,100.5])
  plt.grid(True)
  ax = plt.gca()
  ax.set_aspect('equal')
plot_roc("Train Baseline", train_labels, train_predictions_baseline, color=colors[0])
plot_roc("Test Baseline", test_labels, test_predictions_baseline, color=colors[0], linestyle='--')
plt.legend(loc='lower right');

png

Plot the AUPRC

Now plot the AUPRC. Area under the interpolated precision-recall curve, obtained by plotting (recall, precision) points for different values of the classification threshold. Depending on how it's calculated, PR AUC may be equivalent to the average precision of the model.

def plot_prc(name, labels, predictions, **kwargs):
    precision, recall, _ = sklearn.metrics.precision_recall_curve(labels, predictions)

    plt.plot(precision, recall, label=name, linewidth=2, **kwargs)
    plt.xlabel('Precision')
    plt.ylabel('Recall')
    plt.grid(True)
    ax = plt.gca()
    ax.set_aspect('equal')
plot_prc("Train Baseline", train_labels, train_predictions_baseline, color=colors[0])
plot_prc("Test Baseline", test_labels, test_predictions_baseline, color=colors[0], linestyle='--')
plt.legend(loc='lower right');

png

It looks like the precision is relatively high, but the recall and the area under the ROC curve (AUC) aren't as high as you might like. Classifiers often face challenges when trying to maximize both precision and recall, which is especially true when working with imbalanced datasets. It is important to consider the costs of different types of errors in the context of the problem you care about. In this example, a false negative (a fraudulent transaction is missed) may have a financial cost, while a false positive (a transaction is incorrectly flagged as fraudulent) may decrease user happiness.

Class weights

Calculate class weights

The goal is to identify fraudulent transactions, but you don't have very many of those positive samples to work with, so you would want to have the classifier heavily weight the few examples that are available. You can do this by passing Keras weights for each class through a parameter. These will cause the model to "pay more attention" to examples from an under-represented class.

# Scaling by total/2 helps keep the loss to a similar magnitude.
# The sum of the weights of all examples stays the same.
weight_for_0 = (1 / neg) * (total / 2.0)
weight_for_1 = (1 / pos) * (total / 2.0)

class_weight = {0: weight_for_0, 1: weight_for_1}

print('Weight for class 0: {:.2f}'.format(weight_for_0))
print('Weight for class 1: {:.2f}'.format(weight_for_1))
Weight for class 0: 0.50
Weight for class 1: 289.44

Train a model with class weights

Now try re-training and evaluating the model with class weights to see how that affects the predictions.

weighted_model = make_model()
weighted_model.load_weights(initial_weights)

weighted_history = weighted_model.fit(
    train_features,
    train_labels,
    batch_size=BATCH_SIZE,
    epochs=EPOCHS,
    callbacks=[early_stopping],
    validation_data=(val_features, val_labels),
    # The class weights go here
    class_weight=class_weight)
Epoch 1/100
90/90 [==============================] - 2s 11ms/step - loss: 2.1539 - tp: 146.0000 - fp: 110.0000 - tn: 238725.0000 - fn: 257.0000 - accuracy: 0.9985 - precision: 0.5703 - recall: 0.3623 - auc: 0.8205 - prc: 0.3581 - val_loss: 0.0052 - val_tp: 53.0000 - val_fp: 9.0000 - val_tn: 45471.0000 - val_fn: 36.0000 - val_accuracy: 0.9990 - val_precision: 0.8548 - val_recall: 0.5955 - val_auc: 0.9608 - val_prc: 0.8089
Epoch 2/100
90/90 [==============================] - 0s 5ms/step - loss: 0.8703 - tp: 179.0000 - fp: 355.0000 - tn: 181615.0000 - fn: 127.0000 - accuracy: 0.9974 - precision: 0.3352 - recall: 0.5850 - auc: 0.8990 - prc: 0.4565 - val_loss: 0.0070 - val_tp: 79.0000 - val_fp: 19.0000 - val_tn: 45461.0000 - val_fn: 10.0000 - val_accuracy: 0.9994 - val_precision: 0.8061 - val_recall: 0.8876 - val_auc: 0.9593 - val_prc: 0.8211
Epoch 3/100
90/90 [==============================] - 0s 5ms/step - loss: 0.6934 - tp: 205.0000 - fp: 876.0000 - tn: 181094.0000 - fn: 101.0000 - accuracy: 0.9946 - precision: 0.1896 - recall: 0.6699 - auc: 0.9160 - prc: 0.4276 - val_loss: 0.0109 - val_tp: 79.0000 - val_fp: 44.0000 - val_tn: 45436.0000 - val_fn: 10.0000 - val_accuracy: 0.9988 - val_precision: 0.6423 - val_recall: 0.8876 - val_auc: 0.9677 - val_prc: 0.8001
Epoch 4/100
90/90 [==============================] - 0s 5ms/step - loss: 0.6614 - tp: 208.0000 - fp: 1389.0000 - tn: 180581.0000 - fn: 98.0000 - accuracy: 0.9918 - precision: 0.1302 - recall: 0.6797 - auc: 0.9066 - prc: 0.4035 - val_loss: 0.0157 - val_tp: 79.0000 - val_fp: 134.0000 - val_tn: 45346.0000 - val_fn: 10.0000 - val_accuracy: 0.9968 - val_precision: 0.3709 - val_recall: 0.8876 - val_auc: 0.9703 - val_prc: 0.7471
Epoch 5/100
90/90 [==============================] - 0s 5ms/step - loss: 0.5179 - tp: 230.0000 - fp: 1966.0000 - tn: 180004.0000 - fn: 76.0000 - accuracy: 0.9888 - precision: 0.1047 - recall: 0.7516 - auc: 0.9276 - prc: 0.3460 - val_loss: 0.0225 - val_tp: 81.0000 - val_fp: 247.0000 - val_tn: 45233.0000 - val_fn: 8.0000 - val_accuracy: 0.9944 - val_precision: 0.2470 - val_recall: 0.9101 - val_auc: 0.9802 - val_prc: 0.7475
Epoch 6/100
90/90 [==============================] - 0s 5ms/step - loss: 0.4492 - tp: 242.0000 - fp: 2578.0000 - tn: 179392.0000 - fn: 64.0000 - accuracy: 0.9855 - precision: 0.0858 - recall: 0.7908 - auc: 0.9318 - prc: 0.2897 - val_loss: 0.0308 - val_tp: 81.0000 - val_fp: 387.0000 - val_tn: 45093.0000 - val_fn: 8.0000 - val_accuracy: 0.9913 - val_precision: 0.1731 - val_recall: 0.9101 - val_auc: 0.9832 - val_prc: 0.7319
Epoch 7/100
90/90 [==============================] - 0s 5ms/step - loss: 0.4441 - tp: 241.0000 - fp: 3327.0000 - tn: 178643.0000 - fn: 65.0000 - accuracy: 0.9814 - precision: 0.0675 - recall: 0.7876 - auc: 0.9266 - prc: 0.2571 - val_loss: 0.0394 - val_tp: 82.0000 - val_fp: 483.0000 - val_tn: 44997.0000 - val_fn: 7.0000 - val_accuracy: 0.9892 - val_precision: 0.1451 - val_recall: 0.9213 - val_auc: 0.9843 - val_prc: 0.7269
Epoch 8/100
90/90 [==============================] - 0s 5ms/step - loss: 0.3702 - tp: 254.0000 - fp: 4036.0000 - tn: 177934.0000 - fn: 52.0000 - accuracy: 0.9776 - precision: 0.0592 - recall: 0.8301 - auc: 0.9434 - prc: 0.2348 - val_loss: 0.0460 - val_tp: 82.0000 - val_fp: 563.0000 - val_tn: 44917.0000 - val_fn: 7.0000 - val_accuracy: 0.9875 - val_precision: 0.1271 - val_recall: 0.9213 - val_auc: 0.9844 - val_prc: 0.7069
Epoch 9/100
90/90 [==============================] - 0s 5ms/step - loss: 0.4050 - tp: 249.0000 - fp: 4242.0000 - tn: 177728.0000 - fn: 57.0000 - accuracy: 0.9764 - precision: 0.0554 - recall: 0.8137 - auc: 0.9344 - prc: 0.2347 - val_loss: 0.0530 - val_tp: 82.0000 - val_fp: 663.0000 - val_tn: 44817.0000 - val_fn: 7.0000 - val_accuracy: 0.9853 - val_precision: 0.1101 - val_recall: 0.9213 - val_auc: 0.9851 - val_prc: 0.7078
Epoch 10/100
90/90 [==============================] - 0s 5ms/step - loss: 0.3369 - tp: 256.0000 - fp: 4998.0000 - tn: 176972.0000 - fn: 50.0000 - accuracy: 0.9723 - precision: 0.0487 - recall: 0.8366 - auc: 0.9531 - prc: 0.1939 - val_loss: 0.0620 - val_tp: 82.0000 - val_fp: 742.0000 - val_tn: 44738.0000 - val_fn: 7.0000 - val_accuracy: 0.9836 - val_precision: 0.0995 - val_recall: 0.9213 - val_auc: 0.9890 - val_prc: 0.6888
Epoch 11/100
90/90 [==============================] - 0s 5ms/step - loss: 0.3868 - tp: 251.0000 - fp: 5718.0000 - tn: 176252.0000 - fn: 55.0000 - accuracy: 0.9683 - precision: 0.0421 - recall: 0.8203 - auc: 0.9369 - prc: 0.1663 - val_loss: 0.0717 - val_tp: 82.0000 - val_fp: 827.0000 - val_tn: 44653.0000 - val_fn: 7.0000 - val_accuracy: 0.9817 - val_precision: 0.0902 - val_recall: 0.9213 - val_auc: 0.9910 - val_prc: 0.6586
Epoch 12/100
85/90 [===========================>..] - ETA: 0s - loss: 0.3007 - tp: 256.0000 - fp: 5679.0000 - tn: 168105.0000 - fn: 40.0000 - accuracy: 0.9671 - precision: 0.0431 - recall: 0.8649 - auc: 0.9564 - prc: 0.1717Restoring model weights from the end of the best epoch: 2.
90/90 [==============================] - 0s 6ms/step - loss: 0.2947 - tp: 265.0000 - fp: 5962.0000 - tn: 176008.0000 - fn: 41.0000 - accuracy: 0.9671 - precision: 0.0426 - recall: 0.8660 - auc: 0.9572 - prc: 0.1718 - val_loss: 0.0755 - val_tp: 83.0000 - val_fp: 858.0000 - val_tn: 44622.0000 - val_fn: 6.0000 - val_accuracy: 0.9810 - val_precision: 0.0882 - val_recall: 0.9326 - val_auc: 0.9912 - val_prc: 0.6539
Epoch 12: early stopping

Check training history

plot_metrics(weighted_history)

png

Evaluate metrics

train_predictions_weighted = weighted_model.predict(train_features, batch_size=BATCH_SIZE)
test_predictions_weighted = weighted_model.predict(test_features, batch_size=BATCH_SIZE)
90/90 [==============================] - 0s 1ms/step
28/28 [==============================] - 0s 1ms/step
weighted_results = weighted_model.evaluate(test_features, test_labels,
                                           batch_size=BATCH_SIZE, verbose=0)
for name, value in zip(weighted_model.metrics_names, weighted_results):
  print(name, ': ', value)
print()

plot_cm(test_labels, test_predictions_weighted)
loss :  0.007611860986799002
tp :  79.0
fp :  31.0
tn :  56834.0
fn :  18.0
accuracy :  0.9991397857666016
precision :  0.7181817889213562
recall :  0.8144329786300659
auc :  0.9610110521316528
prc :  0.7328379154205322

Legitimate Transactions Detected (True Negatives):  56834
Legitimate Transactions Incorrectly Detected (False Positives):  31
Fraudulent Transactions Missed (False Negatives):  18
Fraudulent Transactions Detected (True Positives):  79
Total Fraudulent Transactions:  97

png

Here you can see that with class weights the accuracy and precision are lower because there are more false positives, but conversely the recall and AUC are higher because the model also found more true positives. Despite having lower accuracy, this model has higher recall (and identifies more fraudulent transactions). Of course, there is a cost to both types of error (you wouldn't want to bug users by flagging too many legitimate transactions as fraudulent, either). Carefully consider the trade-offs between these different types of errors for your application.

Plot the ROC

plot_roc("Train Baseline", train_labels, train_predictions_baseline, color=colors[0])
plot_roc("Test Baseline", test_labels, test_predictions_baseline, color=colors[0], linestyle='--')

plot_roc("Train Weighted", train_labels, train_predictions_weighted, color=colors[1])
plot_roc("Test Weighted", test_labels, test_predictions_weighted, color=colors[1], linestyle='--')


plt.legend(loc='lower right');

png

Plot the AUPRC

plot_prc("Train Baseline", train_labels, train_predictions_baseline, color=colors[0])
plot_prc("Test Baseline", test_labels, test_predictions_baseline, color=colors[0], linestyle='--')

plot_prc("Train Weighted", train_labels, train_predictions_weighted, color=colors[1])
plot_prc("Test Weighted", test_labels, test_predictions_weighted, color=colors[1], linestyle='--')


plt.legend(loc='lower right');

png

Oversampling

Oversample the minority class

A related approach would be to resample the dataset by oversampling the minority class.

pos_features = train_features[bool_train_labels]
neg_features = train_features[~bool_train_labels]

pos_labels = train_labels[bool_train_labels]
neg_labels = train_labels[~bool_train_labels]

Using NumPy

You can balance the dataset manually by choosing the right number of random indices from the positive examples:

ids = np.arange(len(pos_features))
choices = np.random.choice(ids, len(neg_features))

res_pos_features = pos_features[choices]
res_pos_labels = pos_labels[choices]

res_pos_features.shape
(181970, 29)
resampled_features = np.concatenate([res_pos_features, neg_features], axis=0)
resampled_labels = np.concatenate([res_pos_labels, neg_labels], axis=0)

order = np.arange(len(resampled_labels))
np.random.shuffle(order)
resampled_features = resampled_features[order]
resampled_labels = resampled_labels[order]

resampled_features.shape
(363940, 29)

Using tf.data

If you're using tf.data the easiest way to produce balanced examples is to start with a positive and a negative dataset, and merge them. See the tf.data guide for more examples.

BUFFER_SIZE = 100000

def make_ds(features, labels):
  ds = tf.data.Dataset.from_tensor_slices((features, labels))#.cache()
  ds = ds.shuffle(BUFFER_SIZE).repeat()
  return ds

pos_ds = make_ds(pos_features, pos_labels)
neg_ds = make_ds(neg_features, neg_labels)

Each dataset provides (feature, label) pairs:

for features, label in pos_ds.take(1):
  print("Features:\n", features.numpy())
  print()
  print("Label: ", label.numpy())
Features:
 [ 0.22899304  1.50596855 -3.71909275  3.14371342 -1.7545715  -1.63736056
 -3.76668611  1.05061198 -0.65332479 -4.98126673  5.         -5.
  0.63854757 -5.          0.59022548 -5.         -5.         -1.5983673
  2.77613026  0.71590668  1.03409401  0.1931581   1.06943331  0.21723923
 -3.6675724   0.69625522  1.83098431  0.52810236 -1.45113469]

Label:  1

Merge the two together using tf.data.Dataset.sample_from_datasets:

resampled_ds = tf.data.Dataset.sample_from_datasets([pos_ds, neg_ds], weights=[0.5, 0.5])
resampled_ds = resampled_ds.batch(BATCH_SIZE).prefetch(2)
for features, label in resampled_ds.take(1):
  print(label.numpy().mean())
0.50537109375

To use this dataset, you'll need the number of steps per epoch.

The definition of "epoch" in this case is less clear. Say it's the number of batches required to see each negative example once:

resampled_steps_per_epoch = np.ceil(2.0*neg/BATCH_SIZE)
resampled_steps_per_epoch
278.0

Train on the oversampled data

Now try training the model with the resampled data set instead of using class weights to see how these methods compare.

resampled_model = make_model()
resampled_model.load_weights(initial_weights)

# Reset the bias to zero, since this dataset is balanced.
output_layer = resampled_model.layers[-1] 
output_layer.bias.assign([0])

val_ds = tf.data.Dataset.from_tensor_slices((val_features, val_labels)).cache()
val_ds = val_ds.batch(BATCH_SIZE).prefetch(2) 

resampled_history = resampled_model.fit(
    resampled_ds,
    epochs=EPOCHS,
    steps_per_epoch=resampled_steps_per_epoch,
    callbacks=[early_stopping],
    validation_data=val_ds)
Epoch 1/100
278/278 [==============================] - 8s 24ms/step - loss: 0.4340 - tp: 231930.0000 - fp: 54583.0000 - tn: 286809.0000 - fn: 52984.0000 - accuracy: 0.8283 - precision: 0.8095 - recall: 0.8140 - auc: 0.9024 - prc: 0.9193 - val_loss: 0.1959 - val_tp: 83.0000 - val_fp: 1251.0000 - val_tn: 44229.0000 - val_fn: 6.0000 - val_accuracy: 0.9724 - val_precision: 0.0622 - val_recall: 0.9326 - val_auc: 0.9820 - val_prc: 0.8436
Epoch 2/100
278/278 [==============================] - 6s 22ms/step - loss: 0.2047 - tp: 251779.0000 - fp: 15781.0000 - tn: 269115.0000 - fn: 32669.0000 - accuracy: 0.9149 - precision: 0.9410 - recall: 0.8851 - auc: 0.9722 - prc: 0.9769 - val_loss: 0.1156 - val_tp: 84.0000 - val_fp: 945.0000 - val_tn: 44535.0000 - val_fn: 5.0000 - val_accuracy: 0.9792 - val_precision: 0.0816 - val_recall: 0.9438 - val_auc: 0.9938 - val_prc: 0.8444
Epoch 3/100
278/278 [==============================] - 6s 22ms/step - loss: 0.1624 - tp: 256549.0000 - fp: 11170.0000 - tn: 273954.0000 - fn: 27671.0000 - accuracy: 0.9318 - precision: 0.9583 - recall: 0.9026 - auc: 0.9837 - prc: 0.9855 - val_loss: 0.0876 - val_tp: 84.0000 - val_fp: 885.0000 - val_tn: 44595.0000 - val_fn: 5.0000 - val_accuracy: 0.9805 - val_precision: 0.0867 - val_recall: 0.9438 - val_auc: 0.9956 - val_prc: 0.8389
Epoch 4/100
278/278 [==============================] - 6s 22ms/step - loss: 0.1427 - tp: 260238.0000 - fp: 9686.0000 - tn: 274698.0000 - fn: 24722.0000 - accuracy: 0.9396 - precision: 0.9641 - recall: 0.9132 - auc: 0.9877 - prc: 0.9888 - val_loss: 0.0742 - val_tp: 84.0000 - val_fp: 799.0000 - val_tn: 44681.0000 - val_fn: 5.0000 - val_accuracy: 0.9824 - val_precision: 0.0951 - val_recall: 0.9438 - val_auc: 0.9956 - val_prc: 0.8496
Epoch 5/100
278/278 [==============================] - 6s 22ms/step - loss: 0.1314 - tp: 262727.0000 - fp: 9137.0000 - tn: 275468.0000 - fn: 22012.0000 - accuracy: 0.9453 - precision: 0.9664 - recall: 0.9227 - auc: 0.9898 - prc: 0.9905 - val_loss: 0.0664 - val_tp: 84.0000 - val_fp: 715.0000 - val_tn: 44765.0000 - val_fn: 5.0000 - val_accuracy: 0.9842 - val_precision: 0.1051 - val_recall: 0.9438 - val_auc: 0.9948 - val_prc: 0.8321
Epoch 6/100
278/278 [==============================] - 6s 22ms/step - loss: 0.1234 - tp: 263237.0000 - fp: 8706.0000 - tn: 276245.0000 - fn: 21156.0000 - accuracy: 0.9476 - precision: 0.9680 - recall: 0.9256 - auc: 0.9912 - prc: 0.9916 - val_loss: 0.0615 - val_tp: 84.0000 - val_fp: 667.0000 - val_tn: 44813.0000 - val_fn: 5.0000 - val_accuracy: 0.9853 - val_precision: 0.1119 - val_recall: 0.9438 - val_auc: 0.9937 - val_prc: 0.8333
Epoch 7/100
278/278 [==============================] - 6s 22ms/step - loss: 0.1159 - tp: 263947.0000 - fp: 8304.0000 - tn: 276910.0000 - fn: 20183.0000 - accuracy: 0.9500 - precision: 0.9695 - recall: 0.9290 - auc: 0.9925 - prc: 0.9926 - val_loss: 0.0566 - val_tp: 84.0000 - val_fp: 634.0000 - val_tn: 44846.0000 - val_fn: 5.0000 - val_accuracy: 0.9860 - val_precision: 0.1170 - val_recall: 0.9438 - val_auc: 0.9926 - val_prc: 0.8065
Epoch 8/100
278/278 [==============================] - 6s 22ms/step - loss: 0.1106 - tp: 265655.0000 - fp: 8250.0000 - tn: 276322.0000 - fn: 19117.0000 - accuracy: 0.9519 - precision: 0.9699 - recall: 0.9329 - auc: 0.9933 - prc: 0.9933 - val_loss: 0.0521 - val_tp: 84.0000 - val_fp: 603.0000 - val_tn: 44877.0000 - val_fn: 5.0000 - val_accuracy: 0.9867 - val_precision: 0.1223 - val_recall: 0.9438 - val_auc: 0.9915 - val_prc: 0.8081
Epoch 9/100
278/278 [==============================] - 6s 22ms/step - loss: 0.1039 - tp: 266623.0000 - fp: 8121.0000 - tn: 276600.0000 - fn: 18000.0000 - accuracy: 0.9541 - precision: 0.9704 - recall: 0.9368 - auc: 0.9941 - prc: 0.9940 - val_loss: 0.0490 - val_tp: 84.0000 - val_fp: 613.0000 - val_tn: 44867.0000 - val_fn: 5.0000 - val_accuracy: 0.9864 - val_precision: 0.1205 - val_recall: 0.9438 - val_auc: 0.9905 - val_prc: 0.7927
Epoch 10/100
278/278 [==============================] - 6s 22ms/step - loss: 0.0988 - tp: 267216.0000 - fp: 8259.0000 - tn: 277082.0000 - fn: 16787.0000 - accuracy: 0.9560 - precision: 0.9700 - recall: 0.9409 - auc: 0.9947 - prc: 0.9944 - val_loss: 0.0444 - val_tp: 84.0000 - val_fp: 606.0000 - val_tn: 44874.0000 - val_fn: 5.0000 - val_accuracy: 0.9866 - val_precision: 0.1217 - val_recall: 0.9438 - val_auc: 0.9825 - val_prc: 0.8188
Epoch 11/100
278/278 [==============================] - 6s 22ms/step - loss: 0.0935 - tp: 269345.0000 - fp: 8452.0000 - tn: 276042.0000 - fn: 15505.0000 - accuracy: 0.9579 - precision: 0.9696 - recall: 0.9456 - auc: 0.9953 - prc: 0.9950 - val_loss: 0.0425 - val_tp: 84.0000 - val_fp: 639.0000 - val_tn: 44841.0000 - val_fn: 5.0000 - val_accuracy: 0.9859 - val_precision: 0.1162 - val_recall: 0.9438 - val_auc: 0.9827 - val_prc: 0.8102
Epoch 12/100
278/278 [==============================] - 6s 22ms/step - loss: 0.0892 - tp: 270602.0000 - fp: 8663.0000 - tn: 275947.0000 - fn: 14132.0000 - accuracy: 0.9600 - precision: 0.9690 - recall: 0.9504 - auc: 0.9957 - prc: 0.9953 - val_loss: 0.0381 - val_tp: 84.0000 - val_fp: 590.0000 - val_tn: 44890.0000 - val_fn: 5.0000 - val_accuracy: 0.9869 - val_precision: 0.1246 - val_recall: 0.9438 - val_auc: 0.9829 - val_prc: 0.8100
Epoch 13/100
278/278 [==============================] - 6s 22ms/step - loss: 0.0850 - tp: 272193.0000 - fp: 8673.0000 - tn: 275230.0000 - fn: 13248.0000 - accuracy: 0.9615 - precision: 0.9691 - recall: 0.9536 - auc: 0.9960 - prc: 0.9957 - val_loss: 0.0342 - val_tp: 84.0000 - val_fp: 551.0000 - val_tn: 44929.0000 - val_fn: 5.0000 - val_accuracy: 0.9878 - val_precision: 0.1323 - val_recall: 0.9438 - val_auc: 0.9833 - val_prc: 0.8184
Epoch 14/100
278/278 [==============================] - ETA: 0s - loss: 0.0812 - tp: 271836.0000 - fp: 8737.0000 - tn: 276444.0000 - fn: 12327.0000 - accuracy: 0.9630 - precision: 0.9689 - recall: 0.9566 - auc: 0.9963 - prc: 0.9959Restoring model weights from the end of the best epoch: 4.
278/278 [==============================] - 6s 22ms/step - loss: 0.0812 - tp: 271836.0000 - fp: 8737.0000 - tn: 276444.0000 - fn: 12327.0000 - accuracy: 0.9630 - precision: 0.9689 - recall: 0.9566 - auc: 0.9963 - prc: 0.9959 - val_loss: 0.0327 - val_tp: 84.0000 - val_fp: 558.0000 - val_tn: 44922.0000 - val_fn: 5.0000 - val_accuracy: 0.9876 - val_precision: 0.1308 - val_recall: 0.9438 - val_auc: 0.9790 - val_prc: 0.8093
Epoch 14: early stopping

If the training process were considering the whole dataset on each gradient update, this oversampling would be basically identical to the class weighting.

But when training the model batch-wise, as you did here, the oversampled data provides a smoother gradient signal: Instead of each positive example being shown in one batch with a large weight, they're shown in many different batches each time with a small weight.

This smoother gradient signal makes it easier to train the model.

Check training history

Note that the distributions of metrics will be different here, because the training data has a totally different distribution from the validation and test data.

plot_metrics(resampled_history)

png

Re-train

Because training is easier on the balanced data, the above training procedure may overfit quickly.

So break up the epochs to give the tf.keras.callbacks.EarlyStopping finer control over when to stop training.

resampled_model = make_model()
resampled_model.load_weights(initial_weights)

# Reset the bias to zero, since this dataset is balanced.
output_layer = resampled_model.layers[-1] 
output_layer.bias.assign([0])

resampled_history = resampled_model.fit(
    resampled_ds,
    # These are not real epochs
    steps_per_epoch=20,
    epochs=10*EPOCHS,
    callbacks=[early_stopping],
    validation_data=(val_ds))
Epoch 1/1000
20/20 [==============================] - 2s 48ms/step - loss: 1.2136 - tp: 9872.0000 - fp: 7443.0000 - tn: 58573.0000 - fn: 10641.0000 - accuracy: 0.7910 - precision: 0.5701 - recall: 0.4813 - auc: 0.8047 - prc: 0.6386 - val_loss: 0.5450 - val_tp: 73.0000 - val_fp: 12865.0000 - val_tn: 32615.0000 - val_fn: 16.0000 - val_accuracy: 0.7173 - val_precision: 0.0056 - val_recall: 0.8202 - val_auc: 0.8759 - val_prc: 0.2681
Epoch 2/1000
20/20 [==============================] - 0s 24ms/step - loss: 0.6909 - tp: 14318.0000 - fp: 7094.0000 - tn: 13526.0000 - fn: 6022.0000 - accuracy: 0.6798 - precision: 0.6687 - recall: 0.7039 - auc: 0.7481 - prc: 0.8225 - val_loss: 0.5363 - val_tp: 83.0000 - val_fp: 12240.0000 - val_tn: 33240.0000 - val_fn: 6.0000 - val_accuracy: 0.7313 - val_precision: 0.0067 - val_recall: 0.9326 - val_auc: 0.9476 - val_prc: 0.7202
Epoch 3/1000
20/20 [==============================] - 0s 25ms/step - loss: 0.5307 - tp: 16271.0000 - fp: 6374.0000 - tn: 14085.0000 - fn: 4230.0000 - accuracy: 0.7411 - precision: 0.7185 - recall: 0.7937 - auc: 0.8337 - prc: 0.8849 - val_loss: 0.4958 - val_tp: 83.0000 - val_fp: 10068.0000 - val_tn: 35412.0000 - val_fn: 6.0000 - val_accuracy: 0.7789 - val_precision: 0.0082 - val_recall: 0.9326 - val_auc: 0.9530 - val_prc: 0.8124
Epoch 4/1000
20/20 [==============================] - 0s 25ms/step - loss: 0.4556 - tp: 16825.0000 - fp: 5537.0000 - tn: 15032.0000 - fn: 3566.0000 - accuracy: 0.7778 - precision: 0.7524 - recall: 0.8251 - auc: 0.8729 - prc: 0.9121 - val_loss: 0.4480 - val_tp: 83.0000 - val_fp: 7414.0000 - val_tn: 38066.0000 - val_fn: 6.0000 - val_accuracy: 0.8372 - val_precision: 0.0111 - val_recall: 0.9326 - val_auc: 0.9568 - val_prc: 0.8243
Epoch 5/1000
20/20 [==============================] - 1s 26ms/step - loss: 0.4119 - tp: 17121.0000 - fp: 4743.0000 - tn: 15896.0000 - fn: 3200.0000 - accuracy: 0.8061 - precision: 0.7831 - recall: 0.8425 - auc: 0.8935 - prc: 0.9255 - val_loss: 0.4031 - val_tp: 83.0000 - val_fp: 5408.0000 - val_tn: 40072.0000 - val_fn: 6.0000 - val_accuracy: 0.8812 - val_precision: 0.0151 - val_recall: 0.9326 - val_auc: 0.9606 - val_prc: 0.8345
Epoch 6/1000
20/20 [==============================] - 0s 25ms/step - loss: 0.3794 - tp: 17405.0000 - fp: 4076.0000 - tn: 16314.0000 - fn: 3165.0000 - accuracy: 0.8232 - precision: 0.8103 - recall: 0.8461 - auc: 0.9050 - prc: 0.9343 - val_loss: 0.3636 - val_tp: 83.0000 - val_fp: 4083.0000 - val_tn: 41397.0000 - val_fn: 6.0000 - val_accuracy: 0.9103 - val_precision: 0.0199 - val_recall: 0.9326 - val_auc: 0.9644 - val_prc: 0.8416
Epoch 7/1000
20/20 [==============================] - 0s 25ms/step - loss: 0.3561 - tp: 17458.0000 - fp: 3654.0000 - tn: 16808.0000 - fn: 3040.0000 - accuracy: 0.8366 - precision: 0.8269 - recall: 0.8517 - auc: 0.9152 - prc: 0.9404 - val_loss: 0.3297 - val_tp: 83.0000 - val_fp: 3185.0000 - val_tn: 42295.0000 - val_fn: 6.0000 - val_accuracy: 0.9300 - val_precision: 0.0254 - val_recall: 0.9326 - val_auc: 0.9676 - val_prc: 0.8470
Epoch 8/1000
20/20 [==============================] - 0s 25ms/step - loss: 0.3362 - tp: 17432.0000 - fp: 3154.0000 - tn: 17335.0000 - fn: 3039.0000 - accuracy: 0.8488 - precision: 0.8468 - recall: 0.8515 - auc: 0.9224 - prc: 0.9443 - val_loss: 0.3007 - val_tp: 83.0000 - val_fp: 2577.0000 - val_tn: 42903.0000 - val_fn: 6.0000 - val_accuracy: 0.9433 - val_precision: 0.0312 - val_recall: 0.9326 - val_auc: 0.9704 - val_prc: 0.8533
Epoch 9/1000
20/20 [==============================] - 1s 26ms/step - loss: 0.3112 - tp: 17539.0000 - fp: 2790.0000 - tn: 17780.0000 - fn: 2851.0000 - accuracy: 0.8623 - precision: 0.8628 - recall: 0.8602 - auc: 0.9331 - prc: 0.9512 - val_loss: 0.2758 - val_tp: 83.0000 - val_fp: 2157.0000 - val_tn: 43323.0000 - val_fn: 6.0000 - val_accuracy: 0.9525 - val_precision: 0.0371 - val_recall: 0.9326 - val_auc: 0.9728 - val_prc: 0.8547
Epoch 10/1000
20/20 [==============================] - 0s 25ms/step - loss: 0.2921 - tp: 17652.0000 - fp: 2438.0000 - tn: 18075.0000 - fn: 2795.0000 - accuracy: 0.8722 - precision: 0.8786 - recall: 0.8633 - auc: 0.9405 - prc: 0.9562 - val_loss: 0.2540 - val_tp: 83.0000 - val_fp: 1839.0000 - val_tn: 43641.0000 - val_fn: 6.0000 - val_accuracy: 0.9595 - val_precision: 0.0432 - val_recall: 0.9326 - val_auc: 0.9750 - val_prc: 0.8565
Epoch 11/1000
20/20 [==============================] - 0s 25ms/step - loss: 0.2784 - tp: 17722.0000 - fp: 2102.0000 - tn: 18357.0000 - fn: 2779.0000 - accuracy: 0.8808 - precision: 0.8940 - recall: 0.8644 - auc: 0.9455 - prc: 0.9591 - val_loss: 0.2353 - val_tp: 83.0000 - val_fp: 1671.0000 - val_tn: 43809.0000 - val_fn: 6.0000 - val_accuracy: 0.9632 - val_precision: 0.0473 - val_recall: 0.9326 - val_auc: 0.9773 - val_prc: 0.8597
Epoch 12/1000
20/20 [==============================] - 0s 25ms/step - loss: 0.2685 - tp: 17812.0000 - fp: 1917.0000 - tn: 18473.0000 - fn: 2758.0000 - accuracy: 0.8859 - precision: 0.9028 - recall: 0.8659 - auc: 0.9493 - prc: 0.9617 - val_loss: 0.2195 - val_tp: 83.0000 - val_fp: 1506.0000 - val_tn: 43974.0000 - val_fn: 6.0000 - val_accuracy: 0.9668 - val_precision: 0.0522 - val_recall: 0.9326 - val_auc: 0.9791 - val_prc: 0.8619
Epoch 13/1000
20/20 [==============================] - 0s 25ms/step - loss: 0.2554 - tp: 17822.0000 - fp: 1762.0000 - tn: 18716.0000 - fn: 2660.0000 - accuracy: 0.8920 - precision: 0.9100 - recall: 0.8701 - auc: 0.9545 - prc: 0.9649 - val_loss: 0.2055 - val_tp: 83.0000 - val_fp: 1330.0000 - val_tn: 44150.0000 - val_fn: 6.0000 - val_accuracy: 0.9707 - val_precision: 0.0587 - val_recall: 0.9326 - val_auc: 0.9808 - val_prc: 0.8533
Epoch 14/1000
20/20 [==============================] - 1s 27ms/step - loss: 0.2454 - tp: 17851.0000 - fp: 1545.0000 - tn: 18906.0000 - fn: 2658.0000 - accuracy: 0.8974 - precision: 0.9203 - recall: 0.8704 - auc: 0.9584 - prc: 0.9675 - val_loss: 0.1938 - val_tp: 83.0000 - val_fp: 1229.0000 - val_tn: 44251.0000 - val_fn: 6.0000 - val_accuracy: 0.9729 - val_precision: 0.0633 - val_recall: 0.9326 - val_auc: 0.9825 - val_prc: 0.8456
Epoch 15/1000
20/20 [==============================] - 1s 26ms/step - loss: 0.2388 - tp: 17954.0000 - fp: 1528.0000 - tn: 18861.0000 - fn: 2617.0000 - accuracy: 0.8988 - precision: 0.9216 - recall: 0.8728 - auc: 0.9607 - prc: 0.9692 - val_loss: 0.1832 - val_tp: 83.0000 - val_fp: 1168.0000 - val_tn: 44312.0000 - val_fn: 6.0000 - val_accuracy: 0.9742 - val_precision: 0.0663 - val_recall: 0.9326 - val_auc: 0.9837 - val_prc: 0.8365
Epoch 16/1000
20/20 [==============================] - 0s 26ms/step - loss: 0.2314 - tp: 17878.0000 - fp: 1375.0000 - tn: 19124.0000 - fn: 2583.0000 - accuracy: 0.9034 - precision: 0.9286 - recall: 0.8738 - auc: 0.9636 - prc: 0.9707 - val_loss: 0.1736 - val_tp: 83.0000 - val_fp: 1117.0000 - val_tn: 44363.0000 - val_fn: 6.0000 - val_accuracy: 0.9754 - val_precision: 0.0692 - val_recall: 0.9326 - val_auc: 0.9849 - val_prc: 0.8367
Epoch 17/1000
20/20 [==============================] - 1s 26ms/step - loss: 0.2238 - tp: 18066.0000 - fp: 1290.0000 - tn: 19116.0000 - fn: 2488.0000 - accuracy: 0.9078 - precision: 0.9334 - recall: 0.8790 - auc: 0.9664 - prc: 0.9729 - val_loss: 0.1653 - val_tp: 82.0000 - val_fp: 1087.0000 - val_tn: 44393.0000 - val_fn: 7.0000 - val_accuracy: 0.9760 - val_precision: 0.0701 - val_recall: 0.9213 - val_auc: 0.9859 - val_prc: 0.8382
Epoch 18/1000
20/20 [==============================] - 0s 26ms/step - loss: 0.2171 - tp: 18149.0000 - fp: 1226.0000 - tn: 19146.0000 - fn: 2439.0000 - accuracy: 0.9105 - precision: 0.9367 - recall: 0.8815 - auc: 0.9683 - prc: 0.9744 - val_loss: 0.1579 - val_tp: 82.0000 - val_fp: 1058.0000 - val_tn: 44422.0000 - val_fn: 7.0000 - val_accuracy: 0.9766 - val_precision: 0.0719 - val_recall: 0.9213 - val_auc: 0.9869 - val_prc: 0.8398
Epoch 19/1000
20/20 [==============================] - 0s 26ms/step - loss: 0.2142 - tp: 17994.0000 - fp: 1225.0000 - tn: 19252.0000 - fn: 2489.0000 - accuracy: 0.9093 - precision: 0.9363 - recall: 0.8785 - auc: 0.9695 - prc: 0.9747 - val_loss: 0.1513 - val_tp: 83.0000 - val_fp: 1039.0000 - val_tn: 44441.0000 - val_fn: 6.0000 - val_accuracy: 0.9771 - val_precision: 0.0740 - val_recall: 0.9326 - val_auc: 0.9879 - val_prc: 0.8404
Epoch 20/1000
20/20 [==============================] - 1s 26ms/step - loss: 0.2042 - tp: 18013.0000 - fp: 1140.0000 - tn: 19459.0000 - fn: 2348.0000 - accuracy: 0.9148 - precision: 0.9405 - recall: 0.8847 - auc: 0.9724 - prc: 0.9767 - val_loss: 0.1455 - val_tp: 84.0000 - val_fp: 1023.0000 - val_tn: 44457.0000 - val_fn: 5.0000 - val_accuracy: 0.9774 - val_precision: 0.0759 - val_recall: 0.9438 - val_auc: 0.9891 - val_prc: 0.8405
Epoch 21/1000
20/20 [==============================] - 1s 27ms/step - loss: 0.2030 - tp: 18250.0000 - fp: 1082.0000 - tn: 19253.0000 - fn: 2375.0000 - accuracy: 0.9156 - precision: 0.9440 - recall: 0.8848 - auc: 0.9729 - prc: 0.9775 - val_loss: 0.1402 - val_tp: 84.0000 - val_fp: 1007.0000 - val_tn: 44473.0000 - val_fn: 5.0000 - val_accuracy: 0.9778 - val_precision: 0.0770 - val_recall: 0.9438 - val_auc: 0.9899 - val_prc: 0.8418
Epoch 22/1000
20/20 [==============================] - ETA: 0s - loss: 0.1998 - tp: 17980.0000 - fp: 1062.0000 - tn: 19580.0000 - fn: 2338.0000 - accuracy: 0.9170 - precision: 0.9442 - recall: 0.8849 - auc: 0.9737 - prc: 0.9776Restoring model weights from the end of the best epoch: 12.
20/20 [==============================] - 0s 25ms/step - loss: 0.1998 - tp: 17980.0000 - fp: 1062.0000 - tn: 19580.0000 - fn: 2338.0000 - accuracy: 0.9170 - precision: 0.9442 - recall: 0.8849 - auc: 0.9737 - prc: 0.9776 - val_loss: 0.1352 - val_tp: 84.0000 - val_fp: 985.0000 - val_tn: 44495.0000 - val_fn: 5.0000 - val_accuracy: 0.9783 - val_precision: 0.0786 - val_recall: 0.9438 - val_auc: 0.9910 - val_prc: 0.8424
Epoch 22: early stopping

Re-check training history

plot_metrics(resampled_history)

png

Evaluate metrics

train_predictions_resampled = resampled_model.predict(train_features, batch_size=BATCH_SIZE)
test_predictions_resampled = resampled_model.predict(test_features, batch_size=BATCH_SIZE)
90/90 [==============================] - 0s 1ms/step
28/28 [==============================] - 0s 1ms/step
resampled_results = resampled_model.evaluate(test_features, test_labels,
                                             batch_size=BATCH_SIZE, verbose=0)
for name, value in zip(resampled_model.metrics_names, resampled_results):
  print(name, ': ', value)
print()

plot_cm(test_labels, test_predictions_resampled)
loss :  0.21747452020645142
tp :  88.0
fp :  1755.0
tn :  55110.0
fn :  9.0
accuracy :  0.9690319895744324
precision :  0.04774823784828186
recall :  0.907216489315033
auc :  0.9658931493759155
prc :  0.7448691129684448

Legitimate Transactions Detected (True Negatives):  55110
Legitimate Transactions Incorrectly Detected (False Positives):  1755
Fraudulent Transactions Missed (False Negatives):  9
Fraudulent Transactions Detected (True Positives):  88
Total Fraudulent Transactions:  97

png

Plot the ROC

plot_roc("Train Baseline", train_labels, train_predictions_baseline, color=colors[0])
plot_roc("Test Baseline", test_labels, test_predictions_baseline, color=colors[0], linestyle='--')

plot_roc("Train Weighted", train_labels, train_predictions_weighted, color=colors[1])
plot_roc("Test Weighted", test_labels, test_predictions_weighted, color=colors[1], linestyle='--')

plot_roc("Train Resampled", train_labels, train_predictions_resampled, color=colors[2])
plot_roc("Test Resampled", test_labels, test_predictions_resampled, color=colors[2], linestyle='--')
plt.legend(loc='lower right');

png

Plot the AUPRC

plot_prc("Train Baseline", train_labels, train_predictions_baseline, color=colors[0])
plot_prc("Test Baseline", test_labels, test_predictions_baseline, color=colors[0], linestyle='--')

plot_prc("Train Weighted", train_labels, train_predictions_weighted, color=colors[1])
plot_prc("Test Weighted", test_labels, test_predictions_weighted, color=colors[1], linestyle='--')

plot_prc("Train Resampled", train_labels, train_predictions_resampled, color=colors[2])
plot_prc("Test Resampled", test_labels, test_predictions_resampled, color=colors[2], linestyle='--')
plt.legend(loc='lower right');

png

Applying this tutorial to your problem

Imbalanced data classification is an inherently difficult task since there are so few samples to learn from. You should always start with the data first and do your best to collect as many samples as possible and give substantial thought to what features may be relevant so the model can get the most out of your minority class. At some point your model may struggle to improve and yield the results you want, so it is important to keep in mind the context of your problem and the trade offs between different types of errors.