All Revision Notes

COM6004 Data Mining · Chapter 4A

Classification (I): Decision Trees, KNN, Naïve Bayes & SVM

COM6004 · Chapter 4A · Source: COM6004_Chapter_4A_Classification_(I).pptx (85 slides) · Decision Trees, Nearest-Neighbor, Naïve Bayes, Support Vector Machines

Contents · 12 sections

🎯 本講重點 (Learning outcomes)

  • 定義 classification task(attribute set xx → class label yy),理解 training set / test set 同建 model 嘅一般流程。
  • 理解 Decision Tree 點樣分類、Hunt's Algorithm、各類 attributes 嘅 test conditions,並識計 Gini、Entropy、Misclassification error 同 Gain 去揀 best split。
  • 掌握 K-Nearest Neighbor:三個要素、分類步驟、kk 嘅選擇、scaling、distance-weighted voting。
  • 用 Bayes theorem 同 conditional independence 做 Naïve Bayes 計算(categorical + Gaussian continuous),理解 zero-probability 問題。
  • 理解 SVM 嘅 maximum margin 概念、linear model、support vectors、slack variables 同特性。
  • 比較四種 classifiers(eager vs lazy、speed、memory、robustness)。

⭐ 考試必溫 Top-5

  1. Gini / Entropy / Error 公式同計算;Gain=P−M\text{Gain} = P - M(weighted child impurity);用嚟揀 split(包括 continuous attribute 揀 cut point)。
  2. Naïve Bayes 完整計算(Refund = No, Divorced, Income = 120K 例子),包括 Gaussian density 同 P(Refund=Yes∣Yes)=0P(\text{Refund}=\text{Yes} \mid \text{Yes})=0 嘅問題。
  3. KNN:k 太細 / 太大嘅後果、點解要 scale attributes、weight factor w=1/d2w = 1/d^2。
  4. SVM:maximize margin 2/∥w∥2/\|\mathbf{w}\| ⇔ minimize ∥w∥2/2\|\mathbf{w}\|^2/2,constraints yi(w⋅xi+b)≥1y_i(\mathbf{w}\cdot\mathbf{x}_i + b) \ge 1;decision boundary 只取決於 support vectors。
  5. Summary 表:DT(Tree, Eager)、KNN(Instance, Lazy)、NB(Probabilistic, Eager)、SVM(Geometric, Eager)各自優缺點。

1. Classification: Definition & General Approach

Slide 3:給定一批 records(training set),每個 record 由 tuple (x,y)(x, y) 描述:

  • xx:attribute set(又叫 attribute、predictor、independent variable、input)
  • yy:class label(又叫 class、response、dependent variable、output)

Task:Learn a model that maps each attribute set xx into one of the predefined class labels yy,即將 class label 建模成 attribute set 嘅 function。

Slide 4 Goal:previously unseen records should be assigned a class as accurately as possible. 用 test set 量度 model 嘅 accuracy:通常將 data 分成 training set(建 model)同 test set(validate model)。

Task (Slide 5)Attribute set, xxClass label, yy
Categorizing email messagesFeatures extracted from email message header and contentspam or non-spam
Identifying tumor cellsFeatures extracted from x-rays or MRI scansmalignant or benign cells
Cataloging galaxiesFeatures extracted from telescope imagesElliptical, spiral, or irregular-shaped galaxies

Slide 6 "General Approach for Building Classification Model":Training Set → Learning algorithm(Induction)→ Learn Model → Apply Model 到 Test Set(Deduction)。

🖼️ Slide 6 圖片

左上係 Training Set(Tid 1–10,Attrib1 Yes/No、Attrib2 Small/Medium/Large、Attrib3 收入例如 125K,Class Yes/No),經 Induction 箭咀交俾 Learning algorithm → Learn Model → Model。左下係 Test Set(Tid 11–15,例如 11: No, Small, 55K;12: Yes, Medium, 80K;Class 全部係 "?"),經 Apply Model 再沿 Deduction 箭咀得出預測。Slides 10 同 17 係同一幅圖,分別用紅框突出 "Apply Model" 同 "Tree Induction algorithm"。

2. Decision Trees: 結構同應用

Slide 8–9 展示 decision tree 例子。Tree 由 root node、internal nodes(每個係一個 attribute test condition,叫 splitting attributes)同 leaf nodes(class label)組成。Slide 9 "Another Example" 說明:同一份 data 可以 fit 出多過一棵 tree。

本 chapter 一直用一個 10-record 例子。Slides 8–23 用 2nd edition 嘅名稱:Home Owner、Marital Status、Annual Income、class = Defaulted Borrower;slide 58 Naïve Bayes 部分就用返舊名 Refund、Taxable Income、Evade。兩套名對應同一份數據(下表用舊名,數字同 slide 8 一樣;亦同 slide 58 文字 P(No)=7/10P(\text{No}) = 7/10、P(Married∣No)=4/7P(\text{Married} \mid \text{No}) = 4/7、P(Refund=Yes∣Yes)=0P(\text{Refund} = \text{Yes} \mid \text{Yes}) = 0 完全吻合):

TidRefundMarital StatusTaxable IncomeEvade
1YesSingle125KNo
2NoMarried100KNo
3NoSingle70KNo
4YesMarried120KNo
5NoDivorced95KYes
6NoMarried60KNo
7YesDivorced220KNo
8NoSingle85KYes
9NoMarried75KNo
10NoSingle90KYes
Refund?
├── Yes → NO
└── No  → MarSt?
          ├── Married → NO
          └── Single, Divorced → TaxInc?
                                 ├── < 80K → NO
                                 └── > 80K → YES
🖼️ Slides 8–9 圖片

Slide 8:同上表一樣嘅 training data,欄位標明 categorical(Home Owner、Marital Status)、continuous(Annual Income)、class(Defaulted Borrower)。旁邊棵 tree 同上面一樣:Home Owner → MarSt → Income(< 80K / > 80K),而且用紅字標示 Home Owner、MarSt、Income 係 Splitting Attributes。

Slide 9(Another Example):同一份 data,另一棵 tree 以 MarSt 做 root:

MarSt?
├── Married → NO
└── Single, Divorced → Home Owner?
                       ├── Yes → NO
                       └── No  → Income?  < 80K → NO ; > 80K → YES

兩棵 tree 對 10 個 training records 都分類正確,即 "There could be more than one tree that fits the same data!"

2.1 Apply Model to Test Data (Slides 10–17)

Slides 11–16 一步步示範:由 root 開始,按 test record 嘅 attribute 值沿住分支行,直到 leaf(每張 slide 用紅色箭咀多行一步)。例:test record (Home Owner = No, Marital Status = Married, Annual Income = 80K, Defaulted Borrower = ?):

  1. Root:Home Owner = No → 行去 MarSt 節點
  2. MarSt = Married → 去到 leaf NO
  3. 結果:slide 16 "Assign Defaulted to "No""
💡 直覺理解

Decision tree 就好似一連串 "if-then" 問題(所以 outline 叫 "Rule-Based Classifiers - Decision Trees")。每條由 root 到 leaf 嘅路徑就係一條 rule,例如「IF Refund = No AND MarSt ∈ {Single, Divorced} AND TaxInc > 80K THEN Evade = Yes」。分類一個 record 只需要行一條路徑,所以極快。

3. Decision Tree Induction & Hunt's Algorithm

Slide 18:好多 induction algorithms:Hunt's Algorithm(最早期之一)、CART、ID3, C4.5、SLIQ, SPRINT。

