Lý thuyết
4-5 gio
Bài 10/15

ROC-AUC và Gini Coefficient

ROC Curve, AUC, Gini Coefficient - Đánh giá model classification chuyên sâu

ROC-AUC và Gini Coefficient

Mục tiêu bài học

Sau bài học này, học viên sẽ:

  • Hieu ROC Curve va cach ve
  • Nam vung AUC va y nghia
  • Biet cong thuc va cach tinh Gini Coefficient
  • Phần biet Gini Coefficient voi Gini Impurity

1. ROC Curve

1.1 Định nghĩa

ROC (Receiver Operating Characteristic) la đồ thị thể hiện trade-off giữa:

  • TPR (True Positive Rate) = Recall = Sensitivity
  • FPR (False Positive Rate) = 1 - Specificity

1.2 Công thức

TPR=TPTP+FNTPR = \frac{TP}{TP + FN}

FPR=FPFP+TNFPR = \frac{FP}{FP + TN}

1.3 Cách vẽ ROC Curve

BướcMô tả
1Model output probabilities
2Thay đổi threshold tu 0 đến 1
3Tính TPR, FPR cho mỗi threshold
4Plot các điểm (FPR, TPR)
5Nối các điểm thành ROC Curve

ROC Curve

Hinh: ROC Space - Các điểm trong không gian ROC


2. Ví dụ tính toán thủ công ROC

2.1 Dữ liệu

SampleTrue LabelP(Positive)
A10.95
B10.85
C00.70
D10.65
E00.55
F00.40
G10.30
H00.20

Tổng: 4 Positive, 4 Negative

2.2 Tính TPR, FPR cho các thresholds

Threshold = 0.9:

  • Predict Positive: A
  • TP = 1, FP = 0, FN = 3, TN = 4
  • TPR = 1/4 = 0.25, FPR = 0/4 = 0

Threshold = 0.8:

  • Predict Positive: A, B
  • TP = 2, FP = 0, FN = 2, TN = 4
  • TPR = 2/4 = 0.50, FPR = 0/4 = 0

Threshold = 0.6:

  • Predict Positive: A, B, C, D
  • TP = 3, FP = 1, FN = 1, TN = 3
  • TPR = 3/4 = 0.75, FPR = 1/4 = 0.25

Threshold = 0.5:

  • Predict Positive: A, B, C, D, E
  • TP = 3, FP = 2, FN = 1, TN = 2
  • TPR = 3/4 = 0.75, FPR = 2/4 = 0.50

Threshold = 0.35:

  • Predict Positive: A, B, C, D, E, F
  • TP = 3, FP = 3, FN = 1, TN = 1
  • TPR = 3/4 = 0.75, FPR = 3/4 = 0.75

Threshold = 0.25:

  • Predict Positive: A, B, C, D, E, F, G
  • TP = 4, FP = 3, FN = 0, TN = 1
  • TPR = 4/4 = 1.00, FPR = 3/4 = 0.75

2.3 Bảng tổng hợp ROC Points

ThresholdTPRFPR
1.00.000.00
0.90.250.00
0.80.500.00
0.60.750.25
0.50.750.50
0.350.750.75
0.251.000.75
0.01.001.00

3. AUC (Area Under Curve)

3.1 Định nghĩa

AUC = Diện tích duoi duong ROC

3.2 Ý nghĩa

AUC=P(Scorepositive>Scorenegative)AUC = P(\text{Score}_{positive} > \text{Score}_{negative})

"Xác suất model xếp hạng một positive sample cao hơn mot negative sample"

3.3 Giải thích gia tri AUC

AUCÝ nghĩa
1.0Perfect classifier
0.9 - 1.0Excellent
0.8 - 0.9Good
0.7 - 0.8Fair
0.6 - 0.7Poor
0.5Random guess (đường chéo)
< 0.5Worse than random

3.4 Tính AUC bang Trapezoidal Rule

AUC=i=1n1(TPRi+TPRi+1)2\tıˋmes(FPRi+1FPRi)AUC = \sum_{i=1}^{n-1} \frac{(TPR_i + TPR_{i+1})}{2} \tìmes (FPR_{i+1} - FPR_i)


4. Gini Coefficient

4.1 Công thức

Gini=2\tıˋmesAUC1Gini = 2 \tìmes AUC - 1

4.2 Ý nghĩa

AUCGiniÝ nghĩa
1.01.0Perfect
0.90.8Excellent
0.80.6Good
0.70.4Fair
0.50.0Random

