Bài viết này trình bày quy trình phát hiện giao dịch gian lận thẻ tín dụng bằng hai mô hình học máy Random Forest và XGBoost. Các bước chính bao gồm:
1. Đọc và Khám Phá Dữ Liệu
- Dữ liệu được tải từ một URL và kiểm tra tỷ lệ giao dịch gian lận.
2. Tiền Xử Lý Dữ Liệu
- Chuẩn hóa cột
Amount
và chia dữ liệu thành tập huấn luyện và kiểm tra với tỷ lệ 80:20.
3. Huấn Luyện Mô Hình
- Sử dụng Random Forest và XGBoost để dự đoán giao dịch gian lận.
4. Đánh Giá Mô Hình
- Phân tích độ chính xác bằng Confusion Matrix, Classification Report và ROC Curve, giúp so sánh hiệu suất của hai mô hình.
5. Mục Tiêu
- Xác định các giao dịch bất thường, đánh giá độ hiệu quả của từng mô hình, hỗ trợ quyết định tài chính an toàn hơn.
Mô Tả Bộ Dữ Liệu
Bộ dữ liệu chứa thông tin về các giao dịch thẻ tín dụng thu thập từ châu Âu tháng 9 năm 2013.
- Tổng cộng 284.807 giao dịch, trong đó có 492 giao dịch gian lận (~0,17%).
- Bộ dữ liệu mất cân bằng nghiêm trọng, vì số lượng giao dịch hợp lệ chiếm phần lớn.
Các Cột Trong Bộ Dữ Liệu
Cột | Mô Tả |
---|---|
Time | Thời gian giao dịch (tính bằng giây từ giao dịch đầu tiên). |
V1 – V28 | Các đặc trưng đã được giảm chiều bằng PCA (bảo mật thông tin gốc). |
Amount | Số tiền của giao dịch. |
Class | Nhãn mục tiêu: 0 (hợp lệ), 1 (gian lận). |
Đặc Điểm Dữ Liệu
Time
vàAmount
không được biến đổi qua PCA, trong khiV1 - V28
đã được chuyển đổi thành các thành phần chính.- Class (nhãn mục tiêu) giúp phân loại giữa giao dịch hợp lệ (0) và gian lận (1).
- Mất cân bằng dữ liệu: Tỷ lệ giao dịch gian lận chỉ 0,17%, gây thách thức cho mô hình học máy.
Triển Khai Python
Dưới đây là mã nguồn đầy đủ để thực hiện các bước trên:
# Import các thư viện cần thiết
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier
from sklearn.metrics import classification_report, confusion_matrix, roc_auc_score, roc_curve
# Bước 1: Đọc dữ liệu trực tiếp từ URL
df = pd.read_csv('https://storage.googleapis.com/download.tensorflow.org/data/creditcard.csv')
print(df.head())
# Bước 2: Khám phá dữ liệu
print(df.info())
print(df['Class'].value_counts())
# Tỷ lệ giao dịch gian lận
fraud_ratio = df['Class'].value_counts(normalize=True)[1] * 100
print(f"Tỷ lệ giao dịch gian lận: {fraud_ratio:.2f}%")
# Bước 3: Chuẩn hóa dữ liệu
scaler = StandardScaler()
df['Amount'] = scaler.fit_transform(df[['Amount']])
# Bước 4: Chia dữ liệu thành tập huấn luyện và kiểm tra
X = df.drop(['Class'], axis=1)
y = df['Class']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
# Bước 5: Huấn luyện mô hình Random Forest
rf_model = RandomForestClassifier(random_state=42)
rf_model.fit(X_train, y_train)
# Bước 6: Đánh giá mô hình Random Forest
y_pred_rf = rf_model.predict(X_test)
print("\nBáo cáo phân loại - Random Forest:")
print(classification_report(y_test, y_pred_rf))
# Ma trận nhầm lẫn - Random Forest
conf_matrix_rf = confusion_matrix(y_test, y_pred_rf)
plt.figure(figsize=(8, 6))
sns.heatmap(conf_matrix_rf, annot=True, fmt='d', cmap='Blues')
plt.title('Confusion Matrix - Random Forest')
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.show()
# Vẽ đường cong ROC - Random Forest
roc_auc_rf = roc_auc_score(y_test, rf_model.predict_proba(X_test)[:, 1])
print(f"ROC AUC Score - Random Forest: {roc_auc_rf:.2f}")
fpr_rf, tpr_rf, _ = roc_curve(y_test, rf_model.predict_proba(X_test)[:, 1])
plt.figure(figsize=(10, 6))
plt.plot(fpr_rf, tpr_rf, label=f"Random Forest (AUC = {roc_auc_rf:.2f})")
plt.plot([0, 1], [0, 1], 'r--')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve - Random Forest')
plt.legend()
plt.show()
# Bước 7: Huấn luyện mô hình XGBoost
xgb_model = XGBClassifier(use_label_encoder=False, eval_metric='logloss', random_state=42)
xgb_model.fit(X_train, y_train)
# Đánh giá mô hình XGBoost
y_pred_xgb = xgb_model.predict(X_test)
print("\nBáo cáo phân loại - XGBoost:")
print(classification_report(y_test, y_pred_xgb))
# Ma trận nhầm lẫn - XGBoost
conf_matrix_xgb = confusion_matrix(y_test, y_pred_xgb)
plt.figure(figsize=(8, 6))
sns.heatmap(conf_matrix_xgb, annot=True, fmt='d', cmap='Greens')
plt.title('Confusion Matrix - XGBoost')
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.show()
# Vẽ đường cong ROC - XGBoost
roc_auc_xgb = roc_auc_score(y_test, xgb_model.predict_proba(X_test)[:, 1])
print(f"ROC AUC Score - XGBoost: {roc_auc_xgb:.2f}")
fpr_xgb, tpr_xgb, _ = roc_curve(y_test, xgb_model.predict_proba(X_test)[:, 1])
plt.figure(figsize=(10, 6))
plt.plot(fpr_xgb, tpr_xgb, label=f"XGBoost (AUC = {roc_auc_xgb:.2f})")
plt.plot([0, 1], [0, 1], 'r--')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve - XGBoost')
plt.legend()
plt.show()
Kết Luận
- Random Forest và XGBoost đều là các mô hình mạnh mẽ trong phát hiện giao dịch gian lận.
- ROC AUC Score và Confusion Matrix giúp đánh giá độ chính xác của mô hình.
- XGBoost thường hoạt động tốt hơn trong các bài toán phức tạp, nhưng thời gian huấn luyện lâu hơn.
Discover more from Science Comics
Subscribe to get the latest posts sent to your email.