ExamSlide 19:General Structure of Hunt's Algorithm。設 DtD_t 為到達 node tt 嘅 training records:

⭐ 考試重點:Hunt's Algorithm
  • 如果 DtD_t 入面所有 records 都屬同一 class yty_t,咁 tt 係 leaf node,label 為 yty_t。
  • 如果 DtD_t 包含多過一個 class 嘅 records,就用一個 attribute test 將 data split 成較細嘅 subsets,然後對每個 subset recursively apply 同一程序。

(教科書補充:如果 DtD_t 係空集,tt 就係 leaf,label 用 parent 嘅 majority class。)

Slides 20–23 用稅務 data 示範(圖片):一開始成個 data 係一個 node(label = majority class "No",7 No vs 3 Yes)→ 用 Refund split(Refund = Yes 全部 No → leaf)→ Refund = No 嗰邊再用 Marital Status split(Married 全部 No → leaf)→ Single / Divorced 嗰邊再用 Taxable Income < 80K split → 全部 nodes 變 pure。

🖼️ Slides 20–23 圖片

括號入面係 (No 數目, Yes 數目):

  • (a) 只有一個 node:Defaulted = No (7,3)
  • (b) 用 Home Owner split:Yes → Defaulted = No (3,0)(pure);No → Defaulted = No (4,3)
  • (c) Home Owner = No 嗰邊用 Marital Status split:Single, Divorced → Defaulted = Yes (1,3)(majority 係 Yes);Married → Defaulted = No (3,0)
  • (d) Single, Divorced 嗰邊再用 Annual Income split:< 80K → Defaulted = No (1,0);>= 80K → Defaulted = Yes (0,3)。全部 leaf 都 pure。

留意 (c) 嘅 Single / Divorced node 未 split 之前,label 係 majority class Yes(1 No、3 Yes),唔係 No。

4. Design Issues & Test Conditions

Slide 24–25:Decision tree induction 有兩大設計問題:

  1. How should training records be split?
    • Method for specifying test condition:視乎 attribute types(Nominal / Ordinal / Continuous)同 number of ways to split(2-way / multi-way)。
    • Measure for evaluating the goodness of a test condition:node impurity(Gini Index、Entropy、Misclassification error)。
  2. How should the splitting procedure stop?
    • Stop splitting if all the records belong to the same class or have identical attribute values。
    • Model Selection:Pre-Pruning (Early Stopping Rule)、Post-pruning(trimming the nodes)。

4.1 Test Conditions by Attribute Type (Slides 26–29)

Attribute typeMulti-way splitBinary split
Nominal(例:Marital Status)Use as many partitions as distinct values:{Single}, {Married}, {Divorced}Divides values into two subsets,例:{Married} vs {Single, Divorced}。kk 個值有 2k−1−12^{k-1}-1 種 binary splits。
Ordinal(例:Shirt Size S/M/L/XL)As many partitions as distinct valuesTwo subsets,但要 preserve order property:{S, M} vs {L, XL} ✓;{S, L} vs {M, XL} ✗(破壞次序)
Continuous(例:Annual Income)Discretize 成多個 ranges(slide 28:< 10K, [10K,25K), [25K,50K), [50K,80K), > 80K)Binary decision:(A<v)(A \lt v) or (A≥v)(A \ge v),slide 28 例子係 "Annual Income > 80K?" Yes / No

Splitting based on continuous attributes (slide 29):

  • Discretization to form an ordinal categorical attribute:ranges 用 equal interval bucketing、equal frequency bucketing(percentiles)或 clustering 搵。Static = 開頭 discretize 一次;Dynamic = 每個 node 重做。
  • Binary Decision (A<v)(A \lt v) or (A≥v)(A \ge v):考慮所有可能嘅 splits 搵 best cut;計算量可以較大。
🖼️ Slides 26–28 圖片

Slide 26:Marital Status 嘅 multi-way split 分成 Single / Divorced / Married 三枝;binary split 畫晒 3 種可能(23−1−1=32^{3-1}-1 = 3):{Married} vs {Single, Divorced}、{Single} vs {Married, Divorced}、{Single, Married} vs {Divorced}。

Slide 27:Shirt Size 嘅 multi-way split 分成 Small / Medium / Large / Extra Large 四枝。合法嘅 binary split 有 {Small, Medium} vs {Large, Extra Large} 同 {Small} vs {Medium, Large, Extra Large};{Small, Large} vs {Medium, Extra Large} 就標明 "This grouping violates order property"。

Slide 28:Annual Income 嘅 (i) binary split(> 80K? Yes / No)同 (ii) multi-way split(5 個 ranges,見上表)。

5. Choosing the Best Split: Impurity Measures

Slide 30–31:Greedy approach:nodes with purer class distribution are preferred。需要一個 measure of node impurity。例如 C0 : 5, C1 : 5(high impurity,non-homogeneous)vs C0 : 9, C1 : 1(low impurity,homogeneous)。

⭐ 考試重點:三個 impurity 公式 (Slide 32)
Gini Index(t)=1−∑i=0c−1pi(t)2\text{Gini Index}(t) = 1 - \sum_{i=0}^{c-1} p_i(t)^2
Entropy(t)=−∑i=0c−1pi(t)log⁡2pi(t)\text{Entropy}(t) = -\sum_{i=0}^{c-1} p_i(t)\log_2 p_i(t)
Classification error(t)=1−max⁡i [pi(t)]\text{Classification error}(t) = 1 - \max_i\,[p_i(t)]

pi(t)p_i(t) 係 node tt 入面 class ii 嘅 frequency(比例),cc 係 classes 總數。

最細(pure node)最大(均勻分佈)2-class 最大
Gini01−1/c1 - 1/c0.5
Entropy0log⁡2c\log_2 c1
Error01−1/c1 - 1/c0.5

5.1 Worked example:計單一 node 嘅 impurity

Node (C1, C2)pGiniEntropyError
(0, 6)0, 11−0−1=1 - 0 - 1 = 0−0−1⋅log⁡21=-0 - 1 \cdot \log_2 1 = 01−1=1 - 1 = 0
(1, 5)1/6, 5/61−(1/6)2−(5/6)2=1 - (1/6)^2 - (5/6)^2 = 0.278−(1/6)log⁡2(1/6)−(5/6)log⁡2(5/6)=-(1/6)\log_2(1/6) - (5/6)\log_2(5/6) = 0.6501−5/6=1 - 5/6 = 0.167
(2, 4)2/6, 4/61−(1/3)2−(2/3)2=1 - (1/3)^2 - (2/3)^2 = 0.4440.9181−4/6=1 - 4/6 = 0.333
(3, 3)0.5, 0.50.510.5

三個 measures 嘅排序一致(越 pure 越細),只係數值唔同。Entropy 對 impurity 最敏感。

5.2 Finding the Best Split (Slides 33–34)

⭐ 考試重點:Gain 步驟
  1. 計 splitting 前嘅 impurity measure PP(parent)。
  2. 計 splitting 後嘅 impurity measure MM:先計每個 child node 嘅 impurity,MM = child nodes 嘅 weighted impurity:
    M=∑j=1knjn I(childj)M = \sum_{j=1}^{k} \frac{n_j}{n}\, I(\text{child}_j)
  3. 揀產生最高 gain 嘅 attribute test condition:
    Gain=P−M\text{Gain} = P - M
    或等價地,揀 splitting 後 impurity MM 最低嘅。

用 entropy 計嘅 gain 叫 Information Gain。

5.3 Worked example:用 10-record data 揀 root split(Gini)

