All Revision Notes

COM6004 Data Mining · Chapter 4B

Classification (II): Overfitting, Model Evaluation & Imbalanced Classes

COM6004 · Chapter 4B · Source: COM6004_Chapter_4B_Classification_(II).pptx (58 slides) · Underfitting & Overfitting, Model Evaluation, Imbalanced Class Problem

Contents · 12 sections

🎯 本講重點 (Learning outcomes)

  • 分辨 training error、test error、generalization error;解釋 underfitting 同 overfitting 同 model complexity / training size 嘅關係。
  • 理解 model selection:validation set、Occam's Razor。
  • 由 confusion matrix 計 Accuracy、Precision、Recall、F-measure、TPR、TNR、FPR、FNR;計 classification cost。
  • 比較 Holdout、Random subsampling、k-fold / Leave-one-out / Repeated / Stratified cross-validation。
  • 由 classifier scores 構建 ROC curve,理解 AUC 同用 ROC 比較 models。
  • 理解 class imbalance 問題同處理方法:class-based ordering、cost-sensitive classification、sampling。

⭐ 考試必溫 Top-5

  1. Confusion matrix (a=TP,b=FN,c=FP,d=TN)(a = TP, b = FN, c = FP, d = TN) 同所有 metrics 公式;slides 46–50 嘅數字例子。
  2. Accuracy 喺 imbalanced data 會誤導(9990 vs 10 例子)。
  3. Cost matrix 計算(M1 accuracy 80% cost 3910 vs M2 accuracy 90% cost 4255)同 cost-sensitive decision(sick / healthy 例子)。
  4. ROC:軸(TPR vs FPR)、特殊點 (0,0)、(1,1)、(0,1) ideal、diagonal = random;構建步驟;AUC=1AUC = 1 ideal、0.5 random。
  5. Underfitting vs Overfitting 定義;validation set ≠ test set;k-fold CV 同 stratified CV。

1. Classification Errors

ExamSlide 4:

Error 類型定義
Training errors(apparent errors)Errors committed on the training set
Test errorsErrors committed on the test set
Generalization errorsExpected error of a model over random selection of records from same distribution(真正關心嘅嘢,只能估計)

1.1 Example Data Set (Slides 5–9)

Two-class problem:

  • +:5400 instances——5000 個由中心 (10, 10) 嘅 Gaussian 產生,另加 400 個 noisy instances。
  • o:5400 instances,由 uniform distribution 產生。
  • 10% 用作 training,90% 用作 testing。

Slides 6–9 比較 nodes 數目唔同嘅 decision trees:4 nodes 嘅 tree boundary 好簡單;50 nodes 嘅 tree 喺 training data 上畫出好多細碎 boundaries(連 noise 都 fit 埋)。Slide 9 問:"Which tree is better?"

🖼️ 圖片內容

Slides 5–9 嘅散點圖、trees 同 decision boundaries,以及 slides 10–12 嘅 error curves 全部係圖片;請對照原 slide。

2. Underfitting & Overfitting

Slide 10:As the model becomes more and more complex, test errors can start increasing even though training error may be decreasing.

⭐ 考試重點:定義
  • Underfitting:when model is too simple, both training and test errors are large.
  • Overfitting:when model is too complex, training error is small but test error is large.
Model complexity(例如 tree nodes 數)Training errorTest error狀態
好低(例如 1–4 nodes)高高Underfitting
適中中低最低Just right
好高(例如 50+ nodes)極低(近 0)上升Overfitting
💡 直覺理解

Overfitting 好似學生死背 past paper 答案(連 typo 都背埋)——past paper(training set)攞滿分,但新題目(test set)就唔識。50-node tree 將 400 個 noisy points 都當成真 pattern 去 fit,所以喺新 data 上反而錯更多。

2.1 Impact of Training Data Size (Slides 11–12)

Using twice the number of data instances:Increasing the size of training data reduces the difference between training and testing errors at a given size of model. 即係同一個 50-node tree,用多一倍 training data 訓練,overfitting 會減輕(因為 noise 被更多真實 data「稀釋」)。

2.2 Notes on Overfitting (Slide 13)

  • Overfitting results in decision trees that are more complex than necessary。
  • Training error does not provide a good estimate of how well the tree will perform on previously unseen records。
  • Need ways for estimating generalization errors。

3. Model Selection

Slide 14:Model selection 喺 model building 期間進行,目的係確保 model 唔會 overly complex(避免 overfitting)。要估計 generalization error,方法有:

  • Using Validation Set
  • Incorporating Model Complexity
  • Estimating Statistical Bounds

3.1 Using Validation Set (Slide 15)

