Credit Card Fraud Detection¶

In [ ]:
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV, learning_curve
from sklearn.preprocessing import RobustScaler
from imblearn.over_sampling import SMOTE
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from xgboost import XGBClassifier
from sklearn.metrics import classification_report, roc_auc_score, precision_recall_curve, roc_curve, average_precision_score, confusion_matrix, f1_score, ConfusionMatrixDisplay
import matplotlib.pyplot as plt
import seaborn as sns
import time

Introduction¶

In this project, we aim to identify fraudulent transactions within a highly imbalanced dataset. This notebook details the step-by-step process of building a fraud detection model, starting from data preprocessing and exploratory data analysis (EDA) to model selection, hyperparameter tuning, and performance evaluation. By applying techniques such as log transformation, SMOTE for handling class imbalance, and evaluating multiple machine learning models, we aim to develop a robust model capable of distinguishing fraudulent transactions from legitimate ones.

Data Preprocessing¶

1. Loading Data¶

This data originates from a study done in collaboration by Worldline and a research group from the Université Libre de Bruxelles. This dataset contains real-world transaction data from European card holders over the span of two days. To protect sensitive consumer data, all features except for Time, Amount, and Class, have been transformed using PCA.

In [ ]:
# load data
data = pd.read_csv('../Data/creditcard.csv')
data.head()
Out[ ]:
Time V1 V2 V3 V4 V5 V6 V7 V8 V9 ... V21 V22 V23 V24 V25 V26 V27 V28 Amount Class
0 0.0 -1.359807 -0.072781 2.536347 1.378155 -0.338321 0.462388 0.239599 0.098698 0.363787 ... -0.018307 0.277838 -0.110474 0.066928 0.128539 -0.189115 0.133558 -0.021053 149.62 0
1 0.0 1.191857 0.266151 0.166480 0.448154 0.060018 -0.082361 -0.078803 0.085102 -0.255425 ... -0.225775 -0.638672 0.101288 -0.339846 0.167170 0.125895 -0.008983 0.014724 2.69 0
2 1.0 -1.358354 -1.340163 1.773209 0.379780 -0.503198 1.800499 0.791461 0.247676 -1.514654 ... 0.247998 0.771679 0.909412 -0.689281 -0.327642 -0.139097 -0.055353 -0.059752 378.66 0
3 1.0 -0.966272 -0.185226 1.792993 -0.863291 -0.010309 1.247203 0.237609 0.377436 -1.387024 ... -0.108300 0.005274 -0.190321 -1.175575 0.647376 -0.221929 0.062723 0.061458 123.50 0
4 2.0 -1.158233 0.877737 1.548718 0.403034 -0.407193 0.095921 0.592941 -0.270533 0.817739 ... -0.009431 0.798278 -0.137458 0.141267 -0.206010 0.502292 0.219422 0.215153 69.99 0

5 rows × 31 columns

In [ ]:
# check for null values
data.isnull().sum().max()
Out[ ]:
0

Exploratory Data Analysis¶

Class Imbalance¶

In [ ]:
# Distribution of the target variable 'Class'
plt.figure(figsize=(10, 6))
sns.countplot(x='Class', data=data)
plt.title('Distribution of Target Variable (Class)')
plt.xlabel('Class')
plt.ylabel('Frequency')
plt.show()

data['Class'].value_counts(normalize=True)
Out[ ]:
0    0.998273
1    0.001727
Name: Class, dtype: float64

The graphic above illustrates the severe class imbalance present in the dataset. Non-fraudulent transactions (Class 0) comprise the overwhelming majority or the dataset at over 99.8% of transactions present, fraudulent transactions (Class 1) make up less than 0.2%. This severe imbalance poses a risk of the model becoming biased towards predicting the majority class, resulting in poor detection of fraud. This must be addressed using techniques like SMOTE to rebalance the dataset and evaluating models with the appropriate metrics.

Distributions¶

In [ ]:
# Distribution of the 'Time' feature
plt.figure(figsize=(10, 6))
sns.histplot(data['Time'], bins=50, kde=True)
plt.title('Distribution of Time Feature (All Transactions)')
plt.xlabel('Time')
plt.ylabel('Frequency')
plt.show()