Parent:7 No、3 Yes → P=1−0.72−0.32=1−0.49−0.09=0.42P = 1 - 0.7^2 - 0.3^2 = 1 - 0.49 - 0.09 = \mathbf{0.42}

(a) Refund:

  • Refund = Yes:3 records(No 3, Yes 0)→ Gini=0\text{Gini} = 0
  • Refund = No:7 records(No 4, Yes 3)→ Gini=1−(4/7)2−(3/7)2=1−25/49=0.490\text{Gini} = 1 - (4/7)^2 - (3/7)^2 = 1 - 25/49 = 0.490
  • M=(3/10)(0)+(7/10)(0.490)=M = (3/10)(0) + (7/10)(0.490) = 0.343 → Gain=0.42−0.343=\text{Gain} = 0.42 - 0.343 = 0.077

(b) Marital Status(multi-way):

  • Single:4 records(Tid 1, 3, 8, 10 → No 2, Yes 2)→ Gini=0.5\text{Gini} = 0.5
  • Married:4 records(Tid 2, 4, 6, 9 → No 4)→ Gini=0\text{Gini} = 0
  • Divorced:2 records(Tid 5 Yes, 7 No)→ Gini=0.5\text{Gini} = 0.5
  • M=0.4(0.5)+0.4(0)+0.2(0.5)=M = 0.4(0.5) + 0.4(0) + 0.2(0.5) = 0.300 → Gain=\text{Gain} = 0.120

(c) Marital Status(binary {Married} vs {Single, Divorced}):{S, D} 有 6 records(No 3, Yes 3)→ Gini 0.5 → M=0.6(0.5)+0.4(0)=M = 0.6(0.5) + 0.4(0) = 0.300(同 multi-way 一樣)。

(d) Taxable Income(continuous,binary split):先排序,再喺相鄰值中點試每個 cut:

Sorted income607075859095100120125220
ClassNoNoNoYesYesYesNoNoNoNo
Cut vv≤v\le v (Yes, No)>v> v (Yes, No)Weighted Gini
65(0, 1)(3, 6)0.400
72.5(0, 2)(3, 5)0.375
80(0, 3)(3, 4)0.343
87.5(1, 3)(2, 4)0.417
92.5(2, 3)(1, 4)0.400
97.5(3, 3)(0, 4)0.300 ← best
110(3, 4)(0, 3)0.343
122.5(3, 5)(0, 2)0.375
172.5(3, 6)(0, 1)0.400

例:v=97.5v = 97.5:左 6 records Gini 0.5,右 4 records Gini 0 → M=0.6×0.5=0.3M = 0.6 \times 0.5 = 0.3。

結論:Marital Status 同 Taxable Income (≤97.5\le 97.5) 都得 M=0.300M = 0.300(Gain 0.12),好過 Refund(M=0.343M = 0.343)。

💡 計 continuous split 嘅技巧

(1) 先 sort;(2) 只需要喺 class label 改變嘅相鄰位置試 cut(例如 75→85、95→100),其他位置唔會係最佳;(3) 由左至右掃描,逐步更新左右兩邊嘅 class counts,唔使每次重新數。

5.4 Worked example:Information Gain(Entropy)

Parent entropy:H=−0.3log⁡20.3−0.7log⁡20.7=0.521+0.360=0.881H = -0.3\log_2 0.3 - 0.7\log_2 0.7 = 0.521 + 0.360 = \mathbf{0.881}

  • Refund:Refund = No (3 Yes, 4 No) entropy=0.985\text{entropy} = 0.985;M=0.7×0.985=0.690M = 0.7 \times 0.985 = 0.690;IG=0.881−0.690=0.192IG = 0.881 - 0.690 = 0.192
  • Marital Status:Single (2, 2) = 1;Married = 0;Divorced (1, 1) = 1;M=0.4+0+0.2=0.6M = 0.4 + 0 + 0.2 = 0.6;IG=0.281IG = 0.281
  • Income ≤97.5\le 97.5:(3, 3) = 1;(0, 4) = 0;M=0.6M = 0.6;IG=0.281IG = 0.281

同 Gini 結論一致:Refund 最差。

⚠️ 常見錯誤
  • 計 MM 時忘記用 child size 做 weight(直接平均 children impurity)。
  • log⁡2\log_2 用錯 base(用咗 ln⁡\ln 或 log⁡10\log_{10})。計數機:log⁡2x=ln⁡x/ln⁡2\log_2 x = \ln x / \ln 2。
  • 以為 Gain 越細越好——Gain 越大越好(或 MM 越細越好)。
  • Multi-way split 有好多細 partitions 時(例如用 Customer ID split,每個 child 只有 1 個 record,impurity 全部 0)gain 會好高但冇用——呢個係 impurity-based gain 偏好多值 attributes 嘅問題。
from sklearn.tree import DecisionTreeClassifier, export_text
clf = DecisionTreeClassifier(criterion="gini")   # 或 criterion="entropy"
clf.fit(X_train, y_train)
print(export_text(clf, feature_names=list(X_train.columns)))

6. Stopping, Strengths & Weaknesses of Decision Trees

Stopping Criteria (slide 35):

  • 所有 records 屬同一 class 就停止 expand 該 node。
  • 所有 records 嘅 attribute values 相似(identical)就停止。
  • Early termination(防止 overfitting,詳見 Chapter 4B)。
⭐ 考試重點:Decision Tree 優缺點 (Slide 36)
AdvantagesDisadvantages
  • Inexpensive to construct
  • Extremely fast at classifying unknown records
  • Easy to interpret for small-sized trees
  • Robust to noise (especially when methods to avoid overfitting are employed)
  • Can easily handle redundant or irrelevant attributes (unless the attributes are interacting)
  • Space of possible decision trees is exponentially large. Greedy approaches are often unable to find the best tree.
  • Does not consider interactions between attributes
  • Each decision boundary involves only a single attribute

Handling interactions (slide 37) 同 Limitations of single attribute-based decision boundaries (slide 38):因為每個 test 只用一個 attribute,decision boundaries 永遠平行於坐標軸(axis-parallel,好似樓梯級)。如果真正嘅 boundary 係斜線(例如 x+y<1x + y \lt 1)或者 class 取決於兩個 attributes 嘅 interaction(例如 XOR 型),tree 就要好多層先近似到。

⭐ Slide 37:Handling interactions(XOR 例子)

X–Y 平面上有四團點,排成 XOR 格局:左上同右下係 +(1000 instances,藍),左下同右上係 o(1000 instances,紅)。單獨睇 X 或者單獨睇 Y,兩個 class 都係一半一半,所以:

  • Entropy(X) = 0.99、Entropy(Y) = 0.99(split 完差唔多冇改善)
  • 再加一個 Z:佢係由 uniform distribution 產生嘅 noisy attribute,同 class 完全無關,但 Entropy(Z) = 0.98
  • 結果 "Attribute Z will be chosen for splitting!":greedy 嘅 tree 揀咗一個純 noise 嘅 attribute

原因係 X 同 Y 要一齊睇先有用(interaction),但 greedy split 每次只評估一個 attribute,所以睇唔到。下面兩幅 Z–X、Z–Y 圖亦見到,紅藍點喺每條帶入面完全混埋。

🖼️ Slide 38 圖片

兩個 class 都由 skewed Gaussian 產生(+ 中心 (8,8),o 中心 (12,12)),兩團點沿住一條斜線(大約 x+y=20x + y = 20)分開。Decision tree 畫出嚟嘅 boundary 係好多細小嘅長方形格仔,好似樓梯咁沿住斜線堆出嚟,要用好多個 split 先近似到一條簡單嘅斜線。

