File size: 15,263 Bytes
3bbfd14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# Chương 5: Thuật toán Khai thác Dữ liệu Cốt lõi
## Core Data Mining Algorithms

---

## 📚 Mục tiêu học tập (CLO3, CLO4, CLO5, CLO7, CLO8)

Sau khi hoàn thành chương này, sinh viên có thể:
- Implement thuật toán Apriori và FP-Growth cho Association Rules
- Xây dựng Decision Tree (ID3, C4.5) cho bài toán Classification
- Áp dụng Naive Bayes cho phân loại văn bản/dữ liệu
- Thực hiện K-Means và K-Medoids cho Clustering
- Sử dụng DBSCAN cho density-based clustering
- Phân tích outlier bằng phương pháp thống kê và khoảng cách

---

## 5.1. Khai thác Luật kết hợp (Association Rules)

### Các khái niệm cơ bản

```
    Transaction Database:
    TID  | Items
    ─────┼──────────────────────
    T1   | {Bread, Milk, Butter}
    T2   | {Bread, Milk}
    T3   | {Milk, Eggs}
    T4   | {Bread, Milk, Eggs}
    T5   | {Bread, Butter}
    
    Itemset: Tập các items (VD: {Bread, Milk})
    
    Support(X) = P(X) = count(X) / N
    VD: Support({Bread, Milk}) = 3/5 = 0.6 (60%)
    
    Confidence(X → Y) = P(Y|X) = Support(X∪Y) / Support(X)
    VD: Confidence({Bread} → {Milk}) = Support({Bread,Milk}) / Support({Bread})
                                      = 3/5 / 4/5 = 0.75 (75%)
    
    Lift(X → Y) = Confidence(X→Y) / Support(Y)
    VD: Lift({Bread}→{Milk}) = 0.75 / 0.8 = 0.9375
    
    Lift > 1: X và Y có quan hệ positive
    Lift = 1: X và Y independent
    Lift < 1: X và Y có quan hệ negative
```

---

## 5.2. Thuật toán Apriori

### Nguyên lý Apriori

> **Nếu một itemset không frequent, thì mọi superset của nó cũng không frequent.**
> 
> Ngược lại: mọi subset của frequent itemset đều phải frequent.

```
    Apriori Algorithm (min_support = 0.4):
    
    Bước 1: Frequent 1-itemsets (C1 → L1)
    ┌──────────┬──────────┬─────────┐
    │ Itemset  │ Support  │ Frequent│
    ├──────────┼──────────┼─────────┤
    │ {Bread}  │ 4/5=0.80 │ ✅      │
    │ {Milk}   │ 4/5=0.80 │ ✅      │
    │ {Butter} │ 2/5=0.40 │ ✅      │
    │ {Eggs}   │ 2/5=0.40 │ ✅      │
    └──────────┴──────────┴─────────┘
    
    Bước 2: Generate candidates C2 từ L1, scan DB
    ┌────────────────┬──────────┬─────────┐
    │ Itemset        │ Support  │ Frequent│
    ├────────────────┼──────────┼─────────┤
    │ {Bread, Milk}  │ 3/5=0.60 │ ✅      │
    │ {Bread,Butter} │ 2/5=0.40 │ ✅      │
    │ {Bread, Eggs}  │ 1/5=0.20 │ ❌ prune│
    │ {Milk, Butter} │ 1/5=0.20 │ ❌ prune│
    │ {Milk, Eggs}   │ 2/5=0.40 │ ✅      │
    │ {Butter, Eggs} │ 0/5=0.00 │ ❌ prune│
    └────────────────┴──────────┴─────────┘
    
    Bước 3: C3 từ L2 → {Bread, Milk, Butter}? 
    Check subsets: {Bread,Butter}✅ {Milk,Butter}❌ → Prune!
    → L3 = ∅ → STOP
    
    Kết quả Frequent Itemsets:
    L1: {Bread}, {Milk}, {Butter}, {Eggs}
    L2: {Bread,Milk}, {Bread,Butter}, {Milk,Eggs}
```

### FP-Growth (cải tiến Apriori)

```
    FP-Growth vs Apriori:
    
    Apriori:                    FP-Growth:
    - Scan DB nhiều lần         - Scan DB chỉ 2 lần
    - Generate candidates       - KHÔNG generate candidates
    - Chậm với large DB         - Nhanh hơn nhiều
    - Dễ hiểu                   - Phức tạp hơn
    
    FP-Growth xây dựng FP-Tree (compact representation)
    rồi mine frequent patterns trực tiếp từ tree.
```

---

## 5.3. Classification: Decision Trees

### Information Gain và Entropy

```
    Entropy(S) = -Σ p_i * log2(p_i)
    
    VD: Dataset có 9 positive, 5 negative
    Entropy = -9/14 * log2(9/14) - 5/14 * log2(5/14) = 0.940
    
    Information Gain(S, A) = Entropy(S) - Σ |Sv|/|S| * Entropy(Sv)
    
    Chọn attribute có Information Gain cao nhất để split!
```