將 training data 再分兩部分:

  • Training set:用嚟 model building。
  • Validation set:用嚟估計 generalization error、tune model complexity 同 hyperparameters、model selection 等。

ExamNote: validation set is not the same as test set. Drawback:Less data available for training。

⚠️ 易混淆:Validation vs Test set

Validation set 參與「揀 model / 調 hyperparameter」(例如揀 tree 深度、KNN 嘅 k),所以佢已經間接影響咗 model;Test set 必須完全唔參與任何 training / 選擇過程,最後先用一次去報告最終表現。用 test set 揀 model 會令報告嘅表現過度樂觀。

from sklearn.model_selection import train_test_split
X_tmp, X_test, y_tmp, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
X_tr, X_val, y_tr, y_val = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0)
# 用 (X_tr, X_val) 揀 max_depth;最後先用 X_test 報告一次

3.2 Incorporating Model Complexity (Slide 16)

Rationale:Occam's Razor——Given two models of similar generalization errors, one should prefer the simpler model over the more complex model. 因為 complex model 有更大機會係 accidentally fitted(碰啱 fit 中 noise)。所以評估 model 時應考慮 model complexity(細節 slide 標明 skipped)。

4. Model Evaluation: 三個問題

Slide 18 Purpose:To estimate performance of classifier on previously unseen data (test set)。

  1. Metrics for Performance Evaluation:How to evaluate the performance of a model?
  2. Methods for Performance Evaluation:How to obtain reliable estimates?
  3. Methods for Model Comparison:How to compare the relative performance among competing models?

5. Metrics: Confusion Matrix & Accuracy

Slide 19:Focus on the predictive capability of a model(而唔係速度、scalability 等)。

⭐ 考試重點:Confusion Matrix (Slides 42–43)
ACTUAL CLASSPREDICTED CLASS
Class = YesClass = No
Class = Yesaa (TP)bb (FN)
Class = Nocc (FP)dd (TN)

aa: TP (true positive)、bb: FN (false negative)、cc: FP (false positive)、dd: TN (true negative)。

Accuracy=a+da+b+c+d=TP+TNTP+TN+FP+FN,Error rate=1−Accuracy\text{Accuracy} = \frac{a + d}{a + b + c + d} = \frac{TP + TN}{TP + TN + FP + FN}, \qquad \text{Error rate} = 1 - \text{Accuracy}
💡 記法

第二個字(Positive / Negative)= model 預測咩;第一個字(True / False)= 預測啱定錯。FP = 預測 Positive 但錯咗(實際係 No);FN = 預測 Negative 但錯咗(實際係 Yes)。

5.1 Limitation of Accuracy (Slides 21, 44)

Exam2-class problem:Class 0 有 9990 個,Class 1 有 10 個。如果 model 將所有嘢預測為 class 0,accuracy=9990/10000=\text{accuracy} = 9990/10000 = 99.9%——但 model 一個 class 1 都偵測唔到,所以 accuracy 係 misleading。偵測 rare class 通常先係重點(frauds、intrusions、defects)。

⚠️ Slide 數字留意

Slide 44 寫 "Class 0 = 9990、Class 1 = 10" 但計算寫 "accuracy is 990/1000 = 99%"——數字前後唔一致(應該係 9990/10000 = 99.9%;或者如果係 990 vs 10 就係 99%)。考試照邏輯計:全部預測多數 class 嘅 accuracy = 多數 class 比例。結論一樣:accuracy 高但完全冇用。

6. Cost Matrix & Cost of Classification

Slides 22, 52:C(i∣j)C(i \mid j):Cost of misclassifying class jj example as class ii(slide 22 記法,即 C(predicted∣actual)C(\text{predicted} \mid \text{actual}))。Slide 52 表格用 C(actual,predicted)C(\text{actual}, \text{predicted}) 排列:行 = ACTUAL,列 = PREDICTED。

ACTUALPREDICTED
YesNo
YesC(Yes,Yes)C(\text{Yes}, \text{Yes})C(Yes,No)C(\text{Yes}, \text{No})
NoC(No,Yes)C(\text{No}, \text{Yes})C(No,No)C(\text{No}, \text{No})

總 cost = ∑\sum(confusion matrix 每格 count × cost matrix 對應格 cost)。

⭐ 考試重點:Slide 53 Computing Cost of Classification

Cost matrix:C(+,+)=−1C(+,+) = -1、C(+,−)=100C(+,-) = 100、C(−,+)=1C(-,+) = 1、C(−,−)=0C(-,-) = 0(漏報一個 + 嘅代價 100,極貴)。

Model M1Pred +Pred −
Actual +15040
Actual −60250