7. Nearest-Neighbor Classifiers (KNN)

Slide 40 Basic idea:"If it walks like a duck, quacks like a duck, then it's probably a duck."

ExamSlide 41:Requires three things:

  1. The set of labeled records
  2. Distance metric to compute distance between records
  3. The value of kk, the number of nearest neighbors to retrieve

Slide 42:To classify an unknown record:

  1. Compute distance to other training records
  2. Identify kk nearest neighbors
  3. Use class labels of nearest neighbors to determine the class label of unknown record(e.g., by taking majority vote)

Slide 43:Compute proximity,例如 Euclidean distance d(x,y)=∑i(xi−yi)2d(\mathbf{x},\mathbf{y}) = \sqrt{\sum_i (x_i - y_i)^2}。決定 class:

  • Take the majority vote of class labels among the kk-nearest neighbors
  • Weight the vote according to distance:weight factor w=1/d2w = 1/d^2

7.1 Worked example(自擬)

Training:P1(1,1)P_1(1,1) A、P2(2,2)P_2(2,2) A、P3(3,1)P_3(3,1) A、P4(5,4)P_4(5,4) B、P5(6,5)P_5(6,5) B、P6(4,4)P_6(4,4) B。Test X=(3.2,3)X = (3.2, 3)。

PointClassEuclidean distance to XXw=1/d2w = 1/d^2Rank
P6P_6 (4,4)B0.64+1=1.281\sqrt{0.64+1} = 1.2810.6091
P2P_2 (2,2)A1.44+1=1.562\sqrt{1.44+1} = 1.5620.4102
P3P_3 (3,1)A0.04+4=2.010\sqrt{0.04+4} = 2.0100.2483
P4P_4 (5,4)B3.24+1=2.059\sqrt{3.24+1} = 2.0590.2364
P1P_1 (1,1)A4.84+4=2.973\sqrt{4.84+4} = 2.9730.1135
P5P_5 (6,5)B7.84+4=3.441\sqrt{7.84+4} = 3.4410.0846
  • k=1k = 1:最近係 P6P_6 → B
  • k=3k = 3:P6P_6 (B)、P2P_2 (A)、P3P_3 (A) → majority A(2:1)
  • k=3k = 3, distance-weighted:B=0.609B = 0.609;A=0.410+0.248=0.658A = 0.410 + 0.248 = 0.658 → A(好接近!)
  • k=5k = 5:B, A, A, B, A → A(3:2)

結論:kk 嘅選擇可以改變答案。

7.2 Choosing k & Proximity (Slides 44–45)

⭐ 考試重點:k 嘅選擇
  • If kk is too small, sensitive to noise points(k=1k = 1 時一個 mislabeled 點就會誤導)。
  • If kk is too large, neighborhood may include points from other classes(決策變得太「平均」,被大 class 主導)。

實務:用 cross-validation 揀 kk;binary classification 用奇數 kk 避免打和。

Slide 45:Choice of proximity measure matters——視乎 data types 同 attribute types(例如 documents 用 cosine,binary 用 Jaccard,見 Chapter 2)。

7.3 Data Preprocessing for KNN (Slide 46)

ExamAttributes may have to be scaled to prevent distance measures from being dominated by one of the attributes。例:

  • height of a person may vary from 1.5m to 1.8m
  • weight of a person may vary from 90lb to 300lb
  • income of a person may vary from $10K to $1M

唔 scale 嘅話,distance 幾乎完全由 income 決定。Time series 通常 standardize 成 mean 0、standard deviation 1(Z-score transformation)。

7.4 其他特性 (Slides 47–49)

  • Local classifiers:只用附近嘅點決定,can produce decision boundaries of arbitrary shapes(1-NN 嘅 decision boundary 係 Voronoi diagram 形狀,slide 47 圖)。
  • Missing values:proximity 計算通常需要全部 attributes;有啲方法只用兩個 instances 都有嘅 attributes subset,但咁樣每對 instances 實際用唔同嘅 proximity measure,proximities are not comparable,效果未必好。
  • Irrelevant attributes add noise to the proximity measure;Redundant attributes bias the proximity measure towards certain attributes。可用 variable selection 或 dimensionality reduction 處理。
💡 直覺理解:Lazy learner

KNN 唔會預先「學」任何 model——training 只係將 data 存起(所以 training very fast),每次 predict 先計同所有 training records 嘅距離(所以 prediction slow、memory 用量高)。呢類叫 instance-based / lazy learner;Decision tree、Naïve Bayes、SVM 就係 eager learners。

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
knn = make_pipeline(StandardScaler(),
                    KNeighborsClassifier(n_neighbors=3, weights="distance"))  # 先 scale 再 KNN
knn.fit(X_train, y_train); knn.predict(X_test)

8. Naïve Bayes Classifiers

8.1 Bayes Classifier (Slides 51–54)

A probabilistic framework for solving classification problems。

Conditional Probability: P(Y∣X)=P(X,Y)P(X),P(X∣Y)=P(X,Y)P(Y)\text{Conditional Probability: } P(Y\mid X) = \frac{P(X,Y)}{P(X)}, \qquad P(X\mid Y) = \frac{P(X,Y)}{P(Y)}
Bayes theorem: P(Y∣X)=P(X∣Y) P(Y)P(X)\text{Bayes theorem: } P(Y\mid X) = \frac{P(X\mid Y)\,P(Y)}{P(X)}

將每個 attribute 同 class label 當 random variables。給定 record with attributes (X1,X2,…,Xd)(X_1, X_2, \dots, X_d),目標係預測 class YY:搵令 P(Y∣X1,…,Xd)P(Y \mid X_1, \dots, X_d) 最大嘅 YY。

Slide 53 問:可唔可以直接由 data 估計 P(Evade=Yes∣X)P(\text{Evade} = \text{Yes} \mid X) 同 P(Evade=No∣X)P(\text{Evade} = \text{No} \mid X)?(X=(Refund=No,Divorced,Income=120K)X = (\text{Refund} = \text{No}, \text{Divorced}, \text{Income} = 120\text{K}))——通常唔得,因為 training data 未必有完全相同 attribute 組合嘅 record。

ExamApproach (slide 54):用 Bayes theorem 計 posterior probability:

P(Y∣X1…Xd)=P(X1X2…Xd∣Y) P(Y)P(X1X2…Xd)P(Y \mid X_1 \dots X_d) = \frac{P(X_1 X_2 \dots X_d \mid Y)\, P(Y)}{P(X_1 X_2 \dots X_d)}

Maximum a-posteriori (MAP):揀令 P(Y∣X1…Xd)P(Y \mid X_1 \dots X_d) 最大嘅 YY。因為分母對所有 class 一樣,等價於揀令 P(X1…Xd∣Y) P(Y)P(X_1 \dots X_d \mid Y)\,P(Y) 最大嘅 YY。問題:點估計 P(X1…Xd∣Y)P(X_1 \dots X_d \mid Y)?

8.2 Naïve Bayes Assumption (Slide 56)

Exam假設 class 已知時 attributes 之間 conditional independence:

P(X1,X2,…,Xd∣Yj)=P(X1∣Yj) P(X2∣Yj)⋯P(Xd∣Yj)P(X_1, X_2, \dots, X_d \mid Y_j) = P(X_1 \mid Y_j)\, P(X_2 \mid Y_j) \cdots P(X_d \mid Y_j)

Example:Arm length and reading skills:細路仔手臂較短、閱讀能力有限(同成人比)→ 兩者表面上相關;但如果 age 固定,arm length 同 reading skills 冇明顯關係 → 佢哋係 conditionally independent given age。

