# 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.