Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Fraud Detection (ตรวจจับการฉ้อโกง) ด้วย Machine Learning ใน Python

ใช้ Decision Tree Classifier ตรวจจับธุรกรรมบัตรเครดิตที่เป็น Fraud จากข้อมูล Credit Card Fraud Detection

ข้อมูล

  • 284,807 transactions, 31 features (V1-V28, Time, Amount, Class)
  • Class: 0=Normal, 1=Fraud
  • Imbalance: Fraud เพียง 0.17% (492/284,315)

ขั้นตอน

  1. โหลดข้อมูล, ตรวจสอบ imbalance
  2. แยก Features (X) และ Label (y)
  3. Train/Test Split (80/20)
  4. Train DecisionTreeClassifier (max_depth=4)
  5. ประเมิน: Accuracy, Precision, Recall, F1-Score

โค้ดสำคัญ

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn import metrics
from sklearn.metrics import precision_score, recall_score, f1_score

df = pd.read_csv('creditcard.csv')
X = df.iloc[:, :-1].values
y = df.iloc[:, -1].values

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

clf = DecisionTreeClassifier(max_depth=4, random_state=42)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)

print(f"Accuracy: {metrics.accuracy_score(y_test, y_pred)*100:.4f}%")
print(f"Precision: {precision_score(y_test, y_pred, pos_label=1):.4f}")
print(f"Recall: {recall_score(y_test, y_pred, pos_label=1):.4f}")
print(f"F1-Score: {f1_score(y_test, y_pred, pos_label=1):.4f}")

ผลลัพธ์ตัวอย่าง

Accuracy: 99.94%
Precision: 0.8101
Recall: 0.7711
F1-Score: 0.7901

หมายเหตุสำคัญ

  • Accuracy สูงแค่ 99.94% เพราะข้อมูล imbalance ระดับมาก
  • Precision/Recall/F1 สำคัญกว่า Accuracy ในกรณีนี้
  • ควรลอง: SMOTE, class_weight, anomaly detection, ensemble methods

สรุป

Fraud detection ต้องเน้น Recall (จับ fraud ให้ได้มากที่สุด) และ F1-score ไม่ใช่ accuracy เพียงอย่างเดียว