咁就可以由 training data 估計每個 P(Xi∣Yj)P(X_i \mid Y_j)。新點分類到令 P(Yj)∏iP(Xi∣Yj)P(Y_j)\prod_i P(X_i \mid Y_j) 最大嘅 YjY_j。

8.3 Estimate Probabilities from Data (Slides 58–60)

  • Class prior:P(y)P(y) = fraction of instances of class yy。例:P(No)=7/10P(\text{No}) = 7/10,P(Yes)=3/10P(\text{Yes}) = 3/10。
  • Categorical attributes:P(Xi=c∣y)=nc/nP(X_i = c \mid y) = n_c / n,ncn_c = 屬於 class yy 而 attribute value 為 cc 嘅 instances 數,nn = 屬於 class yy 嘅 instances 數。例:P(Status=Married∣No)=4/7P(\text{Status} = \text{Married} \mid \text{No}) = 4/7、P(Refund=Yes∣Yes)=0P(\text{Refund} = \text{Yes} \mid \text{Yes}) = 0。
  • Continuous attributes(slide 59):
    • Discretization:將 range 分 bins,用 bin value 代替(continuous → ordinal)。
    • Probability density estimation:假設 attribute 跟 normal distribution,用 data 估 parameters(mean、standard deviation),再用 distribution 估 conditional probability。
P(Xi=x∣Yj)=12πσij2  e−(x−μij)22σij2P(X_i = x \mid Y_j) = \frac{1}{\sqrt{2\pi\sigma_{ij}^2}}\; e^{-\frac{(x-\mu_{ij})^2}{2\sigma_{ij}^2}}

Slide 60 例子:For (Income, Class = No):sample mean = 110、sample variance = 2975,所以 P(Income=120∣No)=12π(54.54)e−(120−110)22(2975)=0.0072P(\text{Income} = 120 \mid \text{No}) = \frac{1}{\sqrt{2\pi}(54.54)} e^{-\frac{(120-110)^2}{2(2975)}} = 0.0072。公式要 one for each (Xi,Yj)(X_i, Y_j) pair,即每個 attribute 同每個 class 嘅組合各有一套 μij\mu_{ij}、σij2\sigma_{ij}^2。

🖼️ Slides 61–63 圖片

Slide 61 列晒所有 conditional probabilities:P(Refund=Yes∣No)=3/7P(\text{Refund}=\text{Yes} \mid \text{No}) = 3/7、P(Refund=No∣No)=4/7P(\text{Refund}=\text{No} \mid \text{No}) = 4/7、P(Refund=Yes∣Yes)=0P(\text{Refund}=\text{Yes} \mid \text{Yes}) = 0、P(Refund=No∣Yes)=1P(\text{Refund}=\text{No} \mid \text{Yes}) = 1;Marital Status given No:Single 2/7、Divorced 1/7、Married 4/7;given Yes:Single 2/3、Divorced 1/3、Married 0;Income:No 嘅 mean 110、variance 2975,Yes 嘅 mean 90、variance 25。下面 8.4 嘅 worked example 同 slide 61 數字完全一樣。

Slides 62–63 示範「逐步加入資料」:冇任何 attribute 資料時,只可以用 a priori 嘅 P(Yes)=3/10P(\text{Yes}) = 3/10、P(No)=7/10P(\text{No}) = 7/10;只知道 Divorced:P(Yes∣Divorced)=1/3×3/10/P(Divorced)P(\text{Yes} \mid \text{Divorced}) = 1/3 \times 3/10 / P(\text{Divorced})、P(No∣Divorced)=1/7×7/10/P(Divorced)P(\text{No} \mid \text{Divorced}) = 1/7 \times 7/10 / P(\text{Divorced});再加 Refund = No:Yes 嗰邊乘多個 1、No 嗰邊乘多個 4/7;再加 Income = 120:Yes 嗰邊乘 1.2×10−91.2 \times 10^{-9}、No 嗰邊乘 0.0072。分母相同,所以只需要比較分子。

8.4 Worked example:X = (Refund = No, Divorced, Income = 120K)

⭐ 考試重點:完整 Naïve Bayes 計算

Step 1 — Priors:P(No)=7/10P(\text{No}) = 7/10,P(Yes)=3/10P(\text{Yes}) = 3/10。

Step 2 — Categorical conditionals(由數據表數):

  • Class No(7 records:Tid 1, 2, 3, 4, 6, 7, 9):Refund = No 有 Tid 2, 3, 6, 9 → P(Refund=No∣No)=P(\text{Refund} = \text{No} \mid \text{No}) = 4/7;Divorced 只有 Tid 7 → P(Divorced∣No)=P(\text{Divorced} \mid \text{No}) = 1/7。
  • Class Yes(3 records:Tid 5, 8, 10):Refund 全部 No → P(Refund=No∣Yes)=P(\text{Refund} = \text{No} \mid \text{Yes}) = 1;Divorced 有 Tid 5 → P(Divorced∣Yes)=P(\text{Divorced} \mid \text{Yes}) = 1/3。

Step 3 — Income(Gaussian):

  • Class No incomes:125, 100, 70, 120, 60, 220, 75 → mean=770/7=\text{mean} = 770/7 = 110;sample variance=\text{sample variance} = 2975(sd=54.54\text{sd} = 54.54)。 P(120∣No)=12π(2975)e−(120−110)22(2975)=0.0072P(120 \mid \text{No}) = \frac{1}{\sqrt{2\pi(2975)}} e^{-\frac{(120-110)^2}{2(2975)}} = \mathbf{0.0072}
  • Class Yes incomes:95, 85, 90 → mean=\text{mean} = 90;variance=\text{variance} = 25(sd=5\text{sd} = 5)。 P(120∣Yes)=12π(25)e−(120−90)22(25)=1.2×10−9P(120 \mid \text{Yes}) = \frac{1}{\sqrt{2\pi(25)}} e^{-\frac{(120-90)^2}{2(25)}} = \mathbf{1.2 \times 10^{-9}}

Step 4 — Likelihoods(slide 57 結構):

  • P(X∣No)=P(Refund=No∣No)×P(Divorced∣No)×P(Income=120K∣No)=4/7×1/7×0.0072=P(X \mid \text{No}) = P(\text{Refund} = \text{No} \mid \text{No}) \times P(\text{Divorced} \mid \text{No}) \times P(\text{Income} = 120\text{K} \mid \text{No}) = 4/7 \times 1/7 \times 0.0072 = 0.0006
  • P(X∣Yes)=1×1/3×1.2×10−9=P(X \mid \text{Yes}) = 1 \times 1/3 \times 1.2 \times 10^{-9} = 4×10−104 \times 10^{-10}

Step 5 — 乘 prior 比較:P(X∣No)P(No)=0.0006×0.7=4.2×10−4P(X \mid \text{No})P(\text{No}) = 0.0006 \times 0.7 = 4.2 \times 10^{-4};P(X∣Yes)P(Yes)=4×10−10×0.3=1.2×10−10P(X \mid \text{Yes})P(\text{Yes}) = 4 \times 10^{-10} \times 0.3 = 1.2 \times 10^{-10}。

因為 P(X∣No)P(No)>P(X∣Yes)P(Yes)P(X \mid \text{No})P(\text{No}) > P(X \mid \text{Yes})P(\text{Yes}) → P(No∣X)>P(Yes∣X)P(\text{No} \mid X) > P(\text{Yes} \mid X) → 分類為 Evade = No。

