""" Lab 5: Data Mining Algorithms ============================== BIM5021 - Nhà kho dữ liệu và Tích hợp Chương 5: Thuật toán khai thác dữ liệu cốt lõi Mục tiêu: - Implement Apriori từ đầu (from scratch) - Association Rules mining trên Olist order items - Decision Tree (ID3-style) với scikit-learn - K-Means Customer Segmentation (RFM) - DBSCAN Anomaly Detection - Naive Bayes cho review prediction Yêu cầu: pip install pandas numpy scikit-learn matplotlib mlxtend """ import pandas as pd import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from collections import defaultdict from itertools import combinations import warnings warnings.filterwarnings('ignore') # ============================================================================== # PHẦN 1: APRIORI ALGORITHM (From Scratch!) # ============================================================================== class AprioriFromScratch: """ Implementation Apriori algorithm từ đầu. Tham khảo: Agrawal & Srikant, 1994 """ def __init__(self, min_support: float = 0.01, min_confidence: float = 0.5): self.min_support = min_support self.min_confidence = min_confidence self.frequent_itemsets = {} self.rules = [] def _get_support(self, itemset: frozenset, transactions: list) -> float: """Tính support của 1 itemset.""" count = sum(1 for t in transactions if itemset.issubset(t)) return count / len(transactions) def _get_frequent_1_itemsets(self, transactions: list) -> dict: """Tìm tất cả frequent 1-itemsets.""" item_counts = defaultdict(int) for t in transactions: for item in t: item_counts[frozenset([item])] += 1 n = len(transactions) return { itemset: count / n for itemset, count in item_counts.items() if count / n >= self.min_support } def _generate_candidates(self, prev_frequent: dict, k: int) -> set: """Generate candidate k-itemsets từ (k-1)-itemsets.""" items = list(prev_frequent.keys()) candidates = set() for i in range(len(items)): for j in range(i + 1, len(items)): # Union of two (k-1)-itemsets candidate = items[i] | items[j] if len(candidate) == k: # Apriori pruning: check all (k-1) subsets are frequent all_subsets_frequent = True for item in candidate: subset = candidate - frozenset([item]) if subset not in prev_frequent: all_subsets_frequent = False break if all_subsets_frequent: candidates.add(candidate) return candidates def fit(self, transactions: list): """Chạy thuật toán Apriori.""" print(f"\n [APRIORI] min_support={self.min_support}, " f"min_confidence={self.min_confidence}") print(f" [APRIORI] {len(transactions)} transactions") # Step 1: L1 L1 = self._get_frequent_1_itemsets(transactions) self.frequent_itemsets[1] = L1 print(f" [L1] {len(L1)} frequent 1-itemsets") # Step 2: Iterate k = 2, 3, ... k = 2 prev_frequent = L1 while prev_frequent: # Generate candidates candidates = self._generate_candidates(prev_frequent, k) if not candidates: break # Count support for candidates Lk = {} for candidate in candidates: support = self._get_support(candidate, transactions) if support >= self.min_support: Lk[candidate] = support if Lk: self.frequent_itemsets[k] = Lk print(f" [L{k}] {len(Lk)} frequent {k}-itemsets " f"(from {len(candidates)} candidates)") prev_frequent = Lk k += 1 # Generate rules self._generate_rules(transactions) return self def _generate_rules(self, transactions: list): """Generate association rules từ frequent itemsets.""" self.rules = [] for k in range(2, max(self.frequent_itemsets.keys()) + 1): if k not in self.frequent_itemsets: continue for itemset, support in self.frequent_itemsets[k].items(): # Generate all non-empty proper subsets items = list(itemset) for i in range(1, len(items)): for antecedent_items in combinations(items, i): antecedent = frozenset(antecedent_items) consequent = itemset - antecedent # Find antecedent support ant_support = None ant_k = len(antecedent) if ant_k in self.frequent_itemsets: ant_support = self.frequent_itemsets[ant_k].get(antecedent) if ant_support is None or ant_support == 0: continue confidence = support / ant_support if confidence >= self.min_confidence: # Calculate lift cons_k = len(consequent) cons_support = self.frequent_itemsets.get(cons_k, {}).get( consequent, 0 ) lift = confidence / cons_support if cons_support > 0 else 0 self.rules.append({ 'antecedent': antecedent, 'consequent': consequent, 'support': round(support, 4), 'confidence': round(confidence, 4), 'lift': round(lift, 4), }) # Sort by lift self.rules.sort(key=lambda x: x['lift'], reverse=True) print(f" [RULES] {len(self.rules)} rules generated " f"(confidence >= {self.min_confidence})") def print_rules(self, top_n: int = 10): """In top rules.""" print(f"\n Top {min(top_n, len(self.rules))} Association Rules:") print(f" {'Antecedent':<30} {'Consequent':<20} " f"{'Support':>8} {'Confidence':>10} {'Lift':>8}") print(f" {'-'*80}") for rule in self.rules[:top_n]: ant = ', '.join(sorted(rule['antecedent'])) cons = ', '.join(sorted(rule['consequent'])) print(f" {ant:<30} → {cons:<16} " f"{rule['support']:>8.4f} {rule['confidence']:>10.4f} " f"{rule['lift']:>8.2f}") def demo_apriori(): """Demo Apriori trên simulated Olist data.""" print("\n" + "=" * 70) print(" PART 1: APRIORI - ASSOCIATION RULES MINING") print("=" * 70) np.random.seed(42) # Simulate market basket data (product categories from Olist) categories = [ 'bed_bath_table', 'health_beauty', 'sports_leisure', 'furniture_decor', 'computers_accessories', 'housewares', 'watches_gifts', 'telephony', 'garden_tools', 'auto', 'cool_stuff', 'perfumery', 'toys', 'baby', 'electronics' ] # Generate transactions with realistic patterns transactions = [] for _ in range(500): n_items = np.random.choice([1, 2, 3, 4], p=[0.4, 0.35, 0.2, 0.05]) basket = set() # Add correlated items r = np.random.random() if r < 0.3: basket.update(['bed_bath_table', 'housewares']) elif r < 0.5: basket.update(['health_beauty', 'perfumery']) elif r < 0.6: basket.update(['computers_accessories', 'telephony']) elif r < 0.7: basket.update(['baby', 'toys']) # Fill remaining with random while len(basket) < n_items: basket.add(np.random.choice(categories)) transactions.append(frozenset(basket)) # Run Apriori apriori = AprioriFromScratch(min_support=0.03, min_confidence=0.3) apriori.fit(transactions) apriori.print_rules(top_n=15) # Summary print(f"\n Summary:") for k, items in apriori.frequent_itemsets.items(): print(f" L{k}: {len(items)} frequent {k}-itemsets") # ============================================================================== # PHẦN 2: DECISION TREE (scikit-learn + visualization) # ============================================================================== def demo_decision_tree(): """Decision Tree cho dự đoán customer satisfaction.""" from sklearn.tree import DecisionTreeClassifier, export_text from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, accuracy_score print("\n" + "=" * 70) print(" PART 2: DECISION TREE - CUSTOMER SATISFACTION") print("=" * 70) np.random.seed(42) n = 1000 # Create dataset delivery_days = np.random.exponential(10, n) price = np.random.lognormal(4, 1, n) freight_ratio = np.random.uniform(0.05, 0.5, n) weight_kg = np.random.lognormal(1, 0.8, n) is_weekend = np.random.binomial(1, 0.3, n) # Target: satisfied (review >= 4) based on features satisfaction_prob = ( 0.8 - 0.02 * np.clip(delivery_days, 0, 30) - 0.001 * np.clip(price, 0, 1000) - 0.3 * freight_ratio + 0.05 * is_weekend ) satisfaction_prob = np.clip(satisfaction_prob, 0.05, 0.95) satisfied = np.random.binomial(1, satisfaction_prob) df = pd.DataFrame({ 'delivery_days': delivery_days.round(1), 'price': price.round(2), 'freight_ratio': freight_ratio.round(3), 'weight_kg': weight_kg.round(2), 'is_weekend': is_weekend, 'satisfied': satisfied }) print(f"\n Dataset: {len(df)} samples") print(f" Satisfied: {satisfied.sum()} ({satisfied.mean()*100:.1f}%)") print(f" Not satisfied: {n - satisfied.sum()} ({(1-satisfied.mean())*100:.1f}%)") # Train/test split X = df.drop('satisfied', axis=1) y = df['satisfied'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Train Decision Tree for criterion, name in [('entropy', 'ID3-style (Entropy)'), ('gini', 'CART (Gini)')]: print(f"\n --- {name} ---") tree = DecisionTreeClassifier( criterion=criterion, max_depth=4, min_samples_leaf=20, random_state=42 ) tree.fit(X_train, y_train) y_pred = tree.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print(f" Accuracy: {accuracy:.4f}") print(f"\n Classification Report:") print(classification_report(y_test, y_pred, target_names=['Not Satisfied', 'Satisfied'])) # Feature importance importance = pd.Series(tree.feature_importances_, index=X.columns).sort_values(ascending=False) print(f" Feature Importance:") for feat, imp in importance.items(): bar = '█' * int(imp * 50) print(f" {feat:<20} {imp:.4f} {bar}") # Print tree rules if criterion == 'entropy': print(f"\n Decision Tree Rules (depth ≤ 3):") tree_rules = export_text(tree, feature_names=list(X.columns), max_depth=3) for line in tree_rules.split('\n')[:20]: print(f" {line}") # ============================================================================== # PHẦN 3: K-MEANS CUSTOMER SEGMENTATION # ============================================================================== def demo_kmeans(): """K-Means clustering cho RFM customer segmentation.""" from sklearn.cluster import KMeans from sklearn.preprocessing import StandardScaler from sklearn.metrics import silhouette_score print("\n" + "=" * 70) print(" PART 3: K-MEANS - CUSTOMER SEGMENTATION (RFM)") print("=" * 70) np.random.seed(42) # Simulate RFM data n_customers = 500 # Create clusters with different RFM profiles clusters_data = [] # Champions: Recent, Frequent, High monetary for _ in range(100): clusters_data.append([ np.random.uniform(1, 30), # Recency (days) np.random.randint(5, 15), # Frequency np.random.uniform(500, 2000), # Monetary ]) # Loyal: Moderate recency, frequent, moderate spend for _ in range(120): clusters_data.append([ np.random.uniform(20, 90), np.random.randint(3, 10), np.random.uniform(200, 800), ]) # New customers: Very recent, low frequency for _ in range(80): clusters_data.append([ np.random.uniform(1, 15), np.random.randint(1, 3), np.random.uniform(50, 300), ]) # At Risk: Old, used to be frequent for _ in range(100): clusters_data.append([ np.random.uniform(90, 200), np.random.randint(3, 8), np.random.uniform(300, 1000), ]) # Lost: Very old, infrequent, low spend for _ in range(100): clusters_data.append([ np.random.uniform(150, 365), np.random.randint(1, 3), np.random.uniform(30, 200), ]) rfm = pd.DataFrame(clusters_data, columns=['Recency', 'Frequency', 'Monetary']) print(f"\n RFM Dataset: {len(rfm)} customers") print(f"\n Statistics:") print(rfm.describe().round(2).to_string()) # Standardize scaler = StandardScaler() rfm_scaled = scaler.fit_transform(rfm) # Elbow method print(f"\n --- Elbow Method ---") inertias = [] silhouettes = [] K_range = range(2, 10) for k in K_range: km = KMeans(n_clusters=k, random_state=42, n_init=10) km.fit(rfm_scaled) inertias.append(km.inertia_) sil = silhouette_score(rfm_scaled, km.labels_) silhouettes.append(sil) print(f" K={k}: Inertia={km.inertia_:.0f}, Silhouette={sil:.4f}") best_k = list(K_range)[np.argmax(silhouettes)] print(f"\n Best K by Silhouette: {best_k}") # Final model with K=5 K = 5 km_final = KMeans(n_clusters=K, random_state=42, n_init=10) rfm['Cluster'] = km_final.fit_predict(rfm_scaled) # Cluster profiles print(f"\n --- Cluster Profiles (K={K}) ---") profiles = rfm.groupby('Cluster').agg({ 'Recency': 'mean', 'Frequency': 'mean', 'Monetary': 'mean', 'Cluster': 'count' }).rename(columns={'Cluster': 'Count'}).round(1) # Name clusters segment_names = {} for idx, row in profiles.iterrows(): if row['Recency'] < 30 and row['Frequency'] > 5: segment_names[idx] = 'Champions' elif row['Recency'] < 60 and row['Frequency'] > 3: segment_names[idx] = 'Loyal' elif row['Recency'] < 30 and row['Frequency'] <= 2: segment_names[idx] = 'New Customers' elif row['Recency'] > 100 and row['Frequency'] > 3: segment_names[idx] = 'At Risk' else: segment_names[idx] = 'Lost/Hibernating' profiles['Segment'] = profiles.index.map(segment_names) print(profiles.to_string()) # Visualization fig, axes = plt.subplots(1, 3, figsize=(16, 5)) # Elbow axes[0].plot(list(K_range), inertias, 'bo-') axes[0].set_xlabel('K (Number of Clusters)') axes[0].set_ylabel('Inertia') axes[0].set_title('Elbow Method') # Silhouette axes[1].plot(list(K_range), silhouettes, 'ro-') axes[1].set_xlabel('K') axes[1].set_ylabel('Silhouette Score') axes[1].set_title('Silhouette Method') axes[1].axvline(x=best_k, color='green', linestyle='--', label=f'Best K={best_k}') axes[1].legend() # Scatter: Recency vs Monetary (colored by cluster) colors = ['#e74c3c', '#3498db', '#2ecc71', '#f39c12', '#9b59b6'] for cluster in range(K): mask = rfm['Cluster'] == cluster name = segment_names.get(cluster, f'Cluster {cluster}') axes[2].scatter(rfm.loc[mask, 'Recency'], rfm.loc[mask, 'Monetary'], c=colors[cluster % len(colors)], label=name, alpha=0.6, s=30) axes[2].set_xlabel('Recency (days)') axes[2].set_ylabel('Monetary ($)') axes[2].set_title(f'Customer Segments (K={K})') axes[2].legend(fontsize=8) plt.tight_layout() plt.savefig('kmeans_segmentation.png', dpi=150, bbox_inches='tight') print(f"\n [OK] Saved: kmeans_segmentation.png") plt.close() # ============================================================================== # PHẦN 4: DBSCAN ANOMALY DETECTION # ============================================================================== def demo_dbscan(): """DBSCAN cho phát hiện anomaly trong delivery data.""" from sklearn.cluster import DBSCAN from sklearn.preprocessing import StandardScaler print("\n" + "=" * 70) print(" PART 4: DBSCAN - ANOMALY DETECTION") print("=" * 70) np.random.seed(42) # Simulate order data with anomalies n_normal = 400 n_anomaly = 30 # Normal orders normal = pd.DataFrame({ 'delivery_days': np.random.normal(12, 3, n_normal), 'price': np.random.lognormal(4.5, 0.5, n_normal), 'freight_ratio': np.random.normal(0.15, 0.05, n_normal), }) # Anomalies anomalies = pd.DataFrame({ 'delivery_days': np.concatenate([ np.random.uniform(40, 80, 15), # Very late deliveries np.random.uniform(0, 1, 15), # Suspiciously fast ]), 'price': np.concatenate([ np.random.uniform(2000, 10000, 15), # Very expensive np.random.uniform(0.5, 5, 15), # Suspiciously cheap ]), 'freight_ratio': np.concatenate([ np.random.uniform(0.5, 1.5, 15), # High freight np.random.uniform(0, 0.01, 15), # Almost no freight ]), }) df = pd.concat([normal, anomalies], ignore_index=True) df['is_anomaly_truth'] = [0] * n_normal + [1] * n_anomaly # Standardize features = ['delivery_days', 'price', 'freight_ratio'] scaler = StandardScaler() X_scaled = scaler.fit_transform(df[features]) # DBSCAN # Try different eps values print(f"\n Dataset: {len(df)} orders ({n_anomaly} known anomalies)") print(f"\n --- DBSCAN Parameter Search ---") best_eps = 0.5 best_score = 0 for eps in [0.3, 0.5, 0.7, 1.0, 1.5]: for min_samples in [3, 5, 10]: db = DBSCAN(eps=eps, min_samples=min_samples) labels = db.fit_predict(X_scaled) n_clusters = len(set(labels)) - (1 if -1 in labels else 0) n_noise = (labels == -1).sum() # Check overlap with true anomalies detected_anomalies = set(np.where(labels == -1)[0]) true_anomalies = set(np.where(df['is_anomaly_truth'] == 1)[0]) true_positives = len(detected_anomalies & true_anomalies) precision = true_positives / len(detected_anomalies) if detected_anomalies else 0 recall = true_positives / len(true_anomalies) if true_anomalies else 0 f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0 print(f" eps={eps}, min_samples={min_samples}: " f"clusters={n_clusters}, noise={n_noise}, " f"P={precision:.2f}, R={recall:.2f}, F1={f1:.2f}") if f1 > best_score: best_score = f1 best_eps = eps best_min = min_samples # Best model print(f"\n Best: eps={best_eps}, min_samples={best_min}, F1={best_score:.2f}") db_best = DBSCAN(eps=best_eps, min_samples=best_min) df['dbscan_label'] = db_best.fit_predict(X_scaled) df['detected_anomaly'] = (df['dbscan_label'] == -1).astype(int) # Print anomalies anomalies_detected = df[df['detected_anomaly'] == 1] print(f"\n Detected {len(anomalies_detected)} anomalies:") print(anomalies_detected[features + ['is_anomaly_truth']].describe().round(2).to_string()) # Visualization fig, axes = plt.subplots(1, 2, figsize=(14, 5)) # Delivery days vs Price for label, name, color, marker in [ (0, 'Normal', '#3498db', 'o'), (1, 'Anomaly (DBSCAN)', '#e74c3c', 'x') ]: mask = df['detected_anomaly'] == label axes[0].scatter(df.loc[mask, 'delivery_days'], df.loc[mask, 'price'], c=color, label=name, alpha=0.6, s=30 if label == 0 else 80, marker=marker) axes[0].set_xlabel('Delivery Days') axes[0].set_ylabel('Price ($)') axes[0].set_title('DBSCAN Anomaly Detection') axes[0].legend() # Confusion-like comparison tp = ((df['detected_anomaly'] == 1) & (df['is_anomaly_truth'] == 1)).sum() fp = ((df['detected_anomaly'] == 1) & (df['is_anomaly_truth'] == 0)).sum() fn = ((df['detected_anomaly'] == 0) & (df['is_anomaly_truth'] == 1)).sum() tn = ((df['detected_anomaly'] == 0) & (df['is_anomaly_truth'] == 0)).sum() confusion = np.array([[tn, fp], [fn, tp]]) im = axes[1].imshow(confusion, cmap='Blues', interpolation='nearest') axes[1].set_xticks([0, 1]) axes[1].set_yticks([0, 1]) axes[1].set_xticklabels(['Predicted\nNormal', 'Predicted\nAnomaly']) axes[1].set_yticklabels(['Actual\nNormal', 'Actual\nAnomaly']) axes[1].set_title('Confusion Matrix') for i in range(2): for j in range(2): axes[1].text(j, i, str(confusion[i, j]), ha='center', va='center', fontsize=16, fontweight='bold') plt.tight_layout() plt.savefig('dbscan_anomaly.png', dpi=150, bbox_inches='tight') print(f"\n [OK] Saved: dbscan_anomaly.png") plt.close() # ============================================================================== # PHẦN 5: NAIVE BAYES # ============================================================================== def demo_naive_bayes(): """Naive Bayes cho review score prediction.""" from sklearn.naive_bayes import GaussianNB from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, accuracy_score print("\n" + "=" * 70) print(" PART 5: NAIVE BAYES - REVIEW PREDICTION") print("=" * 70) np.random.seed(42) n = 1000 # Simulate features delivery_days = np.random.exponential(10, n) price = np.random.lognormal(4, 1, n) freight_ratio = np.random.uniform(0.05, 0.5, n) photos_qty = np.random.randint(1, 8, n) description_length = np.random.randint(50, 2000, n) # Target: Good review (>= 4) prob = ( 0.7 - 0.015 * np.clip(delivery_days, 0, 30) + 0.01 * photos_qty + 0.0001 * description_length - 0.2 * freight_ratio ) prob = np.clip(prob, 0.1, 0.9) good_review = np.random.binomial(1, prob) df = pd.DataFrame({ 'delivery_days': delivery_days, 'price': price, 'freight_ratio': freight_ratio, 'photos_qty': photos_qty, 'description_length': description_length, 'good_review': good_review }) X = df.drop('good_review', axis=1) y = df['good_review'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Gaussian Naive Bayes gnb = GaussianNB() gnb.fit(X_train, y_train) y_pred = gnb.predict(X_test) print(f"\n Gaussian Naive Bayes:") print(f" Accuracy: {accuracy_score(y_test, y_pred):.4f}") print(f"\n Classification Report:") print(classification_report(y_test, y_pred, target_names=['Bad Review', 'Good Review'])) # Class priors print(f" Class Priors: {gnb.class_prior_}") # Feature means per class print(f"\n Feature Means by Class:") means = pd.DataFrame(gnb.theta_, columns=X.columns, index=['Bad Review', 'Good Review']) print(means.round(2).to_string()) # Predict example example = pd.DataFrame({ 'delivery_days': [5, 25], 'price': [100, 500], 'freight_ratio': [0.1, 0.4], 'photos_qty': [5, 1], 'description_length': [500, 100] }) probs = gnb.predict_proba(example) print(f"\n Prediction Examples:") for i, (_, row) in enumerate(example.iterrows()): print(f" Order: delivery={row['delivery_days']}d, price=${row['price']}, " f"freight_ratio={row['freight_ratio']}") print(f" → P(Good)={probs[i][1]:.3f}, P(Bad)={probs[i][0]:.3f}, " f"Predicted: {'Good' if probs[i][1] > 0.5 else 'Bad'}") # ============================================================================== # MAIN # ============================================================================== if __name__ == '__main__': print("=" * 70) print(" LAB 5: DATA MINING ALGORITHMS") print(" BIM5021 - Nha kho du lieu va Tich hop") print("=" * 70) demo_apriori() demo_decision_tree() demo_kmeans() demo_dbscan() demo_naive_bayes() print("\n" + "=" * 70) print(" HOAN THANH LAB 5!") print(" Files: kmeans_segmentation.png, dbscan_anomaly.png") print("=" * 70)