# Create datafame only containing fraud cases
fraud_data = data[data['Class'] == 1]

# Distribution of the 'Time' feature for fraudulent transactions
plt.figure(figsize=(10, 6))
sns.histplot(fraud_data['Time'], bins=50, kde=True, color='red')
plt.title('Distribution of Time Feature (Fruadulent Transactions)')
plt.xlabel('Time')
plt.ylabel('Frequency')
plt.show()

The histograms above show the distribution of the Time feature for all transactions and fraudulent transactions. The Time feature represents the time in seconds elapsed from a specific starting point. For all transactions, the distribution exhibits a bimodal pattern with two prominent peaks, indicating periods of high transaction activity. This suggests that transaction volume varies significantly based on the time of day.

For fraudulent transactions, the distribution is more uniform and less pronounced, lacking the clear peaks observed in the overall transaction distribution. This indicates that fraud can occur at any time, without a strong temporal pattern.

In [ ]:
# Distribution of the 'Amount' feature
plt.figure(figsize=(10, 6))
sns.histplot(data['Amount'], bins=50, kde=True)
plt.title('Distribution of Amount Feature (All Transactions)')
plt.xlabel('Amount')
plt.ylabel('Frequency')
plt.show()

# Apply log transformation to the Amount feature
data['LogAmount'] = np.log1p(data['Amount'])

# Distribution of the 'LogAmount' feature
plt.figure(figsize=(10, 6))
sns.histplot(data['LogAmount'], bins=50, kde=True)
plt.title('Distribution of LogAmount Feature (All Transactions)')
plt.xlabel('LogAmount')
plt.ylabel('Frequency')
plt.show()

# Recopy fraudulent data table so it includes LogAmount
fraud_data = data[data['Class'] == 1]

# Distribution of the 'LogAmount' feature
plt.figure(figsize=(10, 6))
sns.histplot(fraud_data['LogAmount'], bins=50, kde=True, color='red')
plt.title('Distribution of LogAmount Feature for Fraud (Fraudulent Transactions)')
plt.xlabel('LogAmount')
plt.ylabel('Frequency')
plt.show()

The first graphic illustrates the distribution of the Amount feature for all transactions, which is highly right-skewed with most transactions having lower amounts. This skewness can affect the performance of machine learning models by emphasizing extreme values. To address this issue, a log transformation was applied to the Amount feature, resulting in a more normalized distribution as shown in the second graphic. The normalized LogAmount distribution reduces the impact of extreme values and enhances model performance.

The third graphic presents the distribution of the LogAmount feature specifically for fraudulent transactions. It shows that fraudulent transactions are more frequent at lower transaction amounts, with a significant peak around the log-transformed value of 0. Additionally, there are other smaller peaks across the range, indicating that fraud can occur at various transaction amounts, though it is more common at smaller values. These visualizations highlight the necessity of the log transformation and provide valuable insights into the patterns of fraudulent transactions, which are critical for developing an effective fraud detection model.

Pairplot¶

In [ ]:
# Pairplot of a subset of features
subset_features = ['V14', 'V10', 'V4', 'V12', 'LogAmount']
sns.pairplot(data[subset_features + ['Class']], hue='Class', diag_kind='kde')
plt.suptitle('Pairplot of Subset of Features', y=1.02)
plt.show()

This pairplot visualizes the relationships between a subset of features (V14, V10, V4, V12, and LogAmount) and distinguishes between non-fraudulent (blue) and fraudulent (orange) transactions. The scatter plots reveal distinct clusters of fraudulent transactions, suggesting that specific combinations of these features are indicative of fraud. For example, in the V14 vs. V10 and V4 vs. V10 plots, fraudulent transactions cluster separately from non-fraudulent ones, highlighting potential patterns that can be leveraged for fraud detection.

Correlations¶

In [ ]:
# Correlation heatmap
plt.figure(figsize=(12, 10))
correlation_matrix = data.corr()
sns.heatmap(correlation_matrix, annot=False, cmap='coolwarm', linewidths=0.5)
plt.title('Correlation Heatmap')
plt.show()

