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.
Providing fraud detection example with SMOTE and XGBoost
The example creates an imbalanced synthetic dataset, applies SMOTE to balance classes, trains an XGBoost classifier, and evaluates performance using the average precision score (area under the precision-recall curve).
Below is a complete Python example demonstrating how to build a fraud detection model on an imbalanced dataset. It uses SMOTE to generate synthetic minority (fraud) samples, trains an XGBoost classifier, and evaluates performance using the area under the Precision-Recall curve (AUPRC) rather than accuracy.
python
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_recall_curve, average_precision_score, auc
from imblearn.over_sampling import SMOTE
from xgboost import XGBClassifier
import matplotlib.pyplot as plt
# 1. Create a synthetic, imbalanced dataset
X, y = make_classification(
n_samples=20000,
n_features=20,
n_informative=5,
n_redundant=2,
n_classes=2,
weights=[0.98, 0.02], # 2% positive (fraud) class
random_state=42
)
# 2. Train-test split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, stratify=y, random_state=42
)
# 3. Apply SMOTE to upsample the minority class in the training set
smote = SMOTE(random_state=42)
X_train_bal, y_train_bal = smote.fit_resample(X_train, y_train)
# 4. Train an XGBoost classifier
model = XGBClassifier(
n_estimators=200,
learning_rate=0.1,
max_depth=5,
subsample=0.8,
colsample_bytree=0.8,
random_state=42,
use_label_encoder=False,
eval_metric='logloss'
)
model.fit(X_train_bal, y_train_bal)
# 5. Evaluate using Precision-Recall metrics
# Predict probabilities for the positive class
y_scores = model.predict_proba(X_test)[:, 1]
precision, recall, thresholds = precision_recall_curve(y_test, y_scores)
ap_score = average_precision_score(y_test, y_scores)
pr_auc = auc(recall, precision) # area under the precision-recall curve
print(f"Average Precision (AP): {ap_score:.4f}")
print(f"Area Under Precision-Recall Curve (AUPRC): {pr_auc:.4f}")
# 6. (Optional) Plot the Precision-Recall curve
plt.figure(figsize=(7, 5))
plt.plot(recall, precision, label=f"PR curve (AUC = {pr_auc:.4f})")
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('Precision-Recall Curve (Fraud Detection)')
plt.legend()
plt.grid(True)
plt.show()
Notes:
We generate a highly imbalanced dataset (2% fraud cases). In practice, you would load your own fraud dataset.
SMOTE oversamples the minority class in the training set to help the model learn from additional synthetic fraud samples.
The model is evaluated with Precision-Recall metrics (both average_precision_score and auc over the PR curve) since accuracy is not well-suited for imbalanced data.