| """ |
| 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') |
|
|
|
|
| |
| |
| |
|
|
| 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)): |
| |
| candidate = items[i] | items[j] |
| if len(candidate) == k: |
| |
| 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") |
| |
| |
| L1 = self._get_frequent_1_itemsets(transactions) |
| self.frequent_itemsets[1] = L1 |
| print(f" [L1] {len(L1)} frequent 1-itemsets") |
| |
| |
| k = 2 |
| prev_frequent = L1 |
| |
| while prev_frequent: |
| |
| candidates = self._generate_candidates(prev_frequent, k) |
| |
| if not candidates: |
| break |
| |
| |
| 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 |
| |
| |
| 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(): |
| |
| items = list(itemset) |
| for i in range(1, len(items)): |
| for antecedent_items in combinations(items, i): |
| antecedent = frozenset(antecedent_items) |
| consequent = itemset - antecedent |
| |
| |
| 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: |
| |
| 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), |
| }) |
| |
| |
| 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) |
| |
| |
| 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' |
| ] |
| |
| |
| 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() |
| |
| |
| 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']) |
| |
| |
| while len(basket) < n_items: |
| basket.add(np.random.choice(categories)) |
| |
| transactions.append(frozenset(basket)) |
| |
| |
| apriori = AprioriFromScratch(min_support=0.03, min_confidence=0.3) |
| apriori.fit(transactions) |
| apriori.print_rules(top_n=15) |
| |
| |
| print(f"\n Summary:") |
| for k, items in apriori.frequent_itemsets.items(): |
| print(f" L{k}: {len(items)} frequent {k}-itemsets") |
|
|
|
|
| |
| |
| |
|
|
| 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 |
| |
| |
| 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) |
| |
| |
| 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}%)") |
| |
| |
| 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) |
| |
| |
| 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'])) |
| |
| |
| 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}") |
| |
| |
| 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}") |
|
|
|
|
| |
| |
| |
|
|
| 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) |
| |
| |
| n_customers = 500 |
| |
| |
| clusters_data = [] |
| |
| |
| for _ in range(100): |
| clusters_data.append([ |
| np.random.uniform(1, 30), |
| np.random.randint(5, 15), |
| np.random.uniform(500, 2000), |
| ]) |
| |
| |
| for _ in range(120): |
| clusters_data.append([ |
| np.random.uniform(20, 90), |
| np.random.randint(3, 10), |
| np.random.uniform(200, 800), |
| ]) |
| |
| |
| for _ in range(80): |
| clusters_data.append([ |
| np.random.uniform(1, 15), |
| np.random.randint(1, 3), |
| np.random.uniform(50, 300), |
| ]) |
| |
| |
| for _ in range(100): |
| clusters_data.append([ |
| np.random.uniform(90, 200), |
| np.random.randint(3, 8), |
| np.random.uniform(300, 1000), |
| ]) |
| |
| |
| 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()) |
| |
| |
| scaler = StandardScaler() |
| rfm_scaled = scaler.fit_transform(rfm) |
| |
| |
| 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}") |
| |
| |
| K = 5 |
| km_final = KMeans(n_clusters=K, random_state=42, n_init=10) |
| rfm['Cluster'] = km_final.fit_predict(rfm_scaled) |
| |
| |
| 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) |
| |
| |
| 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()) |
| |
| |
| fig, axes = plt.subplots(1, 3, figsize=(16, 5)) |
| |
| |
| 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') |
| |
| |
| 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() |
| |
| |
| 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() |
|
|
|
|
| |
| |
| |
|
|
| 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) |
| |
| |
| n_normal = 400 |
| n_anomaly = 30 |
| |
| |
| 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 = pd.DataFrame({ |
| 'delivery_days': np.concatenate([ |
| np.random.uniform(40, 80, 15), |
| np.random.uniform(0, 1, 15), |
| ]), |
| 'price': np.concatenate([ |
| np.random.uniform(2000, 10000, 15), |
| np.random.uniform(0.5, 5, 15), |
| ]), |
| 'freight_ratio': np.concatenate([ |
| np.random.uniform(0.5, 1.5, 15), |
| np.random.uniform(0, 0.01, 15), |
| ]), |
| }) |
| |
| df = pd.concat([normal, anomalies], ignore_index=True) |
| df['is_anomaly_truth'] = [0] * n_normal + [1] * n_anomaly |
| |
| |
| features = ['delivery_days', 'price', 'freight_ratio'] |
| scaler = StandardScaler() |
| X_scaled = scaler.fit_transform(df[features]) |
| |
| |
| |
| 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() |
| |
| |
| 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 |
| |
| |
| 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) |
| |
| |
| 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()) |
| |
| |
| fig, axes = plt.subplots(1, 2, figsize=(14, 5)) |
| |
| |
| 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() |
| |
| |
| 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() |
|
|
|
|
| |
| |
| |
|
|
| 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 |
| |
| |
| 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) |
| |
| |
| 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) |
| |
| |
| 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'])) |
| |
| |
| print(f" Class Priors: {gnb.class_prior_}") |
| |
| |
| 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()) |
| |
| |
| 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'}") |
|
|
|
|
| |
| |
| |
|
|
| 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) |
|
|