### ID3 Algorithm

```
    ID3 Decision Tree cho Olist (đơn giản hóa):
    
    Target: Is customer satisfied? (review_score >= 4)
    
                    ┌──────────────┐
                    │delivery_days │
                    │  IG = 0.32   │
                    └──────┬───────┘

               ┌───────────┼───────────┐
               │           │           │
           ≤ 7 days    8-14 days    > 14 days
               │           │           │
          ┌────▼────┐ ┌────▼────┐ ┌────▼────┐
          │ price   │ │Satisfied│ │  NOT    │
          │IG=0.15  │ │  (68%)  │ │Satisfied│
          └────┬────┘ └─────────┘ │  (82%)  │
               │                  └─────────┘
          ┌────┼────┐
          │         │
       ≤ 200     > 200
          │         │
     ┌────▼────┐ ┌──▼──────┐
     │Satisfied│ │ Check   │
     │  (90%)  │ │ freight │
     └─────────┘ └─────────┘
    
    ID3: Chỉ dùng categorical (discretize nếu cần)
    C4.5: Hỗ trợ continuous attributes, handling missing values
```

### C4.5 Improvements over ID3

| Feature | ID3 | C4.5 |
|---------|-----|------|
| Attributes | Categorical only | Categorical + Continuous |
| Missing values | Not handled | Uses probability weighting |
| Overfitting | Not addressed | Post-pruning (error-based) |
| Splitting criterion | Information Gain | **Gain Ratio** = IG / SplitInfo |
| Multi-way split | Yes | Yes + Binary split for continuous |

```
    Gain Ratio = Information_Gain(A) / SplitInformation(A)
    
    SplitInfo(A) = -Σ |Sv|/|S| * log2(|Sv|/|S|)
    
    → Penalize attributes with many values (fix IG bias)
```

---

## 5.4. Naive Bayes Classification

### Bayes' Theorem

```
    P(C|X) = P(X|C) * P(C) / P(X)
    
    Posterior = Likelihood × Prior / Evidence
    
    Naive assumption: features are conditionally independent
    P(X|C) = P(x1|C) × P(x2|C) × ... × P(xn|C)
    
    Ví dụ: Predict review_score ≥ 4 (satisfied)
    
    Given: delivery_days=5, price=150, state=SP
    
    P(satisfied | features) ∝ P(delivery=5|sat) × P(price=150|sat) × P(SP|sat) × P(sat)
    P(unsatisfied | features) ∝ P(delivery=5|unsat) × P(price=150|unsat) × P(SP|unsat) × P(unsat)
    
    Chọn class có probability cao hơn.
```

### Types of Naive Bayes

| Type | Use case | P(x|C) |
|------|----------|--------|
| **Gaussian NB** | Continuous features | Normal distribution |
| **Multinomial NB** | Text/Count data | Multinomial distribution |
| **Bernoulli NB** | Binary features | Bernoulli distribution |
| **Complement NB** | Imbalanced text | Complement of class |

---

## 5.5. K-Means Clustering

### Algorithm

```
    K-Means Algorithm:
    
    Input: K (số clusters), Data points
    
    1. Khởi tạo K centroids (random hoặc K-Means++)
    2. REPEAT:
       a. ASSIGN: Gán mỗi point vào cluster có centroid gần nhất
       b. UPDATE: Tính lại centroid = mean of all points trong cluster
    3. UNTIL centroids không đổi (hoặc max iterations)
    
    Iteration 0:          Iteration 1:          Converged:
    ┌──────────────┐     ┌──────────────┐     ┌──────────────┐
    │  *           │     │  * . .       │     │  * . .       │
    │     . .  C1  │     │     . C1     │     │    .C1 .     │
    │  .  .  .     │     │  . . .       │     │  . . .       │
    │     C2       │     │              │     │              │
    │  . .   . .   │     │  . .  C2. .  │     │  . . C2. .   │
    │        . .   │     │        . .   │     │        . .   │
    └──────────────┘     └──────────────┘     └──────────────┘
    C = Centroid, . = Data point
```

### K-Means++: Khởi tạo thông minh

```
    K-Means++ (Arthur & Vassilvitskii, 2007):
    
    1. Chọn centroid đầu tiên random
    2. Cho mỗi centroid tiếp theo:
       - Tính D(x) = khoảng cách từ x đến centroid gần nhất
       - Chọn point mới với xác suất ∝ D(x)²
       → Centroids xa nhau → converge nhanh hơn
```

### Chọn K tối ưu

```
    Elbow Method:                    Silhouette Method:
    
    Inertia                          Silhouette Score
    │                                │
    │\                               │        *
    │ \                              │   *         *
    │  \                             │ *               *
    │   \                            │*                    *
    │    \_____                      │
    │     ↑                          │
    │   Elbow                        │
    │         \_____                 │
    └─────────────── K               └─────────────── K
    
    K* = point where adding                K* = max silhouette
    more clusters gives                    s(i) = (b(i)-a(i)) / max(a(i),b(i))
    diminishing returns                    a(i) = avg distance to same cluster
                                           b(i) = avg distance to nearest other cluster
```