Accuracy=(150+250)/500=\text{Accuracy} = (150 + 250)/500 = 80%;Cost=150(−1)+40(100)+60(1)+250(0)=−150+4000+60=\text{Cost} = 150(-1) + 40(100) + 60(1) + 250(0) = -150 + 4000 + 60 = 3910

Model M2Pred +Pred −
Actual +25045
Actual −5200

Accuracy=(250+200)/500=\text{Accuracy} = (250 + 200)/500 = 90%;Cost=250(−1)+45(100)+5(1)+200(0)=−250+4500+5=\text{Cost} = 250(-1) + 45(100) + 5(1) + 200(0) = -250 + 4500 + 5 = 4255

結論:M2 accuracy 較高,但 cost 較高(因為 FN 多咗,而 FN 好貴)→ 以 cost 計 M1 較好。Accuracy 同 cost 可以得出相反結論。

Slide 24 "Cost vs Accuracy":教科書指出如果 cost matrix 係對稱(C(Yes∣No)=C(No∣Yes)=qC(\text{Yes} \mid \text{No}) = C(\text{No} \mid \text{Yes}) = q,C(Yes∣Yes)=C(No∣No)=pC(\text{Yes} \mid \text{Yes}) = C(\text{No} \mid \text{No}) = p),咁 cost 同 accuracy 成線性關係,兩者排名一致;只有 cost 唔對稱時兩者先會分歧。

🖼️ 圖片內容

Slides 22–24 係圖片(cost matrix、computing cost、cost vs accuracy 推導);slide 24 嘅內容係根據教科書補充,請對照原 slide。Slide 53 嘅表格有文字,已完整收錄。

7. Precision, Recall, F-measure & 其他 Measures

⭐ 考試重點:Alternative Measures (Slides 25, 45, 48)
Precision (p)=aa+c=TPTP+FPRecall (r)=aa+b=TPTP+FN\text{Precision } (p) = \frac{a}{a + c} = \frac{TP}{TP+FP} \qquad \text{Recall } (r) = \frac{a}{a + b} = \frac{TP}{TP+FN}
F-measure (F)=2rpr+p=2a2a+b+c\text{F-measure } (F) = \frac{2rp}{r + p} = \frac{2a}{2a + b + c}
Measure公式意思
TPR(Sensitivity, Recall)TP/(TP+FN)TP / (TP + FN)真正 Yes 之中搵到幾多
TNR(Specificity)TN/(TN+FP)TN / (TN + FP)真正 No 之中正確判 No 幾多
FPR=1−TNRFPR = 1 - TNRFP/(FP+TN)FP / (FP + TN)假警報率(= α\alpha,Type I error)
FNR=1−TPRFNR = 1 - TPRFN/(FN+TP)FN / (FN + TP)漏報率(= β\beta,Type II error)
PrecisionTP/(TP+FP)TP / (TP + FP)預測 Yes 之中真係 Yes 幾多

Slide 25 Cost-Sensitive Measures:

  • Precision is biased towards C(Yes∣Yes)C(\text{Yes} \mid \text{Yes}) & C(Yes∣No)C(\text{Yes} \mid \text{No})(只涉及「預測 Yes」嗰一列:TP 同 FP)
  • Recall is biased towards C(Yes∣Yes)C(\text{Yes} \mid \text{Yes}) & C(No∣Yes)C(\text{No} \mid \text{Yes})(只涉及「實際 Yes」嗰一行:TP 同 FN)
  • F-measure is biased towards all except C(No∣No)C(\text{No} \mid \text{No})(用 TP、FP、FN,唔理 TN)

教科書亦有 Weighted Accuracy=w1a+w4dw1a+w2b+w3c+w4d\text{Weighted Accuracy} = \frac{w_1 a + w_4 d}{w_1 a + w_2 b + w_3 c + w_4 d}。

7.1 Worked examples (Slides 46, 47, 49, 50)

Slide 46(imbalanced:10 Yes vs 990 No):

Confusion matrix (a, b, c, d)AccuracyPrecisionRecallF
A:TP 10, FN 0, FP 10, TN 980990/1000 = 0.9910/20 = 0.510/10 = 12(0.5)(1)/1.5 = 0.667
B:TP 1, FN 9, FP 0, TN 990991/1000 = 0.9911/1 = 11/10 = 0.12(1)(0.1)/1.1 = 0.182

兩個 model accuracy 差唔多(0.99 vs 0.991),但 A 搵晒所有 Yes,B 只搵到 1 個。F-measure 清楚顯示 A 較好。

Slides 47 / 49(同樣 TPR,唔同 class 比例):