4.3 Vi du tinh

Neu AUC = 0.85: Gini=2\tıˋmes0.851=0.70Gini = 2 \tìmes 0.85 - 1 = 0.70

4.4 QUAN TRỌNG: Gini Coefficient vs Gini Impurity

Gini CoefficientGini Impurity
Đúng choĐánh giá modelDecision Tree split
Công thức2\tıˋmesAUC12 \tìmes AUC - 11pi21 - \sum p_i^2
Range0 đến 10 đến 0.5
Càng caoModel càng tốtNode càng không thuần

5. Thực hành với Scikit-learn

5.1 Code vẽ ROC và tính AUC

Python
1import numpy as np
2from sklearn.datasets import make_classification
3from sklearn.model_selection import train_test_split
4from sklearn.linear_model import LogisticRegression
5from sklearn.metrics import roc_curve, auc, roc_auc_score
6import matplotlib.pyplot as plt
7
8# Tạo dữ liệu
9X, y = make_classification(n_samples=1000, n_features=20,
10 n_classes=2, random_state=42)
11X_train, X_test, y_train, y_test = train_test_split(
12 X, y, test_size=0.3, random_state=42
13)
14
15# Train model
16model = LogisticRegression()
17model.fit(X_train, y_train)
18
19# Lấy probabilities
20y_prob = model.predict_proba(X_test)[:, 1]
21
22# Tính ROC curve
23fpr, tpr, thresholds = roc_curve(y_test, y_prob)
24roc_auc = auc(fpr, tpr)
25gini = 2 * roc_auc - 1
26
27print(f"AUC: {roc_auc:.4f}")
28print(f"Gini Coefficient: {gini:.4f}")
29
30# Ve ROC Curve
31plt.figure(figsize=(10, 8))
32plt.plot(fpr, tpr, color='blue', lw=2,
33 label=f'ROC curve (AUC = {roc_auc:.3f})')
34plt.plot([0, 1], [0, 1], color='gray', lw=2,
35 linestyle='--', label='Random (AUC = 0.5)')
36plt.xlim([0.0, 1.0])
37plt.ylim([0.0, 1.05])
38plt.xlabel('False Positive Rate (FPR)')
39plt.ylabel('True Positive Rate (TPR)')
40plt.title('ROC Curve')
41plt.legend(loc='lower right')
42plt.grid(True)
43plt.show()

ROC Curve Example

Hinh: Vi du ROC Curve tu Scikit-learn

5.2 So sanh nhieu models

Python
1from sklearn.ensemble import RandomForestClassifier
2from sklearn.svm import SVC
3
4# Train multiple models
5models = {
6 'Logistic Regression': LogisticRegression(),
7 'Random Forest': RandomForestClassifier(n_estìmators=100),
8 'SVM': SVC(probability=True)
9}
10
11plt.figure(figsize=(10, 8))
12
13for name, model in models.items():
14 model.fit(X_train, y_train)
15 y_prob = model.predict_proba(X_test)[:, 1]
16 fpr, tpr, _ = roc_curve(y_test, y_prob)
17 roc_auc = auc(fpr, tpr)
18 plt.plot(fpr, tpr, lw=2, label=f'{name} (AUC = {roc_auc:.3f})')
19
20plt.plot([0, 1], [0, 1], 'k--', lw=2, label='Random')
21plt.xlabel('False Positive Rate')
22plt.ylabel('True Positive Rate')
23plt.title('ROC Curve Comparison')
24plt.legend(loc='lower right')
25plt.grid(True)
26plt.show()

6. Khi nào dùng ROC-AUC?

Uu điểm

  • Khong phu thuoc vao threshold
  • Tot cho imbalanced data
  • So sanh duoc nhieu models
  • Đánh giá kha nang ranking

Nhuoc điểm

  • Khong cho biet performance o threshold cu the
  • Co the misleading voi highly imbalanced data
  • Khong truc quan nhu Precision/Recall

Khi nào dùng

Tính huongMetric phu hop
So sanh modelsAUC
Imbalanced dataAUC hoac PR-AUC
Can threshold cu theF1, Precision, Recall
Ranking qualityAUC

Bài tập tự luyện

  1. Bai tap 1: Tính AUC bang tay cho 5 samples voi labels va probabilities
  2. Bai tap 2: Ve ROC curve va tinh Gini cho model tren Titanic dataset
  3. Bai tap 3: So sanh AUC cua Logistic Regression vs Random Forest

Tài liệu tham khảo