⚠️ 常見錯誤
  • 忘記乘 prior P(Y)P(Y)。
  • Gaussian density 唔係 probability(可以大過 1),但喺比較中可以照用。
  • Variance 用 sample variance(分母 n−1n - 1):Class No 嘅 ∑(x−110)2=17850\sum(x-110)^2 = 17850,÷ 6 = 2975。

8.5 Issues with Naïve Bayes (Slides 64–66)

由 slide 58 可見 P(Refund=Yes∣Yes)=0P(\text{Refund} = \text{Yes} \mid \text{Yes}) = 0。如果 test record 係 Refund = Yes,咁 P(X∣Yes)P(X \mid \text{Yes}) 成個乘積都會變 0——無論其他 attributes 幾支持 Yes 都冇用。如果某 record 對兩個 class 都有一個 conditional probability = 0,就完全分類唔到。

Slide 64:P(Yes∣Married)=0×3/10/P(Married)P(\text{Yes} \mid \text{Married}) = 0 \times 3/10 / P(\text{Married}),因為 P(Married∣Yes)=0P(\text{Married} \mid \text{Yes}) = 0;P(No∣Married)=4/7×7/10/P(Married)P(\text{No} \mid \text{Married}) = 4/7 \times 7/10 / P(\text{Married})。

⭐ Slide 65:刪咗 Tid 7 之後

Tid 7(Yes, Divorced, 220K, No)刪除後,class No 剩 6 個 records:P(Refund=Yes∣No)=2/6P(\text{Refund}=\text{Yes} \mid \text{No}) = 2/6、P(Divorced∣No)=0P(\text{Divorced} \mid \text{No}) = 0(唯一一個 Divorced + No 就係 Tid 7),Income 嘅 mean 變 91、variance 685;class Yes 不變,P(Refund=Yes∣Yes)=0P(\text{Refund}=\text{Yes} \mid \text{Yes}) = 0。

Given X=(Refund=Yes,Divorced,120K)X = (\text{Refund} = \text{Yes}, \text{Divorced}, 120\text{K}):

  • P(X∣No)=2/6×0×0.0083=0P(X \mid \text{No}) = 2/6 \times 0 \times 0.0083 = 0
  • P(X∣Yes)=0×1/3×1.2×10−9=0P(X \mid \text{Yes}) = 0 \times 1/3 \times 1.2 \times 10^{-9} = 0

兩邊都係 0 → "Naïve Bayes will not be able to classify X as Yes or No!"

Slide 66 嘅解決方法:Need to use other estimates of conditional probabilities than simple fractions:

original: P(Xi=c∣y)=ncnLaplace Estimate: P(Xi=c∣y)=nc+1n+vm-estimate: P(Xi=c∣y)=nc+mpn+m\text{original: } P(X_i = c \mid y) = \frac{n_c}{n} \qquad \text{Laplace Estimate: } P(X_i = c \mid y) = \frac{n_c + 1}{n + v} \qquad \text{m-estimate: } P(X_i = c \mid y) = \frac{n_c + mp}{n + m}

其中 nn = number of training instances belonging to class yy;ncn_c = number of instances with Xi=cX_i = c and Y=yY = y;vv = total number of attribute values that XiX_i can take;pp = initial estimate of P(Xi=c∣y)P(X_i = c \mid y) known apriori;mm = hyper-parameter for our confidence in pp。例:Laplace 下 P(Refund=Yes∣Yes)=(0+1)/(3+2)=P(\text{Refund} = \text{Yes} \mid \text{Yes}) = (0 + 1)/(3 + 2) = 0.2(唔再係 0)。

8.6 Characteristics of Naïve Bayes (Slide 67)

  • Robust to isolated noise points(概率係由大量 records 平均估計)
  • Handle missing values by ignoring the instance during probability estimate calculations
  • Robust to irrelevant attributes(irrelevant attribute 嘅 P(Xi∣Y)P(X_i \mid Y) 對所有 class 差唔多,乘落去唔改變排序)
  • Redundant and correlated attributes will violate class conditional independence assumption(同一資訊被乘兩次,過度影響結果)
from sklearn.naive_bayes import GaussianNB, CategoricalNB
GaussianNB().fit(X_num, y)             # continuous attributes,假設 normal
CategoricalNB(alpha=1).fit(X_cat, y)   # categorical;alpha=1 即 Laplace smoothing

9. Support Vector Machines (SVM)

9.1 Maximum Margin Idea (Slides 69–75)

  • Slide 69:Find a linear hyperplane (decision boundary) that will separate the data。
  • Slides 70–72:有好多個可能嘅 hyperplanes("One possible solution"、"Another possible solution"、"Other possible solutions")都可以將兩類分開。
  • Slide 73:Which one is better? B1 or B2? How do you define better?
  • Slide 74:ExamFind hyperplane maximizes the margin → B1 is better than B2.

Margin = decision boundary 同兩邊最近 data points 之間嘅距離(兩條平行 hyperplanes b11b_{11}、b12b_{12} 之間嘅闊度)。Margin 越大,對新 data 嘅 generalization 越好(對 noise 有更大緩衝)。

🖼️ Slides 69–75 圖片

每幅都係同一份 2D data:右上一堆紅色 ○,左下一堆綠色 ■,中間有空隙。Slides 70–72 畫出幾條都可以分開兩類嘅直線。Slide 74 比較兩條:B1 係斜向右下嘅實線,兩邊平行虛線 b11b_{11}、b12b_{12} 之間嘅 margin 好闊;B2 係近乎水平嘅虛線,佢嘅 b21b_{21}、b22b_{22} 幾乎貼住條線,margin 好窄。所以 B1 較好。Slide 75 喺 B1 上面標示:中間線係 w⋅x+b=0\mathbf{w}\cdot\mathbf{x} + b = 0,兩條邊界係 w⋅x+b=+1\mathbf{w}\cdot\mathbf{x} + b = +1(○ 嗰邊,b11b_{11})同 =−1= -1(■ 嗰邊,b12b_{12}),Margin=2/∥w∥\text{Margin} = 2/\|\mathbf{w}\|。

9.2 Linear SVM (Slides 76–79)

Linear model:

