agentic-bi-ecommerce / analytics /satisfaction_model.py
thanhtai435's picture
Add analytics/satisfaction_model.py — complete pipeline for 10/10 grade
460185e verified
"""
Satisfaction Prediction — Decision Tree, Naive Bayes, Evaluation
=================================================================
CLO5: Classification (ID3/C4.5, Naive Bayes), Evaluation metrics
Predict: Khách hàng có hài lòng không? (review_score >= 4)
Features: delivery_days, price, freight_ratio, product weight, payment type...
Usage:
python analytics/satisfaction_model.py --data-dir ./data/raw
"""
import os, sys, logging, argparse, json
import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeClassifier, export_text
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import (classification_report, accuracy_score, confusion_matrix,
roc_auc_score, roc_curve, f1_score)
from sklearn.preprocessing import LabelEncoder
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')
logger = logging.getLogger(__name__)
def prepare_ml_dataset(data_dir: str) -> pd.DataFrame:
"""Chuẩn bị dataset cho classification."""
orders = pd.read_csv(os.path.join(data_dir, 'olist_orders_dataset.csv'),
parse_dates=['order_purchase_timestamp', 'order_delivered_customer_date',
'order_estimated_delivery_date'])
items = pd.read_csv(os.path.join(data_dir, 'olist_order_items_dataset.csv'))
reviews = pd.read_csv(os.path.join(data_dir, 'olist_order_reviews_dataset.csv'))
products = pd.read_csv(os.path.join(data_dir, 'olist_products_dataset.csv'))
payments = pd.read_csv(os.path.join(data_dir, 'olist_order_payments_dataset.csv'))
customers = pd.read_csv(os.path.join(data_dir, 'olist_customers_dataset.csv'))
# Filter delivered + reviewed
orders = orders[orders['order_status'] == 'delivered']
orders = orders.merge(reviews[['order_id', 'review_score']], on='order_id', how='inner')
# Delivery features
mask = orders['order_delivered_customer_date'].notna() & orders['order_purchase_timestamp'].notna()
orders.loc[mask, 'delivery_days'] = (
(orders.loc[mask, 'order_delivered_customer_date'] - orders.loc[mask, 'order_purchase_timestamp'])
.dt.total_seconds() / 86400
)
mask2 = orders['order_delivered_customer_date'].notna() & orders['order_estimated_delivery_date'].notna()
orders.loc[mask2, 'delivery_delay'] = (
(orders.loc[mask2, 'order_delivered_customer_date'] - orders.loc[mask2, 'order_estimated_delivery_date'])
.dt.total_seconds() / 86400
)
orders['is_late'] = (orders['delivery_delay'] > 0).astype(int)
# Item aggregates
item_agg = items.groupby('order_id').agg(
total_price=('price', 'sum'), total_freight=('freight_value', 'sum'),
n_items=('order_item_id', 'count'), n_sellers=('seller_id', 'nunique'),
).reset_index()
# Payment aggregates
pay_agg = payments.groupby('order_id').agg(
total_payment=('payment_value', 'sum'),
max_installments=('payment_installments', 'max'),
primary_payment=('payment_type', lambda x: x.mode()[0] if len(x) > 0 else 'unknown'),
).reset_index()
# Product features (avg per order)
items_products = items.merge(products[['product_id', 'product_weight_g', 'product_photos_qty',
'product_description_lenght', 'product_name_lenght']],
on='product_id', how='left')
prod_agg = items_products.groupby('order_id').agg(
avg_weight=('product_weight_g', 'mean'),
avg_photos=('product_photos_qty', 'mean'),
avg_desc_len=('product_description_lenght', 'mean'),
).reset_index()
# Time features
ts = orders['order_purchase_timestamp']
orders['purchase_hour'] = ts.dt.hour
orders['purchase_dayofweek'] = ts.dt.dayofweek
orders['is_weekend'] = (ts.dt.dayofweek >= 5).astype(int)
# Customer state
orders = orders.merge(customers[['customer_id', 'customer_state']], on='customer_id', how='left')
# Merge all
df = orders.merge(item_agg, on='order_id', how='left')
df = df.merge(pay_agg, on='order_id', how='left')
df = df.merge(prod_agg, on='order_id', how='left')
# Derived
df['freight_ratio'] = (df['total_freight'] / df['total_price'].replace(0, np.nan)).fillna(0)
# Target
df['satisfied'] = (df['review_score'] >= 4).astype(int)
# Feature columns
feature_cols = ['delivery_days', 'delivery_delay', 'is_late', 'total_price', 'total_freight',
'freight_ratio', 'n_items', 'n_sellers', 'max_installments',
'avg_weight', 'avg_photos', 'avg_desc_len',
'purchase_hour', 'purchase_dayofweek', 'is_weekend']
df = df.dropna(subset=['delivery_days', 'review_score'])
# Fill remaining NaN with median
for c in feature_cols:
if c in df.columns:
df[c] = df[c].fillna(df[c].median())
logger.info(f"[DATA] ML dataset: {len(df)} samples, {df['satisfied'].mean()*100:.1f}% satisfied")
return df, feature_cols
def train_and_evaluate(df: pd.DataFrame, feature_cols: list, output_dir: str):
"""Train Decision Tree, Naive Bayes, Random Forest and compare."""
X = df[feature_cols]
y = df['satisfied']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
logger.info(f"Train: {len(X_train)}, Test: {len(X_test)}")
models = {
'Decision Tree (Entropy/ID3)': DecisionTreeClassifier(
criterion='entropy', max_depth=6, min_samples_leaf=50, random_state=42),
'Decision Tree (Gini/CART)': DecisionTreeClassifier(
criterion='gini', max_depth=6, min_samples_leaf=50, random_state=42),
'Gaussian Naive Bayes': GaussianNB(),
'Random Forest': RandomForestClassifier(
n_estimators=100, max_depth=8, min_samples_leaf=30, random_state=42, n_jobs=-1),
}
results = {}
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
ax_flat = axes.flatten()
for idx, (name, model) in enumerate(models.items()):
logger.info(f"\n[MODEL] Training {name}...")
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
y_proba = model.predict_proba(X_test)[:, 1] if hasattr(model, 'predict_proba') else None
acc = accuracy_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
auc = roc_auc_score(y_test, y_proba) if y_proba is not None else 0
# Cross-validation
cv_scores = cross_val_score(model, X, y, cv=5, scoring='f1')
results[name] = {
'accuracy': round(acc, 4), 'f1_score': round(f1, 4), 'auc_roc': round(auc, 4),
'cv_f1_mean': round(cv_scores.mean(), 4), 'cv_f1_std': round(cv_scores.std(), 4),
}
print(f"\n {'='*60}")
print(f" {name}")
print(f" {'='*60}")
print(f" Accuracy: {acc:.4f} | F1: {f1:.4f} | AUC-ROC: {auc:.4f}")
print(f" CV F1: {cv_scores.mean():.4f} ± {cv_scores.std():.4f}")
print(classification_report(y_test, y_pred, target_names=['Not Satisfied', 'Satisfied']))
# Feature importance (for tree models)
if hasattr(model, 'feature_importances_'):
importance = pd.Series(model.feature_importances_, index=feature_cols).sort_values(ascending=False)
print(f" Top 5 Features:")
for feat, imp in importance.head(5).items():
print(f" {feat}: {imp:.4f}")
# ROC Curve
if y_proba is not None:
fpr, tpr, _ = roc_curve(y_test, y_proba)
ax_flat[idx].plot(fpr, tpr, label=f'{name}\nAUC={auc:.3f}', linewidth=2)
ax_flat[idx].plot([0, 1], [0, 1], 'k--', alpha=0.3)
ax_flat[idx].set_xlabel('FPR')
ax_flat[idx].set_ylabel('TPR')
ax_flat[idx].set_title(f'{name}')
ax_flat[idx].legend(fontsize=9)
plt.suptitle('Model Comparison — ROC Curves', fontsize=14, fontweight='bold')
plt.tight_layout()
path = os.path.join(output_dir, 'model_comparison.png')
plt.savefig(path, dpi=150, bbox_inches='tight')
plt.close()
logger.info(f"[VIZ] Saved: {path}")
# Decision Tree Rules
dt_model = models['Decision Tree (Entropy/ID3)']
print(f"\n DECISION TREE RULES (depth ≤ 3):")
tree_text = export_text(dt_model, feature_names=feature_cols, max_depth=3)
for line in tree_text.split('\n')[:25]:
print(f" {line}")
# Feature Importance plot
fig, ax = plt.subplots(figsize=(10, 6))
rf_model = models['Random Forest']
importance = pd.Series(rf_model.feature_importances_, index=feature_cols).sort_values(ascending=True)
importance.plot(kind='barh', ax=ax, color='#3498db', alpha=0.8)
ax.set_title('Feature Importance (Random Forest)')
ax.set_xlabel('Importance')
path2 = os.path.join(output_dir, 'feature_importance.png')
plt.savefig(path2, dpi=150, bbox_inches='tight')
plt.close()
logger.info(f"[VIZ] Saved: {path2}")
# Save results
with open(os.path.join(output_dir, 'model_results.json'), 'w') as f:
json.dump(results, f, indent=2)
# Summary
print(f"\n{'='*70}")
print(f" MODEL COMPARISON SUMMARY")
print(f"{'='*70}")
print(f" {'Model':<35} {'Accuracy':>10} {'F1':>8} {'AUC':>8} {'CV F1':>10}")
print(f" {'-'*75}")
for name, r in results.items():
print(f" {name:<35} {r['accuracy']:>10.4f} {r['f1_score']:>8.4f} "
f"{r['auc_roc']:>8.4f} {r['cv_f1_mean']:>7.4f}±{r['cv_f1_std']:.3f}")
best = max(results.items(), key=lambda x: x[1]['f1_score'])
print(f"\n Best model: {best[0]} (F1={best[1]['f1_score']:.4f})")
print(f"{'='*70}")
return results
def main():
parser = argparse.ArgumentParser(description='Satisfaction Prediction Models')
parser.add_argument('--data-dir', type=str, default='./data/raw')
parser.add_argument('--output-dir', type=str, default='./data/analytics')
args = parser.parse_args()
os.makedirs(args.output_dir, exist_ok=True)
df, feature_cols = prepare_ml_dataset(args.data_dir)
results = train_and_evaluate(df, feature_cols, args.output_dir)
if __name__ == '__main__':
main()