Confusion matrixAccuracyPrecisionRecall = TPRFPRF
C:TP 40, FN 10, FP 10, TN 400.80.80.810/50 = 0.20.8
D:TP 40, FN 10, FP 1000, TN 40004040/5050 = 0.840/1040 = 0.0380.81000/5000 = 0.20.073

重點:TPR 同 FPR 唔受 class 比例影響(C、D 都係 0.8 / 0.2),但 Precision 對 class imbalance 好敏感(Negative 多 100 倍,FP 都多 100 倍,precision 由 0.8 跌到 0.038)。

Slide 50(三個 models,各 50 Yes、50 No):

Confusion matrixTPRFPRPrecisionAccuracy
TP 10, FN 40, FP 10, TN 400.20.20.50.5
TP 25, FN 25, FP 25, TN 250.50.50.50.5
TP 40, FN 10, FP 40, TN 100.80.80.50.5

三個 model 都係 TPR=FPRTPR = FPR,即喺 ROC 嘅 diagonal 上 → 同 random guessing 冇分別(只係「估 Yes」嘅比例唔同)。

from sklearn.metrics import confusion_matrix, classification_report, precision_score, recall_score, f1_score
confusion_matrix(y_true, y_pred, labels=[1, 0])   # 排成 [[TP, FN], [FP, TN]]
print(classification_report(y_true, y_pred))

8. Methods for Performance Evaluation

Slide 27:Performance of a model may depend on other factors besides the learning algorithm:Class distribution、Cost of misclassification、Size of training and test sets(slide 圖 learning curve:training size 越大 accuracy 越高同越穩定)。

⭐ 考試重點:Evaluation methods (Slides 28–30)
Method做法優 / 缺
HoldoutReserve 2/3 for training and 1/3 for testing簡單;但用少咗 data train,結果視乎點分
Random subsamplingRepeated holdout,取平均減少隨機性;但某啲 records 可能從未被 test
Cross validation (k-fold)Partition data into kk disjoint subsets;train on k−1k - 1 partitions,test on the remaining one;重複 kk 次,每個 subset 做一次 test每個 record 都剛好被 test 一次;用晒 data
Leave-one-outk=nk = n最大化 training data;計算量最大
Repeated cross-validation做幾次 cross-validationGives an estimate of the variance of the generalization error
Stratified cross-validationGuarantee the same percentage of class labels in training and testImportant when classes are imbalanced and the sample is small
💡 3-fold CV 例子 (Slide 29)

Data 分 3 份 D1D_1、D2D_2、D3D_3:Run 1 train D2+D3D_2 + D_3、test D1D_1;Run 2 train D1+D3D_1 + D_3、test D2D_2;Run 3 train D1+D2D_1 + D_2、test D3D_3。最終 error = 三次 test errors 嘅平均(或者將三次 confusion matrices 加埋再計)。例如三次 errors 係 0.10、0.15、0.11 → CV error = 0.12。

🖼️ 圖片內容

Slide 27 嘅 learning curve 同 slide 29 嘅 3-fold CV 示意圖係圖片,請對照原 slide。

from sklearn.model_selection import cross_val_score, StratifiedKFold, LeaveOneOut, RepeatedStratifiedKFold
cross_val_score(clf, X, y, cv=StratifiedKFold(n_splits=10, shuffle=True, random_state=0))
cross_val_score(clf, X, y, cv=LeaveOneOut())
cross_val_score(clf, X, y, cv=RepeatedStratifiedKFold(n_splits=5, n_repeats=10))  # 可睇 variance

9. ROC Curve (Methods for Model Comparison)

Slide 32:ROC (Receiver Operating Characteristic):

  • 1950s 為 signal detection theory 分析 noisy signals 而發展。
  • 一個圖像化方法,顯示 detection rate 同 false alarm rate 之間嘅 trade-off。
  • ExamROC curve plots True positive rate TPR (on the yy-axis) against False positive rate FPR (on the xx-axis)。
  • 一個 model 嘅 performance 係 ROC 上嘅一個點;改變 classifier 嘅 threshold 會改變點嘅位置。
⭐ 考試重點:ROC 特殊點 (Slide 33),坐標寫法 (TPR, FPR)
(TPR, FPR)意思
(0, 0)Declare everything to be negative class
(1, 1)Declare everything to be positive class
(1, 0)Ideal(TPR=1TPR = 1、FPR=0FPR = 0;圖上係左上角)
Diagonal lineRandom guessing
Below diagonal linePrediction is opposite of the true class(將預測反轉就會變好)
⚠️ 易混淆