The correlation heatmap above provides a visual representation of the relationships between different features in the dataset. The color intensity indicates the strength of the correlation, with red representing strong positive correlations and blue representing strong negative correlations. Most features show little to no correlation with each other, as indicated by the light blue color across most of the heatmap. This lack of correlation is expected because many features have been transformed using Principal Component Analysis (PCA), which aims to create uncorrelated features to capture the underlying variance in the data. Notably, the Amount feature shows a stronger correlation with LogAmount, confirming that the log transformation effectively normalizes the data while preserving the relationship with the original Amount values.

The Class feature, representing whether a transaction is fraudulent, does not exhibit strong correlations with most features, underscoring the challenge of distinguishing fraudulent transactions based solely on individual features. This emphasizes the importance of using a combination of features and advanced techniques like machine learning models to accurately identify fraudulent activities.

Preprocessing¶

Training and Testing Split¶

In [ ]:
# Define features and target
X = data.drop(columns=['Class', 'Amount'])
y = data['Class']

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)

Rescaling¶

In [ ]:
# Define the scaler
scaler = RobustScaler()

# Fit the scaler on the training data and transform the training data
X_train_scaled = scaler.fit_transform(X_train)

# Transform the testing data using the scaler fitted on the training data
X_test_scaled = scaler.transform(X_test)

SMOTE¶

In [ ]:
# Apply SMOTE to the training data
smote = SMOTE(random_state=42)
X_train_smote, y_train_smote = smote.fit_resample(X_train_scaled, y_train)

Severe class imbalance can negatively affect the training and evaluation of our models in several ways. The model may become biased towards the majority class and perform poorly in predicting the minority class. Accuracy metrics can be misleading; for instance, a model that simply predicts the majority class 100% of the time would still achieve over 99.8% accuracy due to the imbalance. Additionally, the model may fail to properly learn the characteristics that define the minority class, resulting in poor detection of fraudulent transactions.

These issues can be addressed by using SMOTE (Synthetic Minority Over-sampling Technique). SMOTE balances the dataset by generating synthetic samples for the minority class by interpolating between existing minority class samples. This process enhances the model's ability to learn the characteristics of both classes, leading to improved detection performance and overall model robustness.

Baseline Models¶

Logistic Regression, Random Forest, Gradient Boosting, and XGBoost were chosen as baseline models for their proven effectiveness in classification tasks. Logistic Regression is a straightforward linear model that provides a strong baseline. Random Forest, an ensemble method, enhances accuracy and robustness by combining multiple decision trees. Gradient Boosting builds trees sequentially to correct errors from previous trees, improving performance. Lastly, XGBoost is a highly efficient implementation of gradient boosting renowned for its speed and accuracy.

In [ ]:
# Function to compute metrics and return results
def compute_metrics(model, X_test, y_test):
    y_pred = model.predict(X_test)
    y_prob = model.predict_proba(X_test)[:, 1]  # Probabilities for the positive class
    
    precision, recall, _ = precision_recall_curve(y_test, y_prob)
    fpr, tpr, _ = roc_curve(y_test, y_prob)
    avg_precision = average_precision_score(y_test, y_prob)
    roc_auc = roc_auc_score(y_test, y_prob)
    f1 = f1_score(y_test, y_pred)
    prc_auc = average_precision_score(y_test, y_prob)
    report = classification_report(y_test, y_pred, output_dict=True)
    
    return {
        'precision': precision,
        'recall': recall,
        'fpr': fpr,
        'tpr': tpr,
        'avg_precision': avg_precision,
        'roc_auc': roc_auc,
        'prc_auc': prc_auc,
        'f1_score': f1,
        'classification_report': report
    }
In [ ]:
# Initialize models
log_reg = LogisticRegression(random_state=42, solver='liblinear')
random_forest = RandomForestClassifier(random_state=42)
gradient_boosting = GradientBoostingClassifier(random_state=42)
xgb = XGBClassifier(use_label_encoder=False, eval_metric='logloss', random_state=42)

# List of models
models = [
    ("Logistic Regression", log_reg),
    ("Random Forest", random_forest),
    ("Gradient Boosting", gradient_boosting),
    ("XGBoost", xgb)
]
In [ ]:
# Dictionary to store model performance metrics
baseline_model_metrics = {}

