Build fraud detection handling imbalanced data with SMOTE to generate synthetic fraud cases. Train an XGBoost classifier and evaluate with area under precision-recall curve, not accuracy.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a comprehensive request about building a fraud detection system with imbalanced data. Let me create a complete example that demonstrates:
Working with imbalanced data
Using SMOTE to generate synthetic minority class samples
Training an XGBoost classifier
Evaluating using area under precision-recall curve (PR-AUC)
Let me structure this well with explanations and best practices:
python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import (
precision_recall_curve, auc, confusion_matrix,
classification_report, roc_auc_score, roc_curve
)
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline as ImbPipeline
import xgboost as xgb
import warnings
warnings.filterwarnings('ignore')
# Set random seed for reproducibility
np.random.seed(42)
# 1. Generate imbalanced fraud dataset
print("=" * 60)
print("1. GENERATING IMBALANCED FRAUD DATASET")
print("=" * 60)
# Create imbalanced dataset (95% normal, 5% fraud)
X, y = make_classification(
n_samples=10000,
n_features=20,
n_informative=15,
n_redundant=5,
weights=[0.95, 0.05], # 95% normal, 5% fraud
random_state=42
)
# Convert to DataFrame for better visualization
feature_names = [f'feature_{i}' for i in range(X.shape[1])]
X_df = pd.DataFrame(X, columns=feature_names)
y_df = pd.Series(y, name='fraud')
print(f"\nDataset shape: {X_df.shape}")
print(f"\nClass distribution (before SMOTE):")
print(y_df.value_counts())
print(f"\nClass imbalance ratio: {y_df.value_counts()[0] / y_df.value_counts()[1]:.2f}:1")
# Visualize class distribution
fig, axes = plt.subplots(1, 2, figsize=(14, 4))
y_df.value_counts().plot(kind='bar', ax=axes[0], color=['green', 'red'])
axes[0].set_title('Class Distribution (Before SMOTE)')
axes[0].set_ylabel('Count')
axes[0].set_xticklabels(['Normal (0)', 'Fraud (1)'], rotation=0)
y_df.value_counts(normalize=True).plot(kind='bar', ax=axes[1], color=['green', 'red'])
axes[1].set_title('Class Distribution Percentage (Before SMOTE)')
axes[1].set_ylabel('Proportion')
axes[1].set_xticklabels(['Normal (0)', 'Fraud (1)'], rotation=0)
plt.tight_layout()
plt.show()
Now I need to examine the target variable and understand the severe class imbalance—with fraud cases representing only 5% of the data. I'll visualize this imbalance both as raw counts and proportions to highlight why standard metrics would be misleading. The dataset has 10,000 samples across 20 features, with 15 being informative for distinguishing fraud patterns.
Next, I'll split the data into training and test sets using stratification to preserve class proportions, then apply SMOTE exclusively to the training set to generate synthetic fraud examples. This approach prevents data leakage while balancing the training distribution. After resampling, I'll compare the original versus balanced distributions to confirm SMOTE successfully created additional minority class samples.
Finally, I'll standardize all features using StandardScaler, fitting on the SMOTE-resampled training data and applying the same transformation to the test set to ensure consistent scaling across both datasets.
Then I'm training an XGBoost classifier with parameters tuned for the imbalanced fraud detection problem, including a scale_pos_weight parameter to account for class imbalance in the model's loss function. pred = xgb_model.predict(X_test_scaled)
y_pred_proba = xgb_model.predict_proba(X_test_scaled)[:, 1]
print(f"\nArea Under Precision-Recall Curve (PR-AUC): {pr_auc:.4f}")
I'm generating predictions on the test set using both hard predictions and probability estimates. The precision-recall curve gives me a better sense of model performance on this imbalanced dataset, with the PR-AUC metric capturing the trade-off between precision and recall across different classification thresholds.
roc_auc = roc_auc_score(y_test, y_pred_proba)
print(f"Area Under ROC Curve (ROC-AUC): {roc_auc:.4f}")
Now I'll find the optimal decision threshold by maximizing the F1 score across all possible thresholds from the precision-recall curve. For each threshold, I compute the F1 score and identify which one performs best.
f1_scores = []
for threshold in thresholds:
y_pred_threshold = (y_pred_proba >= threshold).astype(int)
f1 = f1_score(y_test, y_pred_threshold)
f1_scores.append(f1)
I'll calculate sensitivity, specificity, and precision from the confusion matrix components. Sensitivity measures how well the model catches actual fraud cases, while specificity shows how well it identifies legitimate transactions. Precision indicates the accuracy of positive predictions.
IMBALANCED DATA: Original dataset had only {y_df.value_counts()[1]} fraud cases
out of {len(y_df)} total transactions ({y_df.value_counts()[1]/len(y_df)*100:.2f}%)
SMOTE APPLICATION: Generated synthetic fraud samples to balance training data
Training samples increased from {len(y_train)} to {len(y_train_smote)}
MODEL PERFORMANCE: Using PR-AUC ({pr_auc:.4f}) instead of accuracy for
better evaluation of imbalanced classification
CLASS BALANCE: Model recalls {sensitivity:.2%} of fraud cases while
maintaining {specificity:.2%} specificity on normal transactions
THRESHOLD OPTIMIZATION: Used F1 score to find optimal threshold ({optimal_threshold:.4f})
to balance precision and recall for production deployment
SMOTE IMPROVEMENT: PR-AUC improved by {((pr
_auc - pr_auc_no_smote) / pr_auc_no_smote * 100):.2f}%
with SMOTE compared to baseline model
""")
from sklearn.model_selection import cross_validate, StratifiedKFold
from imblearn.pipeline import Pipeline as ImbPipeline
from sklearn.preprocessing import StandardScaler
I'm building a stratified 5-fold cross-validation pipeline that combines SMOTE with XGBoost to evaluate model stability across different data splits. The pipeline standardizes features, applies SMOTE to handle class imbalance, and trains the classifier while tracking multiple metrics including PR-AUC, ROC-AUC, precision, recall, and F1 score. I then visualize both per-fold performance and aggregate statistics with error bars to assess consistency.
Fraud Detection with SMOTE and XGBoost
I'll build a complete fraud detection pipeline with SMOTE for handling imbalanced data and evaluation using Precision-Recall AUC.