Slide 33 用 (TPR, FPR) 次序寫坐標,所以 ideal 係 (1, 0);但圖上 xx 軸係 FPR、yy 軸係 TPR,即圖上坐標 (FPR,TPR)=(0,1)(FPR, TPR) = (0, 1) 左上角。考試寫清楚你用邊個次序。

9.1 Continuous-valued outputs (Slides 34–36)

要畫 ROC curve,classifier 必須產生 continuous-valued output(score),用嚟將 test records 由「最可能係 positive」排到「最唔可能」。好多 classifiers 只產生 discrete output(predicted class),但可以攞到 continuous outputs:Decision trees(leaf 入面 positive 比例)、rule-based classifiers、neural networks、Bayesian classifiers(posterior probability)、k-nearest neighbors(neighbors 中 positive 比例)、SVM(距離 hyperplane w⋅x+b\mathbf{w}\cdot\mathbf{x}+b)。

Slide 35:Decision tree 嘅 continuous-valued outputs(每個 leaf 嘅 class 比例)。Slide 36:一維 data 有兩個 classes,x>tx > t 就分類為 positive;喺某個 threshold tt:TPR=0.5TPR = 0.5、FNR=0.5FNR = 0.5、FPR=0.12FPR = 0.12、TNR=0.88TNR = 0.88。tt 向左移 → TPR 同 FPR 一齊上升。

🖼️ 圖片內容

Slides 33、35–37、39 嘅 ROC 圖、decision tree 圖同 slide 39 嘅 score 表係圖片;以下 worked example 為自擬數字。

9.2 How to Construct an ROC Curve (Slides 38–39)

⭐ 考試重點:構建步驟
  1. Use a classifier that produces a continuous-valued score for each instance(越可能係 + class,score 越高)。
  2. Sort the instances in decreasing order according to the score。
  3. Apply a threshold at each unique value of the score(score≥threshold\text{score} \ge \text{threshold} → 預測 +)。
  4. Count the number of TP, FP, TN, FN at each threshold。
  5. TPR=TP/(TP+FN)TPR = TP/(TP + FN);FPR=FP/(FP+TN)FPR = FP/(FP + TN);將每對 (FPR,TPR)(FPR, TPR) 畫出並連線。

Worked example(自擬):10 個 instances(5 個 +、5 個 −):

ScoreClassThreshold ≥\geTPFPFNTNTPRFPR
0.95+0.9510450.20
0.90+0.9020350.40
0.85−0.8521340.40.2
0.80+0.8031240.60.2
0.70−0.7032230.60.4
0.60+0.6042130.80.4
0.50−0.5043120.80.6
0.40−0.4044110.80.8
0.30+0.3054011.00.8
0.20−0.2055001.01.0

加上起點 (FPR,TPR)=(0,0)(FPR, TPR) = (0, 0)(threshold>0.95\text{threshold} > 0.95,全部預測 −)。連線:(0,0)→(0,0.2)→(0,0.4)→(0.2,0.4)→(0.2,0.6)→(0.4,0.6)→(0.4,0.8)→(0.6,0.8)→(0.8,0.8)→(0.8,1)→(1,1)。

AUC(梯形 / 長方形面積):FPR 0–0.2 段 TPR=0.4TPR = 0.4 → 0.08;0.2–0.4 段 TPR=0.6TPR = 0.6 → 0.12;0.4–0.6 段 0.8 → 0.16;0.6–0.8 段 0.8 → 0.16;0.8–1 段 1.0 → 0.2。總和 = 0.72。

💡 快速畫法

由 (0,0) 開始,按 score 由高到低逐個睇:遇到 + 就向上行 1/P1/P(PP = positive 總數),遇到 − 就向右行 1/N1/N。Score 有 ties 時就斜行。AUC 亦等於「隨機揀一個 + 同一個 −,+ 嘅 score 高過 − 嘅概率」:呢度 25 對之中有 18 對 + 較高 → 18/25 = 0.72。

9.3 Using ROC for Model Comparison (Slide 37)

  • No model consistently outperform the other(兩條 ROC 交叉時):M1 is better for small FPR,M2 is better for large FPR。揀邊個視乎應用可接受幾多 false alarms。
  • Area Under the ROC curve (AUC):Ideal: Area = 1;Random guess: Area = 0.5。
from sklearn.metrics import roc_curve, roc_auc_score
y = [1,1,0,1,0,1,0,0,1,0]; s = [.95,.90,.85,.80,.70,.60,.50,.40,.30,.20]
fpr, tpr, thr = roc_curve(y, s)
roc_auc_score(y, s)   # 0.72

10. Class Imbalance Problem

Slide 41:好多 classification problems 嘅 classes 係 skewed(一個 class 嘅 records 遠多過另一個):

  • Credit card fraud
  • Intrusion detection
  • Defective products in manufacturing assembly line