# Train and evaluate models with best hyperparameters
for name, model in models:
    start_time = time.time()
    model.fit(X_train_smote, y_train_smote)
    training_time = time.time() - start_time
    metrics = compute_metrics(model, X_test_scaled, y_test)
    
    baseline_model_metrics[name] = {
        'training_time': training_time,
        'roc_auc': metrics['roc_auc'],
        'average_precision': metrics['avg_precision'],
        'prc_auc': metrics['prc_auc'],
        'classification_report': metrics['classification_report'],
        'precision_curve': metrics['precision'],
        'recall_curve': metrics['recall'],
        'fpr_curve': metrics['fpr'],
        'tpr_curve': metrics['tpr']
    }

Precision-Recall Curves¶

In [ ]:
# Plot Precision-Recall Curves
plt.figure(figsize=(10, 7))
for name, metrics in baseline_model_metrics.items():
    plt.plot(metrics['recall_curve'], metrics['precision_curve'], label=f'{name} (AP = {metrics["average_precision"]:.2f})')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('Precision-Recall Curves')
plt.legend()
plt.grid(True)
plt.show()

The Precision-Recall curves show that XGBoost and Random Forest significantly outperform the other models, with XGBoost achieving the highest average precision (AP = 0.88) and Random Forest following closely (AP = 0.87). These models demonstrate the best balance between precision and recall, making them good contenders for the final model.

ROC Curves¶

In [ ]:
# Plot ROC Curves
plt.figure(figsize=(10, 7))
for name, metrics in baseline_model_metrics.items():
    plt.plot(metrics['fpr_curve'], metrics['tpr_curve'], label=f'{name} (AUC = {metrics["roc_auc"]:.2f})')
plt.plot([0, 1], [0, 1], 'k--')  # Diagonal line for random classifier
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curves')
plt.legend()
plt.grid(True)
plt.show()

While the ROC curve shows that all models, including Logistic Regression and Gradient Boosting, perform well in terms of distinguishing between fraudulent and non-fraudulent transactions, it can be misleading for imbalanced datasets like ours. In fraud detection, where legitimate transactions vastly outnumber fraudulent ones, the ROC curve's high AUC scores do not accurately reflect the models' effectiveness in identifying fraud. Precision-Recall curves, on the other hand, provide a clearer picture by focusing on the performance related to the minority class (fraudulent transactions).

Overall Metrics¶

In [ ]:
# Convert the dictionary to a DataFrame
metrics_df = pd.DataFrame.from_dict(baseline_model_metrics, orient='index')

# Extract precision, recall, and f1-score from the classification report
metrics_df['precision'] = metrics_df['classification_report'].apply(lambda x: x['1']['precision'])
metrics_df['recall'] = metrics_df['classification_report'].apply(lambda x: x['1']['recall'])
metrics_df['f1-score'] = metrics_df['classification_report'].apply(lambda x: x['1']['f1-score'])
metrics_df['average_precision'] = metrics_df['average_precision']
metrics_df['roc_auc'] = metrics_df['roc_auc']
metrics_df['prc_auc'] = metrics_df['prc_auc']

# Drop unnecessary columns
metrics_df = metrics_df.drop(columns=['classification_report', 'precision_curve', 'recall_curve', 'fpr_curve', 'tpr_curve'])

# Print the updated metrics DataFrame
metrics_df
Out[ ]:
training_time roc_auc average_precision prc_auc precision recall f1-score
Logistic Regression 3.151254 0.969693 0.723478 0.723478 0.058670 0.918367 0.110294
Random Forest 282.802420 0.981322 0.874102 0.874102 0.872340 0.836735 0.854167
Gradient Boosting 518.077961 0.982658 0.746354 0.746354 0.102299 0.908163 0.183884
XGBoost 4.571411 0.983994 0.875445 0.875445 0.688000 0.877551 0.771300

Random Forest and XGBoost exhibit the best overall performance with high ROC AUC scores (0.9813 and 0.9840 respectively) and strong f1 scores (0.8542 and 0.7713 respectively). While Gradient Boosting also shows a high ROC AUC score, its precision and f1 score are significantly lower. Logistic Regression has the lowest precision and f1 score, despite also having a high ROC AUC score.

