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 → class label ),理解 training set / test set 同建 model 嘅一般流程。
- 理解 Decision Tree 點樣分類、Hunt's Algorithm、各類 attributes 嘅 test conditions,並識計 Gini、Entropy、Misclassification error 同 Gain 去揀 best split。
- 掌握 K-Nearest Neighbor:三個要素、分類步驟、 嘅選擇、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
- Gini / Entropy / Error 公式同計算;(weighted child impurity);用嚟揀 split(包括 continuous attribute 揀 cut point)。
- Naïve Bayes 完整計算(Refund = No, Divorced, Income = 120K 例子),包括 Gaussian density 同 嘅問題。
- KNN:k 太細 / 太大嘅後果、點解要 scale attributes、weight factor 。
- SVM:maximize margin ⇔ minimize ,constraints ;decision boundary 只取決於 support vectors。
- 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 描述:
- :attribute set(又叫 attribute、predictor、independent variable、input)
- :class label(又叫 class、response、dependent variable、output)
Task:Learn a model that maps each attribute set into one of the predefined class labels ,即將 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, | Class label, |
|---|---|---|
| Categorizing email messages | Features extracted from email message header and content | spam or non-spam |
| Identifying tumor cells | Features extracted from x-rays or MRI scans | malignant or benign cells |
| Cataloging galaxies | Features extracted from telescope images | Elliptical, 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 / test 表係圖片,請對照原 slide 第 6 頁。
COM6005 嘅 Logistic Regression 都係 classification model(predict probability of class);Chapter 1 已介紹 Classification 屬 Predictive task。COM6001 scikit-learn 嘅 train_test_split + fit()(induction)+ predict()(deduction)就係呢個流程。
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 稅務例子(attributes:Refund、Marital Status、Taxable Income;class:Evade / Cheat)。以下係教科書嘅數據同經典 tree(數字同 slide 58 文字 、、 完全吻合):
| Tid | Refund | Marital Status | Taxable Income | Evade |
|---|---|---|---|---|
| 1 | Yes | Single | 125K | No |
| 2 | No | Married | 100K | No |
| 3 | No | Single | 70K | No |
| 4 | Yes | Married | 120K | No |
| 5 | No | Divorced | 95K | Yes |
| 6 | No | Married | 60K | No |
| 7 | Yes | Divorced | 220K | No |
| 8 | No | Single | 85K | Yes |
| 9 | No | Married | 75K | No |
| 10 | No | Single | 90K | Yes |
Refund?
├── Yes → NO
└── No → MarSt?
├── Married → NO
└── Single, Divorced → TaxInc?
├── < 80K → NO
└── > 80K → YES
Slides 8–17 嘅 tree 圖同數據表全部係圖片。上面數據表同 tree 係教科書(Tan et al.)標準例子,同 slide 文字數字一致,但請對照原 slide 第 8–17 頁確認。
2.1 Apply Model to Test Data (Slides 10–17)
Slides 11–16 一步步示範:由 root 開始,按 test record 嘅 attribute 值沿住分支行,直到 leaf。例:test record (Refund = No, Marital Status = Married, Taxable Income = 80K, Evade = ?):
- Root:Refund = No → 行去 MarSt 節點
- MarSt = Married → 去到 leaf NO
- 結果:Assign Evade = "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。設 為到達 node 嘅 training records:
- 如果 入面所有 records 都屬同一 class ,咁 係 leaf node,label 為 。
- 如果 包含多過一個 class 嘅 records,就用一個 attribute test 將 data split 成較細嘅 subsets,然後對每個 subset recursively apply 同一程序。
(教科書補充:如果 係空集, 就係 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 嘅 Hunt's Algorithm 逐步 tree 圖係圖片;上面描述係根據教科書同前述數據重構,請對照原 slide。
4. Design Issues & Test Conditions
Slide 24–25:Decision tree induction 有兩大設計問題:
- 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)。
- 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 type | Multi-way split | Binary split |
|---|---|---|
| Nominal(例:Marital Status) | Use as many partitions as distinct values:{Single}, {Married}, {Divorced} | Divides values into two subsets,例:{Married} vs {Single, Divorced}。 個值有 種 binary splits。 |
| Ordinal(例:Shirt Size S/M/L/XL) | As many partitions as distinct values | Two subsets,但要 preserve order property:{S, M} vs {L, XL} ✓;{S, L} vs {M, XL} ✗(破壞次序) |
| Continuous(例:Taxable Income) | Discretize 成多個 ranges(例如 <10K, [10K,25K), [25K,50K), [50K,80K), ≥80K) | Binary decision: or |
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 or :考慮所有可能嘅 splits 搵 best cut;計算量可以較大。
Slides 26–28 嘅 split 示意圖(例如 Marital Status、Shirt Size、Taxable Income 嘅分支圖)係圖片;上表例子係教科書標準例子,請對照原 slide。
Equal interval / equal frequency / clustering discretization 正正係 Chapter 2 §11.6 Discretization 講嘅方法。
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)。
係 node 入面 class 嘅 frequency(比例), 係 classes 總數。
| 最細(pure node) | 最大(均勻分佈) | 2-class 最大 | |
|---|---|---|---|
| Gini | 0 | 0.5 | |
| Entropy | 0 | 1 | |
| Error | 0 | 0.5 |
Slide 32 嘅三條公式係圖片;上面係教科書標準形式(slide 文字 "where is the frequency of class i at node t, and c is the total number of classes" 與之吻合)。
5.1 Worked example:計單一 node 嘅 impurity
| Node (C1, C2) | p | Gini | Entropy | Error |
|---|---|---|---|---|
| (0, 6) | 0, 1 | 0 | 0 | 0 |
| (1, 5) | 1/6, 5/6 | 0.278 | 0.650 | 0.167 |
| (2, 4) | 2/6, 4/6 | 0.444 | 0.918 | 0.333 |
| (3, 3) | 0.5, 0.5 | 0.5 | 1 | 0.5 |
三個 measures 嘅排序一致(越 pure 越細),只係數值唔同。Entropy 對 impurity 最敏感。
5.2 Finding the Best Split (Slides 33–34)
- 計 splitting 前嘅 impurity measure (parent)。
- 計 splitting 後嘅 impurity measure :先計每個 child node 嘅 impurity, = child nodes 嘅 weighted impurity:
- 揀產生最高 gain 嘅 attribute test condition:
或等價地,揀 splitting 後 impurity 最低嘅。
用 entropy 計嘅 gain 叫 Information Gain。
5.3 Worked example:用 10-record data 揀 root split(Gini)
Parent:7 No、3 Yes →
(a) Refund:
- Refund = Yes:3 records(No 3, Yes 0)→
- Refund = No:7 records(No 4, Yes 3)→
- 0.343 → 0.077
(b) Marital Status(multi-way):
- Single:4 records(Tid 1, 3, 8, 10 → No 2, Yes 2)→
- Married:4 records(Tid 2, 4, 6, 9 → No 4)→
- Divorced:2 records(Tid 5 Yes, 7 No)→
- 0.300 → 0.120
(c) Marital Status(binary {Married} vs {Single, Divorced}):{S, D} 有 6 records(No 3, Yes 3)→ Gini 0.5 → 0.300(同 multi-way 一樣)。
(d) Taxable Income(continuous,binary split):先排序,再喺相鄰值中點試每個 cut:
| Sorted income | 60 | 70 | 75 | 85 | 90 | 95 | 100 | 120 | 125 | 220 |
|---|---|---|---|---|---|---|---|---|---|---|
| Class | No | No | No | Yes | Yes | Yes | No | No | No | No |
| Cut | (Yes, No) | (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 |
例::左 6 records Gini 0.5,右 4 records Gini 0 → 。
結論:Marital Status 同 Taxable Income () 都得 (Gain 0.12),好過 Refund()。
(1) 先 sort;(2) 只需要喺 class label 改變嘅相鄰位置試 cut(例如 75→85、95→100),其他位置唔會係最佳;(3) 由左至右掃描,逐步更新左右兩邊嘅 class counts,唔使每次重新數。
5.4 Worked example:Information Gain(Entropy)
Parent entropy:
- Refund:Refund = No (3 Yes, 4 No) ;;
- Marital Status:Single (2, 2) = 1;Married = 0;Divorced (1, 1) = 1;;
- Income :(3, 3) = 1;(0, 4) = 0;;
同 Gini 結論一致:Refund 最差。
- 計 時忘記用 child size 做 weight(直接平均 children impurity)。
- 用錯 base(用咗 或 )。計數機:。
- 以為 Gain 越細越好——Gain 越大越好(或 越細越好)。
- 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)。
| Advantages | Disadvantages |
|---|---|
|
|
Handling interactions (slide 37) 同 Limitations of single attribute-based decision boundaries (slide 38):因為每個 test 只用一個 attribute,decision boundaries 永遠平行於坐標軸(axis-parallel,好似樓梯級)。如果真正嘅 boundary 係斜線(例如 )或者 class 取決於兩個 attributes 嘅 interaction(例如 XOR 型),tree 就要好多層先近似到。
Slides 37–38 嘅散點圖同 decision boundaries 係圖片,請對照原 slide 第 37–38 頁。
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:
- The set of labeled records
- Distance metric to compute distance between records
- The value of , the number of nearest neighbors to retrieve
Slide 42:To classify an unknown record:
- Compute distance to other training records
- Identify nearest neighbors
- 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 。決定 class:
- Take the majority vote of class labels among the -nearest neighbors
- Weight the vote according to distance:weight factor
7.1 Worked example(自擬)
Training: A、 A、 A、 B、 B、 B。Test 。
| Point | Class | Euclidean distance to | Rank | |
|---|---|---|---|---|
| (4,4) | B | 0.609 | 1 | |
| (2,2) | A | 0.410 | 2 | |
| (3,1) | A | 0.248 | 3 | |
| (5,4) | B | 0.236 | 4 | |
| (1,1) | A | 0.113 | 5 | |
| (6,5) | B | 0.084 | 6 |
- :最近係 → B
- : (B)、 (A)、 (A) → majority A(2:1)
- , distance-weighted:; → A(好接近!)
- :B, A, A, B, A → A(3:2)
結論: 嘅選擇可以改變答案。
7.2 Choosing k & Proximity (Slides 44–45)
- If is too small, sensitive to noise points( 時一個 mislabeled 點就會誤導)。
- If is too large, neighborhood may include points from other classes(決策變得太「平均」,被大 class 主導)。
實務:用 cross-validation 揀 ;binary classification 用奇數 避免打和。
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 處理。
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。
將每個 attribute 同 class label 當 random variables。給定 record with attributes ,目標係預測 class :搵令 最大嘅 。
Slide 53 問:可唔可以直接由 data 估計 同 ?()——通常唔得,因為 training data 未必有完全相同 attribute 組合嘅 record。
ExamApproach (slide 54):用 Bayes theorem 計 posterior probability:
Maximum a-posteriori (MAP):揀令 最大嘅 。因為分母對所有 class 一樣,等價於揀令 最大嘅 。問題:點估計 ?
8.2 Naïve Bayes Assumption (Slide 56)
Exam假設 class 已知時 attributes 之間 conditional independence:
Example:Arm length and reading skills:細路仔手臂較短、閱讀能力有限(同成人比)→ 兩者表面上相關;但如果 age 固定,arm length 同 reading skills 冇明顯關係 → 佢哋係 conditionally independent given age。
咁就可以由 training data 估計每個 。新點分類到令 最大嘅 。
8.3 Estimate Probabilities from Data (Slides 58–60)
- Class prior: = fraction of instances of class 。例:,。
- Categorical attributes:, = 屬於 class 而 attribute value 為 嘅 instances 數, = 屬於 class 嘅 instances 數。例:、。
- 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。
Slide 60 嘅 Gaussian 公式同計算例子、slides 61–63 嘅完整 Naïve Bayes 計算係圖片;下面 worked example 係根據教科書同上述數據計算,請對照原 slide。
8.4 Worked example:X = (Refund = No, Divorced, Income = 120K)
Step 1 — Priors:,。
Step 2 — Categorical conditionals(由數據表數):
- Class No(7 records:Tid 1, 2, 3, 4, 6, 7, 9):Refund = No 有 Tid 2, 3, 6, 9 → 4/7;Divorced 只有 Tid 7 → 1/7。
- Class Yes(3 records:Tid 5, 8, 10):Refund 全部 No → 1;Divorced 有 Tid 5 → 1/3。
Step 3 — Income(Gaussian):
- Class No incomes:125, 100, 70, 120, 60, 220, 75 → 110; 2975()。
- Class Yes incomes:95, 85, 90 → 90; 25()。
Step 4 — Likelihoods(slide 57 結構):
- 0.0006
Step 5 — 乘 prior 比較:;。
因為 → → 分類為 Evade = No。
- 忘記乘 prior 。
- Gaussian density 唔係 probability(可以大過 1),但喺比較中可以照用。
- Variance 用 sample variance(分母 ):Class No 嘅 ,÷ 6 = 2975。
8.5 Issues with Naïve Bayes (Slides 64–66)
由 slide 58 可見 。如果 test record 係 Refund = Yes,咁 成個乘積都會變 0——無論其他 attributes 幾支持 Yes 都冇用。如果某 record 對兩個 class 都有一個 conditional probability = 0,就完全分類唔到。
教科書嘅解決方法係用其他 probability estimates:
其中 = attribute 可取值嘅數目, = 初始估計 (prior) 概率, = parameter。例:Laplace 下 0.2(唔再係 0)。
Slides 64–66 "Issues with Naïve Bayes Classifier" 全部係圖片,文字擷取不到;上面 zero-probability 問題同 Laplace / m-estimate 係根據教科書補充,請對照原 slide 確認 slide 實際涵蓋範圍。
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 嘅 對所有 class 差唔多,乘落去唔改變排序)
- Redundant and correlated attributes will violate class conditional independence assumption(同一資訊被乘兩次,過度影響結果)
COM6005 Module 2 probability:conditional probability、Bayes theorem、Normal distribution pdf 全部喺呢度用到。Gaussian likelihood 就係 Normal pdf 代入 嘅 sample estimates。
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 、 之間嘅闊度)。Margin 越大,對新 data 嘅 generalization 越好(對 noise 有更大緩衝)。
Slides 69–75 嘅 hyperplane 同 margin 示意圖係圖片,請對照原 slide。
9.2 Linear SVM (Slides 76–79)
Linear model:
Decision boundary:;兩條 margin hyperplanes:。Learning the model is equivalent to determining the values of and .
Objective is to maximize:
Which is equivalent to minimizing:
Subject to the following constraints:
呢個係 constrained optimization problem,用 Lagrange multiplier method 解。
Slides 76–79 嘅公式係圖片 / 嵌入物件;上面係教科書標準形式(slide 文字 "Objective is to maximize… equivalent to minimizing… subject to… or…" 與之對應)。Slide 78 嘅數值例子(data points 同 Lagrange multipliers 表)亦係圖片。
- Slide 78:Support vectors 係 Lagrange multipliers 嘅點(即剛好喺 margin 上嘅點;細節略過)。
- Slide 79:Decision boundary depends only on support vectors——如果另一個 data set 有相同 support vectors,decision boundary 唔會變(其他點移動或刪除都唔影響)。
- 搵到 、 之後點分類 test record ?
假設學到 、。
- Test : → +1(剛好喺 margin 上,可能係 support vector)
- Test : → −1
如果想 margin 更大,就要 更細——所以 minimize 。
9.3 Non-linearly Separable: Slack Variables (Slides 80–81)
如果問題唔係 linearly separable?引入 slack variables ,容許部分點越過 margin 甚至分錯:
If is 1 or 2, this leads to similar objective function as linear SVM but with different constraints。 控制「大 margin」同「少錯誤」之間嘅 trade-off( 大 → 少容忍錯誤)。
Slide 81 嘅公式係圖片;上面係教科書標準 soft-margin 形式,請對照原 slide 第 81 頁。
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 比較
| Decision Tree | KNN | Naïve Bayes | SVM | |
|---|---|---|---|---|
| Model | Tree, Eager | Instance, Lazy | Probabilistic, Eager | Geometric, Eager |
| Training speed | Fast to medium | Very fast | Very fast | Slow to very slow |
| Prediction speed | Very fast | Slow | Very fast | Fast |
| Memory usage | Low | High | Low | Medium |
| Robust to noise | Good | Poor | Moderate | Excellent |
| Irrelevant attribute | Good | Very poor | Moderate | Good |
| Redundant attribute | Good | Poor | Very poor | Excellent |
記憶法:KNN 係 lazy(training 唔做嘢 → very fast;prediction 要計晒距離 → slow;要存晒 data → memory high;對 noise / irrelevant 最弱)。NB 最怕 redundant(違反 independence)。SVM training 最慢但最 robust。
自我測驗 Self-test
Q1. 一個 node 有 class 分佈 。計 Gini、Entropy、Classification error。
。 0.48; 0.971; 0.4。
Q2. Parent node 。Split A 得 children 同 ;Split B 得 同 。用 Gini 揀邊個 split 較好?
。
Split A:每個 child ;;。
Split B:child1 (10, 4):;child2 pure = 0;; 0.214。
→ Split B 較好。
Q3. 用 entropy 計 Q2 Split B 嘅 information gain。
Parent entropy = 1。Child1 (10/14, 4/14):;child2 = 0。。 0.396。
Q4. 點解 decision tree 嘅 decision boundaries 係 axis-parallel?有咩後果?
因為每個 internal node 只 test 一個 attribute(例如 ),所以每條 boundary 都垂直於某條軸。如果真正 boundary 係斜線或者 class 取決於 attributes 之間嘅 interaction,tree 要用大量 splits 去近似(樓梯形),容易變得複雜同 overfit(slides 36–38)。
Q5. KNN 中 太細同太大各有咩問題?點解要 scale attributes?
太細 → 對 noise points 敏感; 太大 → neighborhood 會包含其他 class 嘅點。要 scale 係因為 attributes 範圍唔同(例如 income $10K–$1M vs height 1.5–1.8m),唔 scale 嘅話 distance 被範圍最大嘅 attribute 主導。
Q6. 用本頁稅務 data,用 Naïve Bayes 分類 。
;。
0/3 0。
→ 分類為 No。留意 令 Yes 嘅概率直接變 0——就係 zero-probability issue,可用 Laplace smoothing 修正。
Q7. 「Naïve」指咩假設?舉一個 conditional independence 例子。邊類 attributes 會令佢失效?
假設 given class 時 attributes 互相 conditionally independent:。例: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 subject to for all (等價於 maximize )。用 Lagrange multipliers 解;decision boundary 只取決於 support vectors( 嘅點)。
Q9. 一個 linear SVM 有 、。分類 同 ,並計 margin。
(1, 4): → −1。(0, 0): → +1。 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 ;learn model predefined ;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: 同一 class → leaf;否則用 attribute test split,recursive。
- Test conditions:nominal(multi-way / binary subsets)、ordinal(binary 要保持 order)、continuous(discretize static/dynamic,或 binary ,試所有 cuts)。
- Impurity:(max 0.5 for 2-class);(max 1);(max 0.5)。
- ,;揀 gain 最大 / 最細。Entropy 版 = Information Gain。
- 例:Gini parent 0.42;Refund M 0.343;Marital M 0.300;Income 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 + ;majority vote 或 ; 細 → noise 敏感, 大 → 包含其他 class;要 scale(z-score);local、任意形狀 boundary;irrelevant 加 noise、redundant 加 bias;missing values 令 proximities 不可比。
- Naïve Bayes:MAP → ;conditional independence → ;categorical = ;continuous = discretize 或 Gaussian(, 用 sample 估);zero probability 問題(Laplace );robust to noise / irrelevant,missing 可忽略,redundant 違反假設。
- SVM:max margin ⇔ min s.t. ;Lagrange multipliers;boundary 只靠 support vectors;predict ;slack + ;convex → global optimum;training 慢;robust;handle irrelevant / redundant;難處理 missing。
- Summary:DT Tree/Eager;KNN Instance/Lazy;NB Probabilistic/Eager;SVM Geometric/Eager。