Evaluation measures such as accuracy is not well-suited for imbalanced class. 偵測 rare class 就好似 "finding needle in a haystack"。Slides 42–50 嘅 confusion matrix 同 alternative measures 已喺上面 §5、§7 詳述。

10.1 Handling Class Imbalanced Problem (Slide 51)

⭐ 考試重點:三大方法
  1. Class-based ordering:Rules for rare class have higher priority(rule-based classifier 先檢查 rare class 嘅 rules)。
  2. Cost-sensitive classification:Misclassifying rare class as majority class is more expensive than misclassifying majority as rare class。
  3. Sampling-based approaches(slide 57):Modify the distribution of training data so that rare class is well-represented:Under-sample the majority class、Over-sample the rare class。

10.2 Cost-Sensitive Classification (Slides 54–56)

Example:Bayesian classifier。給定 test record xx:計每個 class ii 嘅 p(i∣x)p(i \mid x);decision rule:classify as class kk if k=arg⁡max⁡ip(i∣x)k = \arg\max_i p(i \mid x)。2-class 時:classify xx as + if p(+∣x)>p(−∣x)p(+|x) \gt p(-|x)。

呢條 rule implicitly assumes C(+∣+)=C(−∣−)=0C(+|+) = C(-|-) = 0 and C(+∣−)=C(−∣+)C(+|-) = C(-|+)(即正確冇 cost、兩種錯誤 cost 一樣)。

General decision rule:classify test record xx as class kk if k=arg⁡min⁡j∑ip(i∣x) C(i,j)k = \arg\min_j \sum_i p(i \mid x)\, C(i, j)(揀 expected cost 最低嘅 class)。2-class:

Cost(+)=p(+∣x) C(+,+)+p(−∣x) C(−,+)\text{Cost}(+) = p(+|x)\,C(+,+) + p(-|x)\,C(-,+)
Cost(−)=p(+∣x) C(+,−)+p(−∣x) C(−,−)\text{Cost}(-) = p(+|x)\,C(+,-) + p(-|x)\,C(-,-)

Decision rule:classify xx as + if Cost(+)<Cost(−)\text{Cost}(+) < \text{Cost}(-)。如果 C(+,+)=C(−,−)=0C(+,+) = C(-,-) = 0:

classify as + if   p(+∣x)>C(−,+)C(−,+)+C(+,−)\text{classify as + if } \; p(+|x) \gt \frac{C(-,+)}{C(-,+) + C(+,-)}

(C(i,j)C(i, j) = 實際 class ii 被預測為 jj 嘅 cost。)

🖼️ 圖片內容

Slides 54–55 嘅 argmax / argmin 公式同最後 threshold 公式係圖片;上面係按 slide 文字 Cost(+)\text{Cost}(+)、Cost(−)\text{Cost}(-) 推導出嘅標準結果,請對照原 slide。

⭐ 考試重點:Slide 56 Sick / Healthy 例子

Given:p(sick∣x)=0.3p(\text{sick} \mid x) = 0.3,p(healthy∣x)=0.7p(\text{healthy} \mid x) = 0.7;C(predict healthy∣actually sick)=100,000C(\text{predict healthy} \mid \text{actually sick}) = 100{,}000(missed diagnosis);C(predict sick∣actually healthy)=1,000C(\text{predict sick} \mid \text{actually healthy}) = 1{,}000(false alarm)。

Standard Bayes decision:0.3 < 0.7 ⟹ Predict "healthy"。

Cost-sensitive decision:

  • Expected cost of predicting sick =p(healthy∣x)×1,000=0.7×1,000== p(\text{healthy} \mid x) \times 1{,}000 = 0.7 \times 1{,}000 = 700
  • Expected cost of predicting healthy =p(sick∣x)×100,000=0.3×100,000== p(\text{sick} \mid x) \times 100{,}000 = 0.3 \times 100{,}000 = 30,000

700 < 30,000 ⟹ Predict "sick" ✓

用 threshold 公式:predict sick if p(sick∣x)>1,000/(1,000+100,000)=p(\text{sick} \mid x) > 1{,}000/(1{,}000 + 100{,}000) = 0.0099。0.3 > 0.0099 → sick。

10.3 Sampling-based Approaches (Slide 57)

方法做法風險
Under-sample the majority class隨機抽走部分 majority records,令兩類數目接近丟失有用資訊
Over-sample the rare class重複(或合成,例如 SMOTE)rare class records重複 records 可能導致 overfitting
⚠️ 常見錯誤

Sampling 只可以做喺 training set;test set 要保持原本 distribution,否則評估結果唔反映現實。亦要先 split 再 over-sample,避免同一 record 嘅 copy 同時出現喺 train 同 test。

from sklearn.utils import resample
minority = train[train.y == 1]; majority = train[train.y == 0]
up = resample(minority, replace=True, n_samples=len(majority), random_state=0)    # over-sample
down = resample(majority, replace=False, n_samples=len(minority), random_state=0) # under-sample
# 或 cost-sensitive:DecisionTreeClassifier(class_weight={0: 1, 1: 100})

自我測驗 Self-test

Q1. 一個 model training error 2%、test error 25%;另一個 training error 20%、test error 22%。各屬咩情況?

第一個:training error 細但 test error 大 → Overfitting(model 太複雜)。第二個:兩者都大 → 傾向 Underfitting(model 太簡單)。可以用 validation set 揀中間複雜度、增加 training data,或 pruning。

Q2. Confusion matrix:TP=30,FN=20,FP=10,TN=940TP = 30, FN = 20, FP = 10, TN = 940。計 Accuracy、Precision、Recall、F、FPR、Specificity。

Total=1000\text{Total} = 1000。Accuracy=970/1000=\text{Accuracy} = 970/1000 = 0.97;Precision=30/40=\text{Precision} = 30/40 = 0.75;Recall=30/50=\text{Recall} = 30/50 = 0.6;F=2(0.75)(0.6)/1.35=F = 2(0.75)(0.6)/1.35 = 0.667(或 2a/(2a+b+c)=60/902a/(2a+b+c) = 60/90);FPR=10/950=FPR = 10/950 = 0.0105;Specificity=940/950=\text{Specificity} = 940/950 = 0.989。

Q3. Cost matrix C(+,+)=0,C(+,−)=50,C(−,+)=5,C(−,−)=0C(+,+)=0, C(+,-)=50, C(-,+)=5, C(-,-)=0。Model A:TP 80, FN 20, FP 100, TN 800;Model B:TP 95, FN 5, FP 300, TN 600。邊個 accuracy 高?邊個 cost 低?

A:accuracy=880/1000=0.88\text{accuracy} = 880/1000 = 0.88;cost=20×50+100×5=1000+500=\text{cost} = 20 \times 50 + 100 \times 5 = 1000 + 500 = 1500。
B:accuracy=695/1000=0.695\text{accuracy} = 695/1000 = 0.695;cost=5×50+300×5=250+1500=\text{cost} = 5 \times 50 + 300 \times 5 = 250 + 1500 = 1750。
A accuracy 較高而 cost 亦較低 → A 較好。(如果 C(+,−)C(+,-) 改做 100:A=2500A = 2500,B=2000B = 2000,就會變成 B 較平。)

Q4. 解釋 holdout、k-fold CV、leave-one-out 同 stratified CV。數據得 200 records 而 positive 只有 10 個,應用邊個?

Holdout:2/3 train、1/3 test。k-fold:分 kk 份,輪流用 1 份 test、k−1k - 1 份 train。LOOCV:k=nk = n。Stratified:確保每份 class 比例相同。細樣本 + imbalanced → 用 stratified (repeated) k-fold CV,否則某啲 folds 可能冇 positive。

Q5. ROC 上 (FPR,TPR)=(0,0)(FPR, TPR) = (0, 0)、(1, 1)、(0, 1) 同對角線各代表咩?AUC=0.5AUC = 0.5 代表咩?

(0,0):全部預測 negative;(1,1):全部預測 positive;(0,1):ideal(slide 用 (TPR, FPR) 寫成 (1,0));對角線:random guessing。AUC=0.5AUC = 0.5 = random guess;AUC=1AUC = 1 = ideal。

Q6. Scores 同 labels:0.9(+), 0.8(−), 0.7(+), 0.6(+), 0.4(−), 0.3(−)。畫 ROC 嘅點並計 AUC。

P=3,N=3P = 3, N = 3。Threshold ≥0.9\ge 0.9:TP1 FP0 → (0, 0.333);≥0.8\ge 0.8:(0.333, 0.333);≥0.7\ge 0.7:(0.333, 0.667);≥0.6\ge 0.6:(0.333, 1);≥0.4\ge 0.4:(0.667, 1);≥0.3\ge 0.3:(1, 1)。加 (0,0)。AUC=0.333×0.333+0.667×1=0.111+0.667=AUC = 0.333 \times 0.333 + 0.667 \times 1 = 0.111 + 0.667 = 0.778(= 9 對中 7 對 + 較高 = 7/9)。

Q7. p(fraud∣x)=0.05p(\text{fraud} \mid x) = 0.05。漏報 fraud 嘅 cost = 2000,誤報 cost = 50,正確冇 cost。應該預測咩?

