thanhtai435 commited on
Commit
08f115c
·
verified ·
1 Parent(s): 9bc2cea

Add chapter-05-data-mining/lab-05-data-mining.py

Browse files
chapter-05-data-mining/lab-05-data-mining.py ADDED
@@ -0,0 +1,731 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Lab 5: Data Mining Algorithms
3
+ ==============================
4
+ BIM5021 - Nhà kho dữ liệu và Tích hợp
5
+ Chương 5: Thuật toán khai thác dữ liệu cốt lõi
6
+
7
+ Mục tiêu:
8
+ - Implement Apriori từ đầu (from scratch)
9
+ - Association Rules mining trên Olist order items
10
+ - Decision Tree (ID3-style) với scikit-learn
11
+ - K-Means Customer Segmentation (RFM)
12
+ - DBSCAN Anomaly Detection
13
+ - Naive Bayes cho review prediction
14
+
15
+ Yêu cầu: pip install pandas numpy scikit-learn matplotlib mlxtend
16
+ """
17
+
18
+ import pandas as pd
19
+ import numpy as np
20
+ import matplotlib
21
+ matplotlib.use('Agg')
22
+ import matplotlib.pyplot as plt
23
+ from collections import defaultdict
24
+ from itertools import combinations
25
+ import warnings
26
+ warnings.filterwarnings('ignore')
27
+
28
+
29
+ # ==============================================================================
30
+ # PHẦN 1: APRIORI ALGORITHM (From Scratch!)
31
+ # ==============================================================================
32
+
33
+ class AprioriFromScratch:
34
+ """
35
+ Implementation Apriori algorithm từ đầu.
36
+ Tham khảo: Agrawal & Srikant, 1994
37
+ """
38
+
39
+ def __init__(self, min_support: float = 0.01, min_confidence: float = 0.5):
40
+ self.min_support = min_support
41
+ self.min_confidence = min_confidence
42
+ self.frequent_itemsets = {}
43
+ self.rules = []
44
+
45
+ def _get_support(self, itemset: frozenset, transactions: list) -> float:
46
+ """Tính support của 1 itemset."""
47
+ count = sum(1 for t in transactions if itemset.issubset(t))
48
+ return count / len(transactions)
49
+
50
+ def _get_frequent_1_itemsets(self, transactions: list) -> dict:
51
+ """Tìm tất cả frequent 1-itemsets."""
52
+ item_counts = defaultdict(int)
53
+ for t in transactions:
54
+ for item in t:
55
+ item_counts[frozenset([item])] += 1
56
+
57
+ n = len(transactions)
58
+ return {
59
+ itemset: count / n
60
+ for itemset, count in item_counts.items()
61
+ if count / n >= self.min_support
62
+ }
63
+
64
+ def _generate_candidates(self, prev_frequent: dict, k: int) -> set:
65
+ """Generate candidate k-itemsets từ (k-1)-itemsets."""
66
+ items = list(prev_frequent.keys())
67
+ candidates = set()
68
+
69
+ for i in range(len(items)):
70
+ for j in range(i + 1, len(items)):
71
+ # Union of two (k-1)-itemsets
72
+ candidate = items[i] | items[j]
73
+ if len(candidate) == k:
74
+ # Apriori pruning: check all (k-1) subsets are frequent
75
+ all_subsets_frequent = True
76
+ for item in candidate:
77
+ subset = candidate - frozenset([item])
78
+ if subset not in prev_frequent:
79
+ all_subsets_frequent = False
80
+ break
81
+
82
+ if all_subsets_frequent:
83
+ candidates.add(candidate)
84
+
85
+ return candidates
86
+
87
+ def fit(self, transactions: list):
88
+ """Chạy thuật toán Apriori."""
89
+ print(f"\n [APRIORI] min_support={self.min_support}, "
90
+ f"min_confidence={self.min_confidence}")
91
+ print(f" [APRIORI] {len(transactions)} transactions")
92
+
93
+ # Step 1: L1
94
+ L1 = self._get_frequent_1_itemsets(transactions)
95
+ self.frequent_itemsets[1] = L1
96
+ print(f" [L1] {len(L1)} frequent 1-itemsets")
97
+
98
+ # Step 2: Iterate k = 2, 3, ...
99
+ k = 2
100
+ prev_frequent = L1
101
+
102
+ while prev_frequent:
103
+ # Generate candidates
104
+ candidates = self._generate_candidates(prev_frequent, k)
105
+
106
+ if not candidates:
107
+ break
108
+
109
+ # Count support for candidates
110
+ Lk = {}
111
+ for candidate in candidates:
112
+ support = self._get_support(candidate, transactions)
113
+ if support >= self.min_support:
114
+ Lk[candidate] = support
115
+
116
+ if Lk:
117
+ self.frequent_itemsets[k] = Lk
118
+ print(f" [L{k}] {len(Lk)} frequent {k}-itemsets "
119
+ f"(from {len(candidates)} candidates)")
120
+
121
+ prev_frequent = Lk
122
+ k += 1
123
+
124
+ # Generate rules
125
+ self._generate_rules(transactions)
126
+
127
+ return self
128
+
129
+ def _generate_rules(self, transactions: list):
130
+ """Generate association rules từ frequent itemsets."""
131
+ self.rules = []
132
+
133
+ for k in range(2, max(self.frequent_itemsets.keys()) + 1):
134
+ if k not in self.frequent_itemsets:
135
+ continue
136
+
137
+ for itemset, support in self.frequent_itemsets[k].items():
138
+ # Generate all non-empty proper subsets
139
+ items = list(itemset)
140
+ for i in range(1, len(items)):
141
+ for antecedent_items in combinations(items, i):
142
+ antecedent = frozenset(antecedent_items)
143
+ consequent = itemset - antecedent
144
+
145
+ # Find antecedent support
146
+ ant_support = None
147
+ ant_k = len(antecedent)
148
+ if ant_k in self.frequent_itemsets:
149
+ ant_support = self.frequent_itemsets[ant_k].get(antecedent)
150
+
151
+ if ant_support is None or ant_support == 0:
152
+ continue
153
+
154
+ confidence = support / ant_support
155
+
156
+ if confidence >= self.min_confidence:
157
+ # Calculate lift
158
+ cons_k = len(consequent)
159
+ cons_support = self.frequent_itemsets.get(cons_k, {}).get(
160
+ consequent, 0
161
+ )
162
+ lift = confidence / cons_support if cons_support > 0 else 0
163
+
164
+ self.rules.append({
165
+ 'antecedent': antecedent,
166
+ 'consequent': consequent,
167
+ 'support': round(support, 4),
168
+ 'confidence': round(confidence, 4),
169
+ 'lift': round(lift, 4),
170
+ })
171
+
172
+ # Sort by lift
173
+ self.rules.sort(key=lambda x: x['lift'], reverse=True)
174
+ print(f" [RULES] {len(self.rules)} rules generated "
175
+ f"(confidence >= {self.min_confidence})")
176
+
177
+ def print_rules(self, top_n: int = 10):
178
+ """In top rules."""
179
+ print(f"\n Top {min(top_n, len(self.rules))} Association Rules:")
180
+ print(f" {'Antecedent':<30} {'Consequent':<20} "
181
+ f"{'Support':>8} {'Confidence':>10} {'Lift':>8}")
182
+ print(f" {'-'*80}")
183
+
184
+ for rule in self.rules[:top_n]:
185
+ ant = ', '.join(sorted(rule['antecedent']))
186
+ cons = ', '.join(sorted(rule['consequent']))
187
+ print(f" {ant:<30} → {cons:<16} "
188
+ f"{rule['support']:>8.4f} {rule['confidence']:>10.4f} "
189
+ f"{rule['lift']:>8.2f}")
190
+
191
+
192
+ def demo_apriori():
193
+ """Demo Apriori trên simulated Olist data."""
194
+
195
+ print("\n" + "=" * 70)
196
+ print(" PART 1: APRIORI - ASSOCIATION RULES MINING")
197
+ print("=" * 70)
198
+
199
+ np.random.seed(42)
200
+
201
+ # Simulate market basket data (product categories from Olist)
202
+ categories = [
203
+ 'bed_bath_table', 'health_beauty', 'sports_leisure',
204
+ 'furniture_decor', 'computers_accessories', 'housewares',
205
+ 'watches_gifts', 'telephony', 'garden_tools', 'auto',
206
+ 'cool_stuff', 'perfumery', 'toys', 'baby', 'electronics'
207
+ ]
208
+
209
+ # Generate transactions with realistic patterns
210
+ transactions = []
211
+ for _ in range(500):
212
+ n_items = np.random.choice([1, 2, 3, 4], p=[0.4, 0.35, 0.2, 0.05])
213
+ basket = set()
214
+
215
+ # Add correlated items
216
+ r = np.random.random()
217
+ if r < 0.3:
218
+ basket.update(['bed_bath_table', 'housewares'])
219
+ elif r < 0.5:
220
+ basket.update(['health_beauty', 'perfumery'])
221
+ elif r < 0.6:
222
+ basket.update(['computers_accessories', 'telephony'])
223
+ elif r < 0.7:
224
+ basket.update(['baby', 'toys'])
225
+
226
+ # Fill remaining with random
227
+ while len(basket) < n_items:
228
+ basket.add(np.random.choice(categories))
229
+
230
+ transactions.append(frozenset(basket))
231
+
232
+ # Run Apriori
233
+ apriori = AprioriFromScratch(min_support=0.03, min_confidence=0.3)
234
+ apriori.fit(transactions)
235
+ apriori.print_rules(top_n=15)
236
+
237
+ # Summary
238
+ print(f"\n Summary:")
239
+ for k, items in apriori.frequent_itemsets.items():
240
+ print(f" L{k}: {len(items)} frequent {k}-itemsets")
241
+
242
+
243
+ # ==============================================================================
244
+ # PHẦN 2: DECISION TREE (scikit-learn + visualization)
245
+ # ==============================================================================
246
+
247
+ def demo_decision_tree():
248
+ """Decision Tree cho dự đoán customer satisfaction."""
249
+
250
+ from sklearn.tree import DecisionTreeClassifier, export_text
251
+ from sklearn.model_selection import train_test_split
252
+ from sklearn.metrics import classification_report, accuracy_score
253
+
254
+ print("\n" + "=" * 70)
255
+ print(" PART 2: DECISION TREE - CUSTOMER SATISFACTION")
256
+ print("=" * 70)
257
+
258
+ np.random.seed(42)
259
+ n = 1000
260
+
261
+ # Create dataset
262
+ delivery_days = np.random.exponential(10, n)
263
+ price = np.random.lognormal(4, 1, n)
264
+ freight_ratio = np.random.uniform(0.05, 0.5, n)
265
+ weight_kg = np.random.lognormal(1, 0.8, n)
266
+ is_weekend = np.random.binomial(1, 0.3, n)
267
+
268
+ # Target: satisfied (review >= 4) based on features
269
+ satisfaction_prob = (
270
+ 0.8
271
+ - 0.02 * np.clip(delivery_days, 0, 30)
272
+ - 0.001 * np.clip(price, 0, 1000)
273
+ - 0.3 * freight_ratio
274
+ + 0.05 * is_weekend
275
+ )
276
+ satisfaction_prob = np.clip(satisfaction_prob, 0.05, 0.95)
277
+ satisfied = np.random.binomial(1, satisfaction_prob)
278
+
279
+ df = pd.DataFrame({
280
+ 'delivery_days': delivery_days.round(1),
281
+ 'price': price.round(2),
282
+ 'freight_ratio': freight_ratio.round(3),
283
+ 'weight_kg': weight_kg.round(2),
284
+ 'is_weekend': is_weekend,
285
+ 'satisfied': satisfied
286
+ })
287
+
288
+ print(f"\n Dataset: {len(df)} samples")
289
+ print(f" Satisfied: {satisfied.sum()} ({satisfied.mean()*100:.1f}%)")
290
+ print(f" Not satisfied: {n - satisfied.sum()} ({(1-satisfied.mean())*100:.1f}%)")
291
+
292
+ # Train/test split
293
+ X = df.drop('satisfied', axis=1)
294
+ y = df['satisfied']
295
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
296
+
297
+ # Train Decision Tree
298
+ for criterion, name in [('entropy', 'ID3-style (Entropy)'), ('gini', 'CART (Gini)')]:
299
+ print(f"\n --- {name} ---")
300
+
301
+ tree = DecisionTreeClassifier(
302
+ criterion=criterion,
303
+ max_depth=4,
304
+ min_samples_leaf=20,
305
+ random_state=42
306
+ )
307
+ tree.fit(X_train, y_train)
308
+
309
+ y_pred = tree.predict(X_test)
310
+ accuracy = accuracy_score(y_test, y_pred)
311
+
312
+ print(f" Accuracy: {accuracy:.4f}")
313
+ print(f"\n Classification Report:")
314
+ print(classification_report(y_test, y_pred, target_names=['Not Satisfied', 'Satisfied']))
315
+
316
+ # Feature importance
317
+ importance = pd.Series(tree.feature_importances_, index=X.columns).sort_values(ascending=False)
318
+ print(f" Feature Importance:")
319
+ for feat, imp in importance.items():
320
+ bar = '█' * int(imp * 50)
321
+ print(f" {feat:<20} {imp:.4f} {bar}")
322
+
323
+ # Print tree rules
324
+ if criterion == 'entropy':
325
+ print(f"\n Decision Tree Rules (depth ≤ 3):")
326
+ tree_rules = export_text(tree, feature_names=list(X.columns), max_depth=3)
327
+ for line in tree_rules.split('\n')[:20]:
328
+ print(f" {line}")
329
+
330
+
331
+ # ==============================================================================
332
+ # PHẦN 3: K-MEANS CUSTOMER SEGMENTATION
333
+ # ==============================================================================
334
+
335
+ def demo_kmeans():
336
+ """K-Means clustering cho RFM customer segmentation."""
337
+
338
+ from sklearn.cluster import KMeans
339
+ from sklearn.preprocessing import StandardScaler
340
+ from sklearn.metrics import silhouette_score
341
+
342
+ print("\n" + "=" * 70)
343
+ print(" PART 3: K-MEANS - CUSTOMER SEGMENTATION (RFM)")
344
+ print("=" * 70)
345
+
346
+ np.random.seed(42)
347
+
348
+ # Simulate RFM data
349
+ n_customers = 500
350
+
351
+ # Create clusters with different RFM profiles
352
+ clusters_data = []
353
+
354
+ # Champions: Recent, Frequent, High monetary
355
+ for _ in range(100):
356
+ clusters_data.append([
357
+ np.random.uniform(1, 30), # Recency (days)
358
+ np.random.randint(5, 15), # Frequency
359
+ np.random.uniform(500, 2000), # Monetary
360
+ ])
361
+
362
+ # Loyal: Moderate recency, frequent, moderate spend
363
+ for _ in range(120):
364
+ clusters_data.append([
365
+ np.random.uniform(20, 90),
366
+ np.random.randint(3, 10),
367
+ np.random.uniform(200, 800),
368
+ ])
369
+
370
+ # New customers: Very recent, low frequency
371
+ for _ in range(80):
372
+ clusters_data.append([
373
+ np.random.uniform(1, 15),
374
+ np.random.randint(1, 3),
375
+ np.random.uniform(50, 300),
376
+ ])
377
+
378
+ # At Risk: Old, used to be frequent
379
+ for _ in range(100):
380
+ clusters_data.append([
381
+ np.random.uniform(90, 200),
382
+ np.random.randint(3, 8),
383
+ np.random.uniform(300, 1000),
384
+ ])
385
+
386
+ # Lost: Very old, infrequent, low spend
387
+ for _ in range(100):
388
+ clusters_data.append([
389
+ np.random.uniform(150, 365),
390
+ np.random.randint(1, 3),
391
+ np.random.uniform(30, 200),
392
+ ])
393
+
394
+ rfm = pd.DataFrame(clusters_data, columns=['Recency', 'Frequency', 'Monetary'])
395
+
396
+ print(f"\n RFM Dataset: {len(rfm)} customers")
397
+ print(f"\n Statistics:")
398
+ print(rfm.describe().round(2).to_string())
399
+
400
+ # Standardize
401
+ scaler = StandardScaler()
402
+ rfm_scaled = scaler.fit_transform(rfm)
403
+
404
+ # Elbow method
405
+ print(f"\n --- Elbow Method ---")
406
+ inertias = []
407
+ silhouettes = []
408
+ K_range = range(2, 10)
409
+
410
+ for k in K_range:
411
+ km = KMeans(n_clusters=k, random_state=42, n_init=10)
412
+ km.fit(rfm_scaled)
413
+ inertias.append(km.inertia_)
414
+ sil = silhouette_score(rfm_scaled, km.labels_)
415
+ silhouettes.append(sil)
416
+ print(f" K={k}: Inertia={km.inertia_:.0f}, Silhouette={sil:.4f}")
417
+
418
+ best_k = list(K_range)[np.argmax(silhouettes)]
419
+ print(f"\n Best K by Silhouette: {best_k}")
420
+
421
+ # Final model with K=5
422
+ K = 5
423
+ km_final = KMeans(n_clusters=K, random_state=42, n_init=10)
424
+ rfm['Cluster'] = km_final.fit_predict(rfm_scaled)
425
+
426
+ # Cluster profiles
427
+ print(f"\n --- Cluster Profiles (K={K}) ---")
428
+ profiles = rfm.groupby('Cluster').agg({
429
+ 'Recency': 'mean',
430
+ 'Frequency': 'mean',
431
+ 'Monetary': 'mean',
432
+ 'Cluster': 'count'
433
+ }).rename(columns={'Cluster': 'Count'}).round(1)
434
+
435
+ # Name clusters
436
+ segment_names = {}
437
+ for idx, row in profiles.iterrows():
438
+ if row['Recency'] < 30 and row['Frequency'] > 5:
439
+ segment_names[idx] = 'Champions'
440
+ elif row['Recency'] < 60 and row['Frequency'] > 3:
441
+ segment_names[idx] = 'Loyal'
442
+ elif row['Recency'] < 30 and row['Frequency'] <= 2:
443
+ segment_names[idx] = 'New Customers'
444
+ elif row['Recency'] > 100 and row['Frequency'] > 3:
445
+ segment_names[idx] = 'At Risk'
446
+ else:
447
+ segment_names[idx] = 'Lost/Hibernating'
448
+
449
+ profiles['Segment'] = profiles.index.map(segment_names)
450
+ print(profiles.to_string())
451
+
452
+ # Visualization
453
+ fig, axes = plt.subplots(1, 3, figsize=(16, 5))
454
+
455
+ # Elbow
456
+ axes[0].plot(list(K_range), inertias, 'bo-')
457
+ axes[0].set_xlabel('K (Number of Clusters)')
458
+ axes[0].set_ylabel('Inertia')
459
+ axes[0].set_title('Elbow Method')
460
+
461
+ # Silhouette
462
+ axes[1].plot(list(K_range), silhouettes, 'ro-')
463
+ axes[1].set_xlabel('K')
464
+ axes[1].set_ylabel('Silhouette Score')
465
+ axes[1].set_title('Silhouette Method')
466
+ axes[1].axvline(x=best_k, color='green', linestyle='--', label=f'Best K={best_k}')
467
+ axes[1].legend()
468
+
469
+ # Scatter: Recency vs Monetary (colored by cluster)
470
+ colors = ['#e74c3c', '#3498db', '#2ecc71', '#f39c12', '#9b59b6']
471
+ for cluster in range(K):
472
+ mask = rfm['Cluster'] == cluster
473
+ name = segment_names.get(cluster, f'Cluster {cluster}')
474
+ axes[2].scatter(rfm.loc[mask, 'Recency'], rfm.loc[mask, 'Monetary'],
475
+ c=colors[cluster % len(colors)], label=name, alpha=0.6, s=30)
476
+ axes[2].set_xlabel('Recency (days)')
477
+ axes[2].set_ylabel('Monetary ($)')
478
+ axes[2].set_title(f'Customer Segments (K={K})')
479
+ axes[2].legend(fontsize=8)
480
+
481
+ plt.tight_layout()
482
+ plt.savefig('kmeans_segmentation.png', dpi=150, bbox_inches='tight')
483
+ print(f"\n [OK] Saved: kmeans_segmentation.png")
484
+ plt.close()
485
+
486
+
487
+ # ==============================================================================
488
+ # PHẦN 4: DBSCAN ANOMALY DETECTION
489
+ # ==============================================================================
490
+
491
+ def demo_dbscan():
492
+ """DBSCAN cho phát hiện anomaly trong delivery data."""
493
+
494
+ from sklearn.cluster import DBSCAN
495
+ from sklearn.preprocessing import StandardScaler
496
+
497
+ print("\n" + "=" * 70)
498
+ print(" PART 4: DBSCAN - ANOMALY DETECTION")
499
+ print("=" * 70)
500
+
501
+ np.random.seed(42)
502
+
503
+ # Simulate order data with anomalies
504
+ n_normal = 400
505
+ n_anomaly = 30
506
+
507
+ # Normal orders
508
+ normal = pd.DataFrame({
509
+ 'delivery_days': np.random.normal(12, 3, n_normal),
510
+ 'price': np.random.lognormal(4.5, 0.5, n_normal),
511
+ 'freight_ratio': np.random.normal(0.15, 0.05, n_normal),
512
+ })
513
+
514
+ # Anomalies
515
+ anomalies = pd.DataFrame({
516
+ 'delivery_days': np.concatenate([
517
+ np.random.uniform(40, 80, 15), # Very late deliveries
518
+ np.random.uniform(0, 1, 15), # Suspiciously fast
519
+ ]),
520
+ 'price': np.concatenate([
521
+ np.random.uniform(2000, 10000, 15), # Very expensive
522
+ np.random.uniform(0.5, 5, 15), # Suspiciously cheap
523
+ ]),
524
+ 'freight_ratio': np.concatenate([
525
+ np.random.uniform(0.5, 1.5, 15), # High freight
526
+ np.random.uniform(0, 0.01, 15), # Almost no freight
527
+ ]),
528
+ })
529
+
530
+ df = pd.concat([normal, anomalies], ignore_index=True)
531
+ df['is_anomaly_truth'] = [0] * n_normal + [1] * n_anomaly
532
+
533
+ # Standardize
534
+ features = ['delivery_days', 'price', 'freight_ratio']
535
+ scaler = StandardScaler()
536
+ X_scaled = scaler.fit_transform(df[features])
537
+
538
+ # DBSCAN
539
+ # Try different eps values
540
+ print(f"\n Dataset: {len(df)} orders ({n_anomaly} known anomalies)")
541
+ print(f"\n --- DBSCAN Parameter Search ---")
542
+
543
+ best_eps = 0.5
544
+ best_score = 0
545
+
546
+ for eps in [0.3, 0.5, 0.7, 1.0, 1.5]:
547
+ for min_samples in [3, 5, 10]:
548
+ db = DBSCAN(eps=eps, min_samples=min_samples)
549
+ labels = db.fit_predict(X_scaled)
550
+
551
+ n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
552
+ n_noise = (labels == -1).sum()
553
+
554
+ # Check overlap with true anomalies
555
+ detected_anomalies = set(np.where(labels == -1)[0])
556
+ true_anomalies = set(np.where(df['is_anomaly_truth'] == 1)[0])
557
+
558
+ true_positives = len(detected_anomalies & true_anomalies)
559
+ precision = true_positives / len(detected_anomalies) if detected_anomalies else 0
560
+ recall = true_positives / len(true_anomalies) if true_anomalies else 0
561
+ f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0
562
+
563
+ print(f" eps={eps}, min_samples={min_samples}: "
564
+ f"clusters={n_clusters}, noise={n_noise}, "
565
+ f"P={precision:.2f}, R={recall:.2f}, F1={f1:.2f}")
566
+
567
+ if f1 > best_score:
568
+ best_score = f1
569
+ best_eps = eps
570
+ best_min = min_samples
571
+
572
+ # Best model
573
+ print(f"\n Best: eps={best_eps}, min_samples={best_min}, F1={best_score:.2f}")
574
+
575
+ db_best = DBSCAN(eps=best_eps, min_samples=best_min)
576
+ df['dbscan_label'] = db_best.fit_predict(X_scaled)
577
+ df['detected_anomaly'] = (df['dbscan_label'] == -1).astype(int)
578
+
579
+ # Print anomalies
580
+ anomalies_detected = df[df['detected_anomaly'] == 1]
581
+ print(f"\n Detected {len(anomalies_detected)} anomalies:")
582
+ print(anomalies_detected[features + ['is_anomaly_truth']].describe().round(2).to_string())
583
+
584
+ # Visualization
585
+ fig, axes = plt.subplots(1, 2, figsize=(14, 5))
586
+
587
+ # Delivery days vs Price
588
+ for label, name, color, marker in [
589
+ (0, 'Normal', '#3498db', 'o'),
590
+ (1, 'Anomaly (DBSCAN)', '#e74c3c', 'x')
591
+ ]:
592
+ mask = df['detected_anomaly'] == label
593
+ axes[0].scatter(df.loc[mask, 'delivery_days'], df.loc[mask, 'price'],
594
+ c=color, label=name, alpha=0.6, s=30 if label == 0 else 80,
595
+ marker=marker)
596
+ axes[0].set_xlabel('Delivery Days')
597
+ axes[0].set_ylabel('Price ($)')
598
+ axes[0].set_title('DBSCAN Anomaly Detection')
599
+ axes[0].legend()
600
+
601
+ # Confusion-like comparison
602
+ tp = ((df['detected_anomaly'] == 1) & (df['is_anomaly_truth'] == 1)).sum()
603
+ fp = ((df['detected_anomaly'] == 1) & (df['is_anomaly_truth'] == 0)).sum()
604
+ fn = ((df['detected_anomaly'] == 0) & (df['is_anomaly_truth'] == 1)).sum()
605
+ tn = ((df['detected_anomaly'] == 0) & (df['is_anomaly_truth'] == 0)).sum()
606
+
607
+ confusion = np.array([[tn, fp], [fn, tp]])
608
+ im = axes[1].imshow(confusion, cmap='Blues', interpolation='nearest')
609
+ axes[1].set_xticks([0, 1])
610
+ axes[1].set_yticks([0, 1])
611
+ axes[1].set_xticklabels(['Predicted\nNormal', 'Predicted\nAnomaly'])
612
+ axes[1].set_yticklabels(['Actual\nNormal', 'Actual\nAnomaly'])
613
+ axes[1].set_title('Confusion Matrix')
614
+
615
+ for i in range(2):
616
+ for j in range(2):
617
+ axes[1].text(j, i, str(confusion[i, j]),
618
+ ha='center', va='center', fontsize=16, fontweight='bold')
619
+
620
+ plt.tight_layout()
621
+ plt.savefig('dbscan_anomaly.png', dpi=150, bbox_inches='tight')
622
+ print(f"\n [OK] Saved: dbscan_anomaly.png")
623
+ plt.close()
624
+
625
+
626
+ # ==============================================================================
627
+ # PHẦN 5: NAIVE BAYES
628
+ # ==============================================================================
629
+
630
+ def demo_naive_bayes():
631
+ """Naive Bayes cho review score prediction."""
632
+
633
+ from sklearn.naive_bayes import GaussianNB
634
+ from sklearn.model_selection import train_test_split
635
+ from sklearn.metrics import classification_report, accuracy_score
636
+
637
+ print("\n" + "=" * 70)
638
+ print(" PART 5: NAIVE BAYES - REVIEW PREDICTION")
639
+ print("=" * 70)
640
+
641
+ np.random.seed(42)
642
+ n = 1000
643
+
644
+ # Simulate features
645
+ delivery_days = np.random.exponential(10, n)
646
+ price = np.random.lognormal(4, 1, n)
647
+ freight_ratio = np.random.uniform(0.05, 0.5, n)
648
+ photos_qty = np.random.randint(1, 8, n)
649
+ description_length = np.random.randint(50, 2000, n)
650
+
651
+ # Target: Good review (>= 4)
652
+ prob = (
653
+ 0.7
654
+ - 0.015 * np.clip(delivery_days, 0, 30)
655
+ + 0.01 * photos_qty
656
+ + 0.0001 * description_length
657
+ - 0.2 * freight_ratio
658
+ )
659
+ prob = np.clip(prob, 0.1, 0.9)
660
+ good_review = np.random.binomial(1, prob)
661
+
662
+ df = pd.DataFrame({
663
+ 'delivery_days': delivery_days,
664
+ 'price': price,
665
+ 'freight_ratio': freight_ratio,
666
+ 'photos_qty': photos_qty,
667
+ 'description_length': description_length,
668
+ 'good_review': good_review
669
+ })
670
+
671
+ X = df.drop('good_review', axis=1)
672
+ y = df['good_review']
673
+
674
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
675
+
676
+ # Gaussian Naive Bayes
677
+ gnb = GaussianNB()
678
+ gnb.fit(X_train, y_train)
679
+ y_pred = gnb.predict(X_test)
680
+
681
+ print(f"\n Gaussian Naive Bayes:")
682
+ print(f" Accuracy: {accuracy_score(y_test, y_pred):.4f}")
683
+ print(f"\n Classification Report:")
684
+ print(classification_report(y_test, y_pred, target_names=['Bad Review', 'Good Review']))
685
+
686
+ # Class priors
687
+ print(f" Class Priors: {gnb.class_prior_}")
688
+
689
+ # Feature means per class
690
+ print(f"\n Feature Means by Class:")
691
+ means = pd.DataFrame(gnb.theta_, columns=X.columns, index=['Bad Review', 'Good Review'])
692
+ print(means.round(2).to_string())
693
+
694
+ # Predict example
695
+ example = pd.DataFrame({
696
+ 'delivery_days': [5, 25],
697
+ 'price': [100, 500],
698
+ 'freight_ratio': [0.1, 0.4],
699
+ 'photos_qty': [5, 1],
700
+ 'description_length': [500, 100]
701
+ })
702
+
703
+ probs = gnb.predict_proba(example)
704
+ print(f"\n Prediction Examples:")
705
+ for i, (_, row) in enumerate(example.iterrows()):
706
+ print(f" Order: delivery={row['delivery_days']}d, price=${row['price']}, "
707
+ f"freight_ratio={row['freight_ratio']}")
708
+ print(f" → P(Good)={probs[i][1]:.3f}, P(Bad)={probs[i][0]:.3f}, "
709
+ f"Predicted: {'Good' if probs[i][1] > 0.5 else 'Bad'}")
710
+
711
+
712
+ # ==============================================================================
713
+ # MAIN
714
+ # ==============================================================================
715
+
716
+ if __name__ == '__main__':
717
+ print("=" * 70)
718
+ print(" LAB 5: DATA MINING ALGORITHMS")
719
+ print(" BIM5021 - Nha kho du lieu va Tich hop")
720
+ print("=" * 70)
721
+
722
+ demo_apriori()
723
+ demo_decision_tree()
724
+ demo_kmeans()
725
+ demo_dbscan()
726
+ demo_naive_bayes()
727
+
728
+ print("\n" + "=" * 70)
729
+ print(" HOAN THANH LAB 5!")
730
+ print(" Files: kmeans_segmentation.png, dbscan_anomaly.png")
731
+ print("=" * 70)