Based on these results, it is apparent that in this highly imbalanced dataset, ROC AUC scores can be very misleading. Precision-Recall AUC is an alternative metric that focuses on the performance of a model related to the positive class. This provides a much clearer understanding of the model's ability to minimize false positives and false negatives. Optimizing for Precision-Recall AUC will ensure our final model can effectively distiguish between classes and detect fraudulent transactions.

Hyperparameter Tuning¶

In [ ]:
# Define hyperparameter grid for Random Forest
random_forest_params = {
    'n_estimators': [100, 200],
    'max_depth': [10, 15, 20],
    'min_samples_split': [4, 6, 8]
}

# Define hyperparameter grid for XGBoost
xgb_params = {
    'n_estimators': [100, 200],
    'learning_rate': [0.1, 0.3, 0.5],
    'max_depth': [9, 12, 15]
}
In [ ]:
# Perform GridSearchCV with PRC AUC scoring for Random Forest
random_forest_grid = GridSearchCV(RandomForestClassifier(random_state=42), random_forest_params, cv=3, scoring='average_precision')
random_forest_grid.fit(X_train_smote, y_train_smote)

# Perform GridSearchCV with PRC AUC scoring for XGBoost
xgb_grid = GridSearchCV(XGBClassifier(random_state=42, use_label_encoder=False, eval_metric='logloss'), xgb_params, cv=3, scoring='average_precision')
xgb_grid.fit(X_train_smote, y_train_smote)

# Best parameters and scores
best_params_random_forest = random_forest_grid.best_params_
best_score_random_forest = random_forest_grid.best_score_

best_params_xgb = xgb_grid.best_params_
best_score_xgb = xgb_grid.best_score_

best_params_random_forest, best_score_random_forest, best_params_xgb, best_score_xgb
Out[ ]:
({'max_depth': 20, 'min_samples_split': 6, 'n_estimators': 200},
 0.9999939138950618,
 {'learning_rate': 0.3, 'max_depth': 9, 'n_estimators': 100},
 0.9999863827704459)
In [ ]:
# Define the models with their names and best parameters
tuned_models = [
    ('Random Forest', RandomForestClassifier(random_state=42, **best_params_random_forest)),
    ('XGBoost', XGBClassifier(random_state=42, use_label_encoder=False, eval_metric='logloss', **best_params_xgb))
]

# Dictionary to store model performance metrics
tuned_model_metrics = {}

# Train and evaluate models with best hyperparameters
for name, model in tuned_models:
    start_time = time.time()
    model.fit(X_train_smote, y_train_smote)
    training_time = time.time() - start_time
    metrics = compute_metrics(model, X_test_scaled, y_test)
    
    tuned_model_metrics[name] = {
        'training_time': training_time,
        'roc_auc': metrics['roc_auc'],
        'average_precision': metrics['avg_precision'],
        'prc_auc': metrics['prc_auc'],
        'classification_report': metrics['classification_report'],
        'precision_curve': metrics['precision'],
        'recall_curve': metrics['recall'],
        'fpr_curve': metrics['fpr'],
        'tpr_curve': metrics['tpr']
    }

Precision Recall Curves¶

In [ ]:
# Plot Precision-Recall Curves
plt.figure(figsize=(10, 7))
for name, metrics in tuned_model_metrics.items():
    plt.plot(metrics['recall_curve'], metrics['precision_curve'], label=f'{name} (AP = {metrics["average_precision"]:.2f})')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('Precision-Recall Curves')
plt.legend()
plt.grid(True)
plt.show()

The Precision-Recall curves for the tuned models show that XGBoost outperforms Random Forest with an average precision (AP) score of 0.89 compared to Random Forest's 0.86. Both models maintain high precision across a wide range of recall values, indicating strong performance in identifying fraudulent transactions. However, XGBoost demonstrates a slightly better balance between precision and recall, making it the more effective model for fraud detection in this dataset.

ROC Curves¶

In [ ]:
# Plot ROC Curves
plt.figure(figsize=(10, 7))
for name, metrics in tuned_model_metrics.items():
    plt.plot(metrics['fpr_curve'], metrics['tpr_curve'], label=f'{name} (AUC = {metrics["roc_auc"]:.2f})')
plt.plot([0, 1], [0, 1], 'k--')  # Diagonal line for random classifier
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curves')
plt.legend()
plt.grid(True)
plt.show()

The ROC curves for the tuned models indicate that both Random Forest and XGBoost achieve high AUC scores of 0.97 and 0.98, respectively. This suggests that both models are highly effective at distinguishing between fraudulent and non-fraudulent transactions. However, as previously noted, evaluating models based on ROC AUC alone can be misleading for imbalanced datasets like this one, where the majority class dominates the dataset.

Overall Metrics¶

In [ ]:
# Convert the dictionary to a DataFrame
metrics_df = pd.DataFrame.from_dict(tuned_model_metrics, orient='index')

# Extract precision, recall, and f1-score from the classification report
metrics_df['precision'] = metrics_df['classification_report'].apply(lambda x: x['1']['precision'])
metrics_df['recall'] = metrics_df['classification_report'].apply(lambda x: x['1']['recall'])
metrics_df['f1-score'] = metrics_df['classification_report'].apply(lambda x: x['1']['f1-score'])
metrics_df['average_precision'] = metrics_df['average_precision']
metrics_df['roc_auc'] = metrics_df['roc_auc']
metrics_df['prc_auc'] = metrics_df['prc_auc']

# Drop unnecessary columns
metrics_df = metrics_df.drop(columns=['classification_report', 'precision_curve', 'recall_curve', 'fpr_curve', 'tpr_curve'])

# Display the updated metrics DataFrame
metrics_df
Out[ ]:
training_time roc_auc average_precision prc_auc precision recall f1-score
Random Forest 488.240699 0.973935 0.862659 0.862659 0.734513 0.846939 0.786730
XGBoost 3.719887 0.983889 0.890382 0.890382 0.783784 0.887755 0.832536

XGBoost demonstrates a significantly shorter training time, making it efficient for quick deployment. It also balances precision and recall effectively, ensuring reliable fraud detection with minimal false positives. This balance leads to superior overall performance, making XGBoost a robust and efficient solution for fraud detection.

On the other hand, Random Forest offers strong detection capabilities but has a much longer training time compared to XGBoost. It effectively distinguishes between fraudulent and non-fraudulent transactions but does not perform as efficiently. While Random Forest remains a reliable model, it may be less practical for time-sensitive applications.

Final Model: XGBoost¶

In [ ]:
# Predict the labels for the test set
y_pred_xgb = xgb_best.predict(X_test_scaled)

# Generate the confusion matrix
cm = confusion_matrix(y_test, y_pred_xgb)

# Display the confusion matrix
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=['Non-Fraud', 'Fraud'])
disp.plot(cmap=plt.cm.Blues)
plt.title("Confusion Matrix for XGBoost Model")
plt.show()

The confusion matrix for the XGBoost model shows that it is highly effective in predicting fraudulent and non-fraudulent transactions. We were able to correctly identified 87 out of 98 fraudulent transactions. It also accurately labeled 56,840 out of 56,864 non-fraudulent transactions, with only 24 false positives. This indicates that the model has a high level of accuracy, successfully distinguishing between fraudulent and non-fraudulent transactions while maintaining a low false positive rate and a low false negative rate.

Conclusion¶

The XGBoost model is highly accurate and reliable for detecting fraudulent transactions. This ensures that genuine transactions are processed smoothly while effectively catching most fraud cases. Customers can trust that their legitimate transactions will go through without unnecessary interruptions, while the system actively works to prevent fraud. While the model performs well overall, continuous monitoring and improvement are essential to adapt to new fraud patterns and further enhance security and user experience.

Further tuning and the incorporation of additional features could improve model performance even more. Exploring ensemble methods that combine multiple models could yield even better results.

This project demonstrates a robust approach to building and evaluating a fraud detection model using XGBoost, providing a solid foundation for deploying an effective fraud detection system in a real-world financial environment.