f(x)={+1if w⋅x+b≥1−1if w⋅x+b≤−1f(\mathbf{x}) = \begin{cases} +1 & \text{if } \mathbf{w}\cdot\mathbf{x} + b \ge 1 \\ -1 & \text{if } \mathbf{w}\cdot\mathbf{x} + b \le -1 \end{cases}

Decision boundary:w⋅x+b=0\mathbf{w}\cdot\mathbf{x} + b = 0;兩條 margin hyperplanes:w⋅x+b=±1\mathbf{w}\cdot\mathbf{x} + b = \pm 1。Learning the model is equivalent to determining the values of w\mathbf{w} and bb.

⭐ 考試重點:Learning Linear SVM (Slide 77)

Objective is to maximize:Margin=2∥w∥\text{Margin} = \dfrac{2}{\|\mathbf{w}\|}

Which is equivalent to minimizing:L(w)=∥w∥22L(\mathbf{w}) = \dfrac{\|\mathbf{w}\|^2}{2}

Subject to the following constraints:

yi={+1if w⋅xi+b≥1−1if w⋅xi+b≤−1oryi(w⋅xi+b)≥1, i=1,…,Ny_i = \begin{cases} +1 & \text{if } \mathbf{w}\cdot\mathbf{x}_i + b \ge 1 \\ -1 & \text{if } \mathbf{w}\cdot\mathbf{x}_i + b \le -1 \end{cases} \quad \text{or} \quad y_i(\mathbf{w}\cdot\mathbf{x}_i + b) \ge 1,\ i = 1,\dots,N

呢個係 constrained optimization problem,用 Lagrange multiplier method 解。

🖼️ Slide 78 表格

8 個 training points (x1,x2,y)(x_1, x_2, y) 同各自嘅 Lagrange multiplier λ\lambda:

x1x_1x2x_2yyλ\lambda
0.38580.4687165.5261
0.48710.611−165.5261
0.92180.4103−10
0.73820.8936−10
0.17630.057910
0.40570.352910
0.93550.8132−10
0.21460.009910

只有頭兩點嘅 λ>0\lambda \gt 0,slide 用紅圈標示佢哋係 support vectors;其餘 6 點 λ=0\lambda = 0,對 decision boundary 冇影響。

  • Slide 78:Support vectors 係 Lagrange multipliers λi>0\lambda_i \gt 0 嘅點(即剛好喺 margin 上嘅點;細節略過)。
  • Slide 79:Decision boundary depends only on support vectors——如果另一個 data set 有相同 support vectors,decision boundary 唔會變(其他點移動或刪除都唔影響)。
  • 搵到 w\mathbf{w}、bb 之後點分類 test record x\mathbf{x}?(Slide 79 寫嘅係 f(xi)=1f(\mathbf{x}_i) = 1 if w⋅xi+b≥1\mathbf{w}\cdot\mathbf{x}_i + b \ge 1、−1-1 if ≤−1\le -1,即係 training 時嘅 margin 條件;實際分類時,落喺 margin 入面嘅點就睇 w⋅x+b\mathbf{w}\cdot\mathbf{x} + b 係正定負,即下式)
    f(x)={+1if w⋅x+b≥0−1if w⋅x+b<0f(\mathbf{x}) = \begin{cases} +1 & \text{if } \mathbf{w}\cdot\mathbf{x} + b \ge 0 \\ -1 & \text{if } \mathbf{w}\cdot\mathbf{x} + b \lt 0 \end{cases}
💡 Worked example(自擬)

假設學到 w=(1,1)\mathbf{w} = (1, 1)、b=−3b = -3。

  • Test x=(2.5,1.5)\mathbf{x} = (2.5, 1.5):1(2.5)+1(1.5)−3=1≥01(2.5) + 1(1.5) - 3 = 1 \ge 0 → +1(剛好喺 margin 上,可能係 support vector)
  • Test x=(1,1)\mathbf{x} = (1, 1):1+1−3=−1<01 + 1 - 3 = -1 \lt 0 → −1
  • Margin=2/∥w∥=2/12+12=2/2=1.414\text{Margin} = 2/\|\mathbf{w}\| = 2/\sqrt{1^2+1^2} = 2/\sqrt{2} = \mathbf{1.414}

如果想 margin 更大,就要 ∥w∥\|\mathbf{w}\| 更細——所以 minimize ∥w∥2/2\|\mathbf{w}\|^2/2。

9.3 Non-linearly Separable: Slack Variables (Slides 80–81)

如果問題唔係 linearly separable?引入 slack variables ξi≥0\xi_i \ge 0,容許部分點越過 margin 甚至分錯:

min⁡  L(w)=∥w∥22+C(∑i=1Nξi)k\min\; L(\mathbf{w}) = \frac{\|\mathbf{w}\|^2}{2} + C\left(\sum_{i=1}^{N} \xi_i\right)^{k}
Subject to: yi={+1if w⋅xi+b≥1−ξi−1if w⋅xi+b≤−1+ξi\text{Subject to: } y_i = \begin{cases} +1 & \text{if } \mathbf{w}\cdot\mathbf{x}_i + b \ge 1 - \xi_i \\ -1 & \text{if } \mathbf{w}\cdot\mathbf{x}_i + b \le -1 + \xi_i \end{cases}

If kk is 1 or 2, this leads to similar objective function as linear SVM but with different constraints。CC 控制「大 margin」同「少錯誤」之間嘅 trade-off(CC 大 → 少容忍錯誤)。

(上式同 slide 81 一樣:成個 ∑ξi\sum \xi_i 先至 kk 次方。Slide 用藍圈突出 constraints 入面嘅 1−ξi1 - \xi_i 同 −1+ξi-1 + \xi_i,即係同 linear SVM 唯一唔同嘅地方。)

9.4 Characteristics of SVM (Slides 82–83)

  • Learning problem 係 convex optimization problem:有 efficient algorithms 搵 global minima(其他好多方法用 greedy approaches,只搵到 locally optimal solutions,例如 decision tree)。
  • High computational complexity for building the model(training 慢)。
  • Robust to noise。
  • Overfitting is handled by maximizing the margin of the decision boundary。
  • SVM can handle irrelevant and redundant attributes better than many other techniques。
  • Difficult to handle missing values。
from sklearn.svm import SVC
svm = make_pipeline(StandardScaler(), SVC(kernel="linear", C=1.0))
svm.fit(X_train, y_train)
svm[-1].coef_, svm[-1].intercept_, svm[-1].support_vectors_   # w, b, support vectors

10. Summary: 四種 Classifiers 比較

⭐ 考試重點:Slide 84 Summary 表(建議背)
Decision TreeKNNNaïve BayesSVM
ModelTree, EagerInstance, LazyProbabilistic, EagerGeometric, Eager
Training speedFast to mediumVery fastVery fastSlow to very slow
Prediction speedVery fastSlowVery fastFast
Memory usageLowHighLowMedium
Robust to noiseGoodPoorModerateExcellent
Irrelevant attributeGoodVery poorModerateGood
Redundant attributeGoodPoorVery poorExcellent

記憶法:KNN 係 lazy(training 唔做嘢 → very fast;prediction 要計晒距離 → slow;要存晒 data → memory high;對 noise / irrelevant 最弱)。NB 最怕 redundant(違反 independence)。SVM training 最慢但最 robust。

自我測驗 Self-test

Q1. 一個 node 有 class 分佈 (C1=4,C2=6)(C_1 = 4, C_2 = 6)。計 Gini、Entropy、Classification error。

p=0.4,0.6p = 0.4, 0.6。Gini=1−0.16−0.36=\text{Gini} = 1 - 0.16 - 0.36 = 0.48;Entropy=−0.4log⁡20.4−0.6log⁡20.6=0.529+0.442=\text{Entropy} = -0.4 \log_2 0.4 - 0.6 \log_2 0.6 = 0.529 + 0.442 = 0.971;Error=1−0.6=\text{Error} = 1 - 0.6 = 0.4。

Q2. Parent node (C0=10,C1=10)(C_0 = 10, C_1 = 10)。Split A 得 children (C0=7,C1=3)(C_0 = 7, C_1 = 3) 同 (C0=3,C1=7)(C_0 = 3, C_1 = 7);Split B 得 (C0=10,C1=4)(C_0 = 10, C_1 = 4) 同 (C0=0,C1=6)(C_0 = 0, C_1 = 6)。用 Gini 揀邊個 split 較好?

P=0.5P = 0.5。
Split A:每個 child Gini=1−0.49−0.09=0.42\text{Gini} = 1 - 0.49 - 0.09 = 0.42;M=0.5(0.42)+0.5(0.42)=0.42M = 0.5(0.42) + 0.5(0.42) = 0.42;Gain=0.08\text{Gain} = 0.08。
Split B:child1 (10, 4):Gini=1−(10/14)2−(4/14)2=1−0.510−0.082=0.408\text{Gini} = 1 - (10/14)^2 - (4/14)^2 = 1 - 0.510 - 0.082 = 0.408;child2 pure = 0;M=(14/20)(0.408)=0.286M = (14/20)(0.408) = 0.286;Gain=\text{Gain} = 0.214。
→ Split B 較好。

Q3. 用 entropy 計 Q2 Split B 嘅 information gain。

Parent entropy = 1。Child1 (10/14, 4/14):−0.714log⁡20.714−0.286log⁡20.286=0.347+0.516=0.863-0.714 \log_2 0.714 - 0.286 \log_2 0.286 = 0.347 + 0.516 = 0.863;child2 = 0。M=0.7×0.863=0.604M = 0.7 \times 0.863 = 0.604。IG=1−0.604=IG = 1 - 0.604 = 0.396。

Q4. 點解 decision tree 嘅 decision boundaries 係 axis-parallel?有咩後果?

因為每個 internal node 只 test 一個 attribute(例如 x1<5x_1 < 5),所以每條 boundary 都垂直於某條軸。如果真正 boundary 係斜線或者 class 取決於 attributes 之間嘅 interaction,tree 要用大量 splits 去近似(樓梯形),容易變得複雜同 overfit(slides 36–38)。

Q5. KNN 中 kk 太細同太大各有咩問題?點解要 scale attributes?

kk 太細 → 對 noise points 敏感;kk 太大 → neighborhood 會包含其他 class 嘅點。要 scale 係因為 attributes 範圍唔同(例如 income $10K–$1M vs height 1.5–1.8m),唔 scale 嘅話 distance 被範圍最大嘅 attribute 主導。

Q6. 用本頁稅務 data,用 Naïve Bayes 分類 X=(Refund=No,Married,Income=120K)X = (\text{Refund} = \text{No}, \text{Married}, \text{Income} = 120\text{K})。

P(X∣No)=P(Refund=No∣No)×P(Married∣No)×P(120∣No)=4/7×4/7×0.0072=0.00235P(X \mid \text{No}) = P(\text{Refund}=\text{No} \mid \text{No}) \times P(\text{Married} \mid \text{No}) \times P(120 \mid \text{No}) = 4/7 \times 4/7 \times 0.0072 = 0.00235;×P(No) 0.7=1.6×10−3\times P(\text{No})\ 0.7 = 1.6 \times 10^{-3}。
P(X∣Yes)=1×P(Married∣Yes)×⋯=1×P(X \mid \text{Yes}) = 1 \times P(\text{Married} \mid \text{Yes}) \times \dots = 1 \times 0/3 ×⋯=\times \dots = 0。
→ 分類為 No。留意 P(Married∣Yes)=0P(\text{Married} \mid \text{Yes}) = 0 令 Yes 嘅概率直接變 0——就係 zero-probability issue,可用 Laplace smoothing 修正。

Q7. 「Naïve」指咩假設?舉一個 conditional independence 例子。邊類 attributes 會令佢失效?

假設 given class 時 attributes 互相 conditionally independent:P(X1…Xd∣Y)=∏P(Xi∣Y)P(X_1 \ldots X_d \mid Y) = \prod P(X_i \mid Y)。例:arm length 同 reading skills 係 conditionally independent given age。Redundant / correlated attributes 會違反呢個假設(slide 67)。

Q8. SVM 點解要 maximize margin?寫出 optimization problem。邊啲點決定 decision boundary?

Margin 大 → generalization 較好、對 noise 更 robust、減少 overfitting。Problem:minimize ∥w∥2/2\|w\|^2/2 subject to yi(w⋅xi+b)≥1y_i(w\cdot x_i + b) \ge 1 for all ii(等價於 maximize 2/∥w∥2/\|w\|)。用 Lagrange multipliers 解;decision boundary 只取決於 support vectors(λi>0\lambda_i > 0 嘅點)。

Q9. 一個 linear SVM 有 w=(2,−1)w = (2, -1)、b=1b = 1。分類 x=(1,4)x = (1, 4) 同 x=(0,0)x = (0, 0),並計 margin。

(1, 4):2−4+1=−1<02 - 4 + 1 = -1 < 0 → −1。(0, 0):0+0+1=1≥00 + 0 + 1 = 1 \ge 0 → +1。Margin=2/∥w∥=2/5=\text{Margin} = 2/\|w\| = 2/\sqrt{5} = 0.894。

Q10. 邊個 classifier:(a) prediction 最慢 (b) training 最慢 (c) 對 redundant attributes 最差 (d) 係 lazy learner?

(a) KNN (b) SVM (c) Naïve Bayes(very poor)(d) KNN(Instance, Lazy)。

一頁總結 Cheat sheet

⭐ 考前速記
  • Classification:record (x,y)(x, y);learn model x→x \to predefined yy;training set 建 model,test set 量 accuracy。
  • Decision tree:root → internal (attribute test) → leaf (class);分類只行一條路徑。Algorithms:Hunt's、CART、ID3/C4.5、SLIQ/SPRINT。
  • Hunt's:DtD_t 同一 class → leaf;否則用 attribute test split,recursive。
  • Test conditions:nominal(multi-way / binary subsets)、ordinal(binary 要保持 order)、continuous(discretize static/dynamic,或 binary A<vA < v,試所有 cuts)。
  • Impurity:Gini=1−∑p2\text{Gini} = 1 - \sum p^2(max 0.5 for 2-class);Entropy=−∑plog⁡2p\text{Entropy} = -\sum p \log_2 p(max 1);Error=1−max⁡p\text{Error} = 1 - \max p(max 0.5)。
  • Gain=P−M\text{Gain} = P - M,M=∑(nj/n) I(childj)M = \sum (n_j/n)\, I(\text{child}_j);揀 gain 最大 / MM 最細。Entropy 版 = Information Gain。
  • 例:Gini parent 0.42;Refund M 0.343;Marital M 0.300;Income ≤97.5\le 97.5 M 0.300。
  • Stop:same class / identical attributes / early termination;pre-pruning、post-pruning。
  • DT 優:平、快、易解釋(細 tree)、robust to noise、handle redundant / irrelevant;缺:greedy 未必最佳、唔考慮 interactions、boundary 只涉及單一 attribute(axis-parallel)。
  • KNN:labeled records + distance metric + kk;majority vote 或 w=1/d2w = 1/d^2;kk 細 → noise 敏感,kk 大 → 包含其他 class;要 scale(z-score);local、任意形狀 boundary;irrelevant 加 noise、redundant 加 bias;missing values 令 proximities 不可比。
  • Naïve Bayes:MAP → max⁡P(X∣Y)P(Y)\max P(X \mid Y)P(Y);conditional independence → ∏P(Xi∣Y)\prod P(X_i \mid Y);categorical = nc/nn_c/n;continuous = discretize 或 Gaussian(μ\mu, σ2\sigma^2 用 sample 估);zero probability 問題(Laplace (nc+1)/(n+c)(n_c+1)/(n+c));robust to noise / irrelevant,missing 可忽略,redundant 違反假設。
  • SVM:max margin 2/∥w∥2/\|w\| ⇔ min ∥w∥2/2\|w\|^2/2 s.t. yi(w⋅xi+b)≥1y_i(w\cdot x_i+b) \ge 1;Lagrange multipliers;boundary 只靠 support vectors;predict sign(w⋅x+b)\text{sign}(w\cdot x+b);slack ξi\xi_i + C∑ξikC \sum \xi_i^k;convex → global optimum;training 慢;robust;handle irrelevant / redundant;難處理 missing。
  • Summary:DT Tree/Eager;KNN Instance/Lazy;NB Probabilistic/Eager;SVM Geometric/Eager。