---

## 5.6. DBSCAN (Density-Based Clustering)

### Nguyên lý hoạt động

```
    DBSCAN Parameters:
    - ε (epsilon): Bán kính neighborhood
    - MinPts: Số điểm tối thiểu trong ε-neighborhood
    
    3 loại điểm:
    ┌──────────────────────────────────────┐
    │                                      │
    │   Core Point (≥ MinPts trong ε)      │
    │   ┌─────┐                            │
    │   │  ●──┼──. . .  (≥5 points)       │
    │   │  ε  │                            │
    │   └─────┘                            │
    │                                      │
    │   Border Point (< MinPts nhưng       │
    │   trong ε của Core Point)            │
    │        ○ ← border                   │
    │        ↓                             │
    │   ┌─────┐                            │
    │   │  ●  │  core                      │
    │   └─────┘                            │
    │                                      │
    │   Noise Point (không thuộc cluster)   │
    │        ✕ ← noise/outlier            │
    │                                      │
    └──────────────────────────────────────┘
    
    DBSCAN Algorithm:
    1. Cho mỗi point chưa visited:
       a. Đánh dấu visited
       b. Tìm ε-neighborhood
       c. Nếu ≥ MinPts → Core point → Tạo/mở rộng cluster
       d. Nếu < MinPts → Tạm đánh dấu noise (có thể thành border sau)
    
    DBSCAN vs K-Means:
    ┌────────────────┬─────────────┬──────────────┐
    │ Feature        │ K-Means     │ DBSCAN       │
    ├────────────────┼─────────────┼──────────────┤
    │ # Clusters     │ Phải chỉ K  │ Tự phát hiện │
    │ Cluster shape  │ Spherical   │ Arbitrary    │
    │ Outlier handle │ Không       │ Có (noise)   │
    │ Scalability    │ O(nKt)      │ O(n²) worst  │
    │ Parameters     │ K           │ ε, MinPts    │
    └────────────────┴─────────────┴──────────────┘
```

---

## 5.7. Phân cụm Phân cấp (Hierarchical Clustering)

```
    Agglomerative (Bottom-up):
    
    Start: Mỗi point = 1 cluster
    
    Step 1: {A}{B}{C}{D}{E}     Merge closest: A,B
    Step 2: {A,B}{C}{D}{E}      Merge closest: D,E
    Step 3: {A,B}{C}{D,E}       Merge closest: C,{D,E}
    Step 4: {A,B}{C,D,E}        Merge closest: {A,B},{C,D,E}
    Step 5: {A,B,C,D,E}         Done!
    
    Dendrogram:
    ─────────────────────────
    │           ┌───────────┤
    │     ┌─────┤           │
    │     │     │    ┌──────┤
    │  ┌──┤     │    │  ┌───┤
    ─  A  B     C    D  E
    
    Linkage Methods:
    - Single: min distance between clusters
    - Complete: max distance  
    - Average: mean distance (UPGMA)
    - Ward's: minimize variance increase
```

---

## 5.8. Outlier Detection

### Phương pháp phát hiện Outlier

| Method | Type | Mô tả |
|--------|------|-------|
| **Z-Score** | Statistical | \|z\| > 3 → outlier |
| **Modified Z-Score** | Statistical (robust) | Uses MAD instead of std |
| **IQR** | Statistical | < Q1-1.5IQR or > Q3+1.5IQR |
| **Isolation Forest** | ML-based | Random splits, outliers isolated faster |
| **LOF** | Distance-based | Local Outlier Factor, density-based |
| **DBSCAN noise** | Density-based | Points classified as noise |
| **Mahalanobis Distance** | Statistical | Accounts for correlation |

---

## 🔬 Labs

- [`lab-05-apriori.py`](lab-05-apriori.py) — Apriori & FP-Growth trên Olist
- [`lab-05-decision-tree.py`](lab-05-decision-tree.py) — Decision Tree Classification
- [`lab-05-naive-bayes.py`](lab-05-naive-bayes.py) — Naive Bayes Classification
- [`lab-05-kmeans.py`](lab-05-kmeans.py) — K-Means Customer Segmentation
- [`lab-05-dbscan.py`](lab-05-dbscan.py) — DBSCAN Anomaly Detection

---

## 📝 Câu hỏi ôn tập

1. Tính Support, Confidence và Lift cho rule {A} → {B} biết: N=100, count(A)=40, count(B)=50, count(A∪B)=25
2. Giải thích nguyên lý Apriori. Tại sao nó giúp giảm số lượng candidates?
3. So sánh Information Gain (ID3) và Gain Ratio (C4.5). Tại sao Gain Ratio tốt hơn?
4. K-Means có nhược điểm gì? K-Means++ cải thiện như thế nào?
5. DBSCAN phát hiện outlier như thế nào? So sánh với K-Means về handling outliers.
6. Cho dataset: [1,2,3,100,2,3,1,2,500]. Dùng IQR method, xác định outliers.