Cost(predict fraud)=p(normal∣x)×50=0.95×50=47.5\text{Cost}(\text{predict fraud}) = p(\text{normal} \mid x) \times 50 = 0.95 \times 50 = 47.5;Cost(predict normal)=p(fraud∣x)×2000=0.05×2000=100\text{Cost}(\text{predict normal}) = p(\text{fraud} \mid x) \times 2000 = 0.05 \times 2000 = 100。47.5 < 100 → predict fraud。Threshold=50/(50+2000)=0.0244<0.05\text{Threshold} = 50/(50 + 2000) = 0.0244 < 0.05。

Q8. 點解 precision 會受 class imbalance 影響,但 TPR / FPR 唔會?用 slide 47 例子解釋。

TPR 只用實際 positive 嗰行(TP/(TP+FN)TP/(TP+FN)),FPR 只用實際 negative 嗰行(FP/(FP+TN)FP/(FP+TN)),各自係行內比例,唔受兩類相對數目影響。Precision=TP/(TP+FP)\text{Precision} = TP/(TP+FP) 混合咗兩行:negative 多 100 倍時 FP 亦多 100 倍(10 → 1000),precision 由 0.8 跌到 0.038,雖然 TPR=0.8TPR = 0.8、FPR=0.2FPR = 0.2 冇變。

Q9. Validation set 同 test set 有咩分別?點解唔可以用 test set 揀 hyperparameters?

Validation set 由 training data 分出,用嚟估 generalization error、tune complexity / hyperparameters、model selection;test set 只喺最後評估一次。用 test set 揀 hyperparameters 會令 test set 間接參與 training,報告嘅 performance 過度樂觀,唔再係 unseen data 嘅公正估計。

一頁總結 Cheat sheet

⭐ 考前速記
  • Errors:training (apparent)、test、generalization (expected error on same distribution)。
  • Underfitting:太簡單,train & test error 都大;Overfitting:太複雜,train error 細 test error 大。更多 training data → 減少 train/test 差距。
  • Model selection:validation set(≠ test set;缺點:少咗 training data)、model complexity(Occam's Razor)、statistical bounds。
  • Confusion matrix:a=TPa = TP、b=FNb = FN、c=FPc = FP、d=TNd = TN(行 = actual,列 = predicted)。
  • Accuracy=(a+d)/N\text{Accuracy} = (a+d)/N;Precision=a/(a+c)\text{Precision} = a/(a+c);Recall=TPR=a/(a+b)\text{Recall} = TPR = a/(a+b);F=2rp/(r+p)=2a/(2a+b+c)F = 2rp/(r+p) = 2a/(2a+b+c);TNR=d/(c+d)TNR = d/(c+d);FPR=c/(c+d)=αFPR = c/(c+d) = \alpha (Type I);FNR=b/(a+b)=βFNR = b/(a+b) = \beta (Type II)。
  • Accuracy misleading:9990 vs 10,全估 0 → 99.9%。Precision 受 imbalance 影響,TPR / FPR 唔受。
  • Cost =∑count×cost= \sum \text{count} \times \text{cost};M1 (80%, 3910) 好過 M2 (90%, 4255)。Precision 偏向 C(Y∣Y)C(\text{Y} \mid \text{Y})、C(Y∣N)C(\text{Y} \mid \text{N});Recall 偏向 C(Y∣Y)C(\text{Y} \mid \text{Y})、C(N∣Y)C(\text{N} \mid \text{Y});F 除 C(N∣N)C(\text{N} \mid \text{N}) 外全部。
  • Evaluation:holdout (2/3 : 1/3)、random subsampling (repeated holdout)、k-fold CV、LOOCV (k=nk = n)、repeated CV(估 variance)、stratified CV(imbalanced + 細樣本)。
  • ROC:y=TPRy = TPR、x=FPRx = FPR;(TPR,FPR)=(0,0)(TPR,FPR)=(0,0) 全 −、(1,1) 全 +、(1,0) ideal;diagonal random;below = 反轉。要 continuous scores;sort desc → 每個 unique score 做 threshold → 計 TPR/FPR。AUC:1 ideal、0.5 random;曲線交叉時 M1 好喺細 FPR、M2 好喺大 FPR。
  • Imbalance handling:class-based ordering、cost-sensitive (predict + if p(+∣x)>C(−,+)/(C(−,+)+C(+,−))p(+|x) > C(-,+)/(C(-,+)+C(+,-)))、sampling (under-sample majority / over-sample rare)。
  • Sick 例:0.7×1000 = 700 < 0.3×100000 = 30000 → predict sick。