{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# AI Chatbot for Customer Objection Solution — v3 (Hierarchical)\n", "\n", "### Thesis Implementation Notebook — Chapters 3 to 5\n", "\n", "**Author:** Huth Sakda — Institute of Technology of Cambodia (ITC)\n", "**Company Context:** Explorer by SL — Visa & Travel Agency, Cambodia\n", "\n", "---\n", "\n", "> **How to run**: Always use **Kernel → Restart & Run All**.\n", ">\n", "> **GPU required** for Section 4.8 (DistilBERT hierarchical training). With an NVIDIA GPU it takes ~20-30 minutes total. CPU-only will take ~2-3 hours.\n", ">\n", "> **Parallelism fix**: Section 3.1 forces joblib to use the threading backend to avoid `_posixsubprocess` errors.\n", "\n", "---\n", "\n", "## What changed in v3\n", "\n", "This version is architecturally different from v1/v2. The dataset has **25 cluster names** but **33 (objection_type, cluster) pairs** because some clusters (General, Refund, Previous Rejection, Travel History, Document Forgery, Processing Time) appear under multiple parent objection types with genuinely different meanings.\n", "\n", "**Solution: hierarchical classification.** Every model is now a two-stage classifier:\n", "\n", "1. **Stage 1** predicts the **Objection Type** (8 classes)\n", "2. **Stage 2** predicts the **Cluster** within the predicted objection type\n", "\n", "This eliminates the ambiguity of duplicate cluster names and produces cleaner metrics.\n", "\n", "## Five hierarchical models trained\n", "\n", "Each model has both a Stage-1 and a Stage-2 classifier:\n", "\n", "1. **TF-IDF + Logistic Regression**\n", "2. **TF-IDF + Linear SVM** (with calibrated probabilities)\n", "3. **TF-IDF + Random Forest**\n", "4. **Sentence-Transformer Embeddings + Logistic Regression**\n", "5. **Fine-tuned DistilBERT** (the headline model)\n", "\n", "All rigorous methodology from v2 is preserved: 10-fold CV, full grid search, ablation study, learning curves, McNemar's significance tests, OOD detection, inference latency benchmarks, per-class PR curves, top-3 predictions with confidence.\n", "\n", "---\n", "\n", "## Table of Contents\n", "\n", "### Chapter 3 — Data Understanding\n", "- 3.1 Setup and Environment\n", "- 3.2 Load the Dataset\n", "- 3.3 Schema and Quality Checks\n", "- 3.4 Hierarchy Verification\n", "- 3.5 Label Distribution\n", "- 3.6 Hierarchy Visualization\n", "- 3.7 Text Length Analysis\n", "- 3.8 Vocabulary and Word Clouds\n", "- 3.9 Preprocessing Pipeline\n", "- 3.10 Train/Test Split\n", "\n", "### Chapter 4 — Methodology and Model Training\n", "- 4.1 Hierarchical Classification Framework\n", "- 4.2 Evaluation Metrics and 10-Fold CV\n", "- 4.3 Hierarchical Classifier Class\n", "- 4.4 Model 1 — Hierarchical TF-IDF + LogReg\n", "- 4.5 Model 2 — Hierarchical TF-IDF + LinearSVC (calibrated)\n", "- 4.6 Model 3 — Hierarchical TF-IDF + Random Forest\n", "- 4.7 Model 4 — Hierarchical Embeddings + LogReg\n", "- 4.8 Model 5 — Hierarchical DistilBERT\n", "- 4.9 TF-IDF Feature Ablation\n", "- 4.10 Learning Curves\n", "- 4.11 Consolidated CV Results\n", "\n", "### Chapter 5 — Evaluation and Model Selection\n", "- 5.1 Held-Out Test Evaluation\n", "- 5.2 Model Comparison Visualization\n", "- 5.3 McNemar's Significance Testing\n", "- 5.4 Confusion Matrices (Stage 1 and Stage 2)\n", "- 5.5 Per-Class Performance\n", "- 5.6 Stage-1 vs Stage-2 Error Decomposition\n", "- 5.7 Deep Error Analysis with Quote Inspection\n", "- 5.8 Per-Class PR Curves\n", "- 5.9 Inference Latency Benchmarking\n", "- 5.10 Top-3 Predictions with Confidence\n", "- 5.11 Out-of-Distribution Detection\n", "- 5.12 Final Model Selection\n", "- 5.13 Save Artifacts for Webapp\n", "- 5.14 Demo Inference Cell\n", "- 5.15 Chapter Summary\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Chapter 3 — Data Understanding" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3.1 — Setup and Environment" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Core\n", "import pandas as pd\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "import seaborn as sns\n", "from wordcloud import WordCloud\n", "\n", "import re\n", "import pickle\n", "import time\n", "import warnings\n", "from pathlib import Path\n", "from collections import Counter\n", "from copy import deepcopy\n", "\n", "# ML\n", "from sklearn.model_selection import train_test_split, StratifiedKFold, GridSearchCV\n", "from sklearn.feature_extraction.text import TfidfVectorizer\n", "from sklearn.linear_model import LogisticRegression\n", "from sklearn.svm import LinearSVC\n", "from sklearn.ensemble import RandomForestClassifier\n", "from sklearn.calibration import CalibratedClassifierCV\n", "from sklearn.pipeline import Pipeline\n", "from sklearn.base import BaseEstimator, ClassifierMixin\n", "from sklearn.metrics import (\n", " accuracy_score, f1_score, precision_score, recall_score,\n", " classification_report, confusion_matrix, precision_recall_curve\n", ")\n", "\n", "# Sentence-Transformer\n", "from sentence_transformers import SentenceTransformer\n", "\n", "# Deep learning\n", "import torch\n", "from torch.utils.data import Dataset, DataLoader\n", "from torch.optim import AdamW\n", "from transformers import AutoTokenizer, AutoModelForSequenceClassification, get_linear_schedule_with_warmup\n", "\n", "warnings.filterwarnings('ignore')\n", "\n", "# Reproducibility\n", "RANDOM_STATE = 42\n", "np.random.seed(RANDOM_STATE)\n", "torch.manual_seed(RANDOM_STATE)\n", "\n", "# Display\n", "pd.set_option('display.max_colwidth', 100)\n", "pd.set_option('display.width', 200)\n", "sns.set_style('whitegrid')\n", "plt.rcParams['figure.figsize'] = (12, 6)\n", "plt.rcParams['axes.titleweight'] = 'bold'\n", "\n", "# Paths\n", "DATA_PATH = Path('final_dataset.csv')\n", "ARTIFACTS_DIR = Path('artifacts')\n", "ARTIFACTS_DIR.mkdir(exist_ok=True)\n", "\n", "# 10-fold stratified CV (used for all CV calls)\n", "CV_FOLDS = 10\n", "cv_splitter = StratifiedKFold(n_splits=CV_FOLDS, shuffle=True, random_state=RANDOM_STATE)\n", "\n", "# Parallelism fix: threading backend\n", "import joblib\n", "joblib.parallel_config(backend='threading', n_jobs=-1)\n", "\n", "# GPU detection\n", "if torch.cuda.is_available():\n", " DEVICE = torch.device('cuda')\n", " print(f'GPU detected: {torch.cuda.get_device_name(0)}')\n", " print(f'CUDA version : {torch.version.cuda}')\n", "else:\n", " DEVICE = torch.device('cpu')\n", " print('WARNING: No GPU detected. Section 4.8 (DistilBERT) will be slow.')\n", "\n", "print(f'\\nEnvironment ready.')\n", "print(f'CV folds : {CV_FOLDS}')\n", "print(f'Device : {DEVICE}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3.2 — Load the Dataset" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df = pd.read_csv(DATA_PATH, encoding='utf-8')\n", "print(f'Dataset loaded: {df.shape[0]} rows x {df.shape[1]} columns')\n", "df.head(8)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3.3 — Schema and Quality Checks" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Schema\n", "schema = pd.DataFrame({\n", " 'dtype' : df.dtypes.astype(str),\n", " 'non_null': df.notna().sum(),\n", " 'nulls' : df.isnull().sum(),\n", " 'unique' : df.nunique(),\n", "})\n", "print('Schema:')\n", "print(schema)\n", "\n", "# Quality\n", "print(f'\\nFully duplicate rows: {df.duplicated().sum()}')\n", "print(f'Duplicate quote text: {df[\"quote\"].duplicated().sum()}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3.4 — Hierarchy Verification\n", "\n", "This dataset has a hierarchical label structure: each **cluster** belongs to exactly one **objection type**. We verify this, and explicitly enumerate the `(cluster, objection_type)` pairs because some cluster names (General, Refund, Previous Rejection, etc.) appear under multiple parent types." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Verify hierarchy: each unique (cluster, objection_type) pair is a distinct label\n", "pair_labels = df[['objection_type', 'cluster']].drop_duplicates().sort_values(['objection_type', 'cluster'])\n", "\n", "print(f'Unique cluster names : {df[\"cluster\"].nunique()}')\n", "print(f'Unique objection types : {df[\"objection_type\"].nunique()}')\n", "print(f'Unique (type, cluster) pairs: {len(pair_labels)}')\n", "print()\n", "print('All (objection_type, cluster) pairs in dataset:')\n", "print(pair_labels.to_string(index=False))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Quotes that map to multiple clusters within the SAME objection type\n", "quote_cluster = df.groupby(['objection_type', 'quote'])['cluster'].nunique()\n", "inconsistent = quote_cluster[quote_cluster > 1]\n", "print(f'Quote<->cluster inconsistencies within same objection type: {len(inconsistent)}')\n", "\n", "# Build cluster-to-type lookup for hierarchical models\n", "# Keyed by (objection_type, cluster) to disambiguate duplicate cluster names\n", "cluster_type_pairs = set(zip(df['objection_type'], df['cluster']))\n", "print(f'Total (type, cluster) labels: {len(cluster_type_pairs)}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3.5 — Label Distribution" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type_counts = df['objection_type'].value_counts()\n", "pair_counts = df.groupby(['objection_type', 'cluster']).size().sort_values(ascending=False)\n", "\n", "print('Objection Type distribution:')\n", "print(type_counts.to_string())\n", "print(f'\\n Min/Max/Ratio: {type_counts.min()} / {type_counts.max()} / {type_counts.max()/type_counts.min():.2f}x\\n')\n", "\n", "print('(Type, Cluster) pair distribution:')\n", "print(pair_counts.to_string())\n", "print(f'\\n Min/Max/Ratio: {pair_counts.min()} / {pair_counts.max()} / {pair_counts.max()/pair_counts.min():.2f}x')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Objection type distribution chart\n", "fig, ax = plt.subplots(figsize=(11, 6))\n", "type_counts.plot(kind='barh', ax=ax, color=sns.color_palette('viridis', len(type_counts)))\n", "ax.set_title('Objection Type Distribution (Stage-1 labels)', fontsize=13)\n", "ax.set_xlabel('Number of Quotes')\n", "ax.invert_yaxis()\n", "for i, v in enumerate(type_counts.values):\n", " ax.text(v + 10, i, str(v), va='center', fontsize=10)\n", "plt.tight_layout()\n", "plt.savefig(ARTIFACTS_DIR / 'fig_3_5a_type_dist.png', dpi=150, bbox_inches='tight')\n", "plt.show()\n", "\n", "# Pair distribution chart\n", "fig, ax = plt.subplots(figsize=(13, 10))\n", "pair_labels_arr = [f'{t} | {c}' for (t, c), _ in pair_counts.items()]\n", "ax.barh(pair_labels_arr, pair_counts.values, color=sns.color_palette('mako', len(pair_counts)))\n", "ax.set_title('(Objection Type, Cluster) Pair Distribution (Stage-2 labels)', fontsize=13)\n", "ax.set_xlabel('Number of Quotes')\n", "ax.invert_yaxis()\n", "for i, v in enumerate(pair_counts.values):\n", " ax.text(v + 2, i, str(v), va='center', fontsize=8)\n", "plt.tight_layout()\n", "plt.savefig(ARTIFACTS_DIR / 'fig_3_5b_pair_dist.png', dpi=150, bbox_inches='tight')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3.6 — Hierarchy Visualization" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "hierarchy = df.groupby(['objection_type', 'cluster']).size().reset_index(name='count')\n", "hierarchy = hierarchy.sort_values(['objection_type', 'count'], ascending=[True, False])\n", "\n", "palette = sns.color_palette('tab10', n_colors=df['objection_type'].nunique())\n", "type_colors = {t: palette[i] for i, t in enumerate(sorted(df['objection_type'].unique()))}\n", "\n", "fig, ax = plt.subplots(figsize=(14, 10))\n", "ax.barh(range(len(hierarchy)), hierarchy['count'],\n", " color=[type_colors[t] for t in hierarchy['objection_type']])\n", "ax.set_yticks(range(len(hierarchy)))\n", "ax.set_yticklabels([f\"{r['cluster']} ({r['objection_type']})\" for _, r in hierarchy.iterrows()],\n", " fontsize=9)\n", "ax.set_xlabel('Number of Quotes')\n", "ax.set_title('Cluster → Objection Type Hierarchy', fontsize=13)\n", "ax.invert_yaxis()\n", "\n", "from matplotlib.patches import Patch\n", "legend = [Patch(facecolor=type_colors[t], label=t) for t in sorted(df['objection_type'].unique())]\n", "ax.legend(handles=legend, loc='lower right', title='Objection Type')\n", "plt.tight_layout()\n", "plt.savefig(ARTIFACTS_DIR / 'fig_3_6_hierarchy.png', dpi=150, bbox_inches='tight')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3.7 — Text Length Analysis" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df['char_length'] = df['quote'].str.len()\n", "df['word_count'] = df['quote'].str.split().str.len()\n", "\n", "print('Character length:')\n", "print(df['char_length'].describe().round(1))\n", "print('\\nWord count:')\n", "print(df['word_count'].describe().round(1))\n", "\n", "fig, axes = plt.subplots(1, 2, figsize=(16, 5))\n", "axes[0].hist(df['char_length'], bins=40, color='#2E86AB', edgecolor='white', alpha=0.85)\n", "axes[0].axvline(df['char_length'].median(), color='red', linestyle='--', label=f\"Median = {df['char_length'].median():.0f}\")\n", "axes[0].set_title('Character Length')\n", "axes[0].set_xlabel('Characters')\n", "axes[0].legend()\n", "\n", "axes[1].hist(df['word_count'], bins=30, color='#A23B72', edgecolor='white', alpha=0.85)\n", "axes[1].axvline(df['word_count'].median(), color='red', linestyle='--', label=f\"Median = {df['word_count'].median():.0f}\")\n", "axes[1].set_title('Word Count')\n", "axes[1].set_xlabel('Words')\n", "axes[1].legend()\n", "\n", "plt.tight_layout()\n", "plt.savefig(ARTIFACTS_DIR / 'fig_3_7_lengths.png', dpi=150, bbox_inches='tight')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3.8 — Vocabulary and Word Clouds" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "STOPWORDS = {'the','a','an','i','you','me','my','your','we','our','to','of','in','on',\n", " 'at','for','with','and','or','but','if','is','are','was','were','be','been',\n", " 'have','has','had','do','does','did','will','would','can','could','should',\n", " 'this','that','these','those','it','them','so','not','no','yes','very'}\n", "\n", "def simple_tokens(text):\n", " text = str(text).lower()\n", " text = re.sub(r\"[^a-z0-9\\s']\", ' ', text)\n", " return [t for t in text.split() if len(t) > 2]\n", "\n", "all_tokens = []\n", "for q in df['quote']:\n", " all_tokens.extend(simple_tokens(q))\n", "\n", "vocab = Counter(all_tokens)\n", "print(f'Total tokens : {len(all_tokens):,}')\n", "print(f'Unique tokens : {len(vocab):,}')\n", "print(f'\\nTop 20 tokens:')\n", "for tok, count in vocab.most_common(20):\n", " print(f' {tok:15s} {count:6d}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Word clouds per objection type\n", "objection_types = sorted(df['objection_type'].unique())\n", "nrows = int(np.ceil(len(objection_types) / 3))\n", "\n", "fig, axes = plt.subplots(nrows, 3, figsize=(18, 5 * nrows))\n", "axes = axes.flatten() if len(objection_types) > 1 else [axes]\n", "\n", "for i, ot in enumerate(objection_types):\n", " text = ' '.join(df[df['objection_type'] == ot]['quote'].astype(str))\n", " wc = WordCloud(width=600, height=400, background_color='white',\n", " colormap='viridis', stopwords=STOPWORDS, max_words=50,\n", " random_state=RANDOM_STATE).generate(text)\n", " axes[i].imshow(wc, interpolation='bilinear')\n", " axes[i].set_title(ot, fontsize=13, fontweight='bold')\n", " axes[i].axis('off')\n", "\n", "for j in range(i + 1, len(axes)):\n", " axes[j].axis('off')\n", "\n", "plt.tight_layout()\n", "plt.savefig(ARTIFACTS_DIR / 'fig_3_8_wordclouds.png', dpi=150, bbox_inches='tight')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3.9 — Preprocessing Pipeline" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def preprocess_text(text):\n", " \"\"\"Canonical preprocessing for classical models.\n", "\n", " DistilBERT uses its own tokenizer on raw text.\n", " \"\"\"\n", " text = str(text).lower()\n", " text = re.sub(r'http\\S+|www\\S+', ' ', text)\n", " text = re.sub(r\"[^a-z0-9\\s']\", ' ', text)\n", " text = re.sub(r'\\s+', ' ', text).strip()\n", " return text\n", "\n", "df['quote_clean'] = df['quote'].apply(preprocess_text)\n", "df[['quote', 'quote_clean']].sample(5, random_state=RANDOM_STATE).to_string()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3.10 — Train/Test Split\n", "\n", "We use an 80/20 stratified split on a combined `(type, cluster)` label so BOTH levels remain balanced in train and test sets." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "X_raw = df['quote'].values\n", "X = df['quote_clean'].values\n", "y_type = df['objection_type'].values\n", "y_cluster = df['cluster'].values\n", "\n", "# Combined label for stratification\n", "y_combined = np.array([f'{t}||{c}' for t, c in zip(y_type, y_cluster)])\n", "\n", "# Filter out singleton combined classes that would break stratify\n", "from collections import Counter\n", "combo_counts = Counter(y_combined)\n", "singleton_mask = np.array([combo_counts[c] < 2 for c in y_combined])\n", "if singleton_mask.any():\n", " print(f'Removing {singleton_mask.sum()} singleton-class examples before split')\n", " keep = ~singleton_mask\n", " X_raw = X_raw[keep]; X = X[keep]\n", " y_type = y_type[keep]; y_cluster = y_cluster[keep]\n", " y_combined = y_combined[keep]\n", "\n", "X_raw_train, X_raw_test, X_train, X_test, y_type_train, y_type_test, y_cluster_train, y_cluster_test = \\\n", " train_test_split(X_raw, X, y_type, y_cluster,\n", " test_size=0.20,\n", " random_state=RANDOM_STATE,\n", " stratify=y_combined)\n", "\n", "print(f'Train size: {len(X_train)}')\n", "print(f'Test size : {len(X_test)}')\n", "print(f'\\nAll {df[\"objection_type\"].nunique()} objection types in both splits: '\n", " f'{set(y_type_train) == set(y_type_test)}')\n", "print(f'All cluster names preserved: train={len(set(y_cluster_train))}, test={len(set(y_cluster_test))}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Chapter 4 — Methodology and Model Training" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.1 — Hierarchical Classification Framework\n", "\n", "**The problem with flat classification.** If we treat cluster as a flat 25-class target, the model conflates \"General\" under Trust with \"General\" under Location — three distinct objection types, one label. This hurts both accuracy and interpretability.\n", "\n", "**The hierarchical solution.** We decompose the task:\n", "\n", "- **Stage 1**: Predict the **Objection Type** (8 classes) from the quote text.\n", "- **Stage 2**: Predict the **Cluster** from the quote text, conditioned on the Stage-1 prediction.\n", "\n", "Stage 2 is actually **multiple sub-classifiers** — one for each objection type — each trained only on the clusters that belong to that type. At inference time:\n", "\n", "```\n", "quote ──► Stage 1 ──► predicted_type ──► route to Stage 2[predicted_type] ──► predicted_cluster\n", "```\n", "\n", "This matches the real taxonomy and eliminates name collisions. Published evidence (Silla & Freitas, 2011) shows this approach often outperforms flat classification for hierarchical label structures." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.2 — Evaluation Metrics and 10-Fold CV\n", "\n", "Metrics reported at both levels:\n", "\n", "| Metric | Purpose |\n", "|---|---|\n", "| **Type Accuracy / Macro-F1** | Stage 1 quality |\n", "| **Full-path Accuracy** | Both type AND cluster must be correct |\n", "| **Full-path Macro-F1** | Computed over the 33 (type, cluster) classes |\n", "\n", "Primary model-selection metric: **full-path Macro-F1** — this is what actually matters for the chatbot." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Safety net\n", "try:\n", " cv_splitter, CV_FOLDS\n", "except NameError:\n", " CV_FOLDS = 10\n", " cv_splitter = StratifiedKFold(n_splits=CV_FOLDS, shuffle=True, random_state=RANDOM_STATE)\n", "\n", "print(f'Cross-validation: {CV_FOLDS}-fold stratified, seed={RANDOM_STATE}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.3 — Hierarchical Classifier Class\n", "\n", "A single reusable class wraps the two-stage prediction logic. The `base_estimator_factory` argument is a zero-arg callable that returns a fresh model — we'll pass in TF-IDF+LogReg, TF-IDF+SVM, etc. to get each variant." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class HierarchicalTextClassifier(BaseEstimator, ClassifierMixin):\n", " \"\"\"Two-stage classifier for (objection_type, cluster) prediction.\n", "\n", " Stage 1: predicts objection_type from quote.\n", " Stage 2: per-type sub-classifiers predict cluster within that type.\n", "\n", " Parameters\n", " ----------\n", " base_estimator_factory : callable\n", " Zero-argument factory returning a FRESH sklearn-compatible estimator.\n", " Called once for stage 1 and once per stage-2 sub-classifier.\n", " \"\"\"\n", " def __init__(self, base_estimator_factory):\n", " self.base_estimator_factory = base_estimator_factory\n", "\n", " def fit(self, X, y_type, y_cluster):\n", " X = np.asarray(X, dtype=object)\n", " y_type = np.asarray(y_type)\n", " y_cluster = np.asarray(y_cluster)\n", "\n", " # Stage 1\n", " self.stage1_ = self.base_estimator_factory()\n", " self.stage1_.fit(X, y_type)\n", "\n", " # Stage 2: one sub-classifier per objection type\n", " self.stage2_ = {}\n", " self.type_to_clusters_ = {}\n", " for t in sorted(np.unique(y_type)):\n", " mask = y_type == t\n", " clusters_in_type = np.unique(y_cluster[mask])\n", " self.type_to_clusters_[t] = list(clusters_in_type)\n", "\n", " if len(clusters_in_type) == 1:\n", " # Only one cluster -> no sub-classifier needed; predict it directly\n", " self.stage2_[t] = None\n", " else:\n", " clf = self.base_estimator_factory()\n", " clf.fit(X[mask], y_cluster[mask])\n", " self.stage2_[t] = clf\n", " return self\n", "\n", " def predict_type(self, X):\n", " X = np.asarray(X, dtype=object)\n", " return self.stage1_.predict(X)\n", "\n", " def predict_cluster(self, X, predicted_types=None):\n", " X = np.asarray(X, dtype=object)\n", " if predicted_types is None:\n", " predicted_types = self.predict_type(X)\n", " clusters = np.empty(len(X), dtype=object)\n", " for t in np.unique(predicted_types):\n", " mask = predicted_types == t\n", " if self.stage2_.get(t) is None:\n", " # Deterministic single cluster for this type\n", " clusters[mask] = self.type_to_clusters_[t][0]\n", " else:\n", " clusters[mask] = self.stage2_[t].predict(X[mask])\n", " return clusters\n", "\n", " def predict(self, X):\n", " \"\"\"Returns an (n,2) array: [type, cluster].\"\"\"\n", " y_type_pred = self.predict_type(X)\n", " y_cluster_pred = self.predict_cluster(X, y_type_pred)\n", " return np.column_stack([y_type_pred, y_cluster_pred])\n", "\n", " def predict_type_proba(self, X):\n", " X = np.asarray(X, dtype=object)\n", " return self.stage1_.predict_proba(X)\n", "\n", "\n", "def evaluate_hierarchical(model, X, y_type_true, y_cluster_true):\n", " \"\"\"Compute type + full-path metrics for a hierarchical model.\"\"\"\n", " y_type_pred = model.predict_type(X)\n", " y_cluster_pred = model.predict_cluster(X, y_type_pred)\n", "\n", " type_acc = accuracy_score(y_type_true, y_type_pred)\n", " type_f1 = f1_score(y_type_true, y_type_pred, average='macro', zero_division=0)\n", "\n", " # Full-path: both correct\n", " full_correct = (y_type_pred == y_type_true) & (y_cluster_pred == y_cluster_true)\n", " full_acc = full_correct.mean()\n", "\n", " # Full-path F1 using composite labels\n", " composite_true = np.array([f'{t}||{c}' for t, c in zip(y_type_true, y_cluster_true)])\n", " composite_pred = np.array([f'{t}||{c}' for t, c in zip(y_type_pred, y_cluster_pred)])\n", " full_f1 = f1_score(composite_true, composite_pred, average='macro', zero_division=0)\n", "\n", " return {\n", " 'type_accuracy' : type_acc,\n", " 'type_f1_macro' : type_f1,\n", " 'full_accuracy' : full_acc,\n", " 'full_f1_macro' : full_f1,\n", " 'y_type_pred' : y_type_pred,\n", " 'y_cluster_pred' : y_cluster_pred,\n", " }\n", "\n", "print('HierarchicalTextClassifier defined.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.4 — Model 1: Hierarchical TF-IDF + Logistic Regression\n", "\n", "We tune hyperparameters on STAGE 1 (objection type prediction) via full grid search, then build the hierarchical model around those optimal settings. Stage-2 sub-classifiers reuse the same TF-IDF pipeline config but train on per-type subsets." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ---- Grid search on stage-1 task (objection type) ----\n", "pipe_logreg = Pipeline([\n", " ('tfidf', TfidfVectorizer(sublinear_tf=True, lowercase=True)),\n", " ('clf', LogisticRegression(max_iter=2000, class_weight='balanced', random_state=RANDOM_STATE))\n", "])\n", "\n", "param_grid_logreg = {\n", " 'tfidf__ngram_range' : [(1,1), (1,2)],\n", " 'tfidf__max_features' : [3000, 5000, 10000],\n", " 'tfidf__min_df' : [1, 2],\n", " 'clf__C' : [0.1, 1.0, 10.0],\n", "}\n", "\n", "t0 = time.time()\n", "gs_logreg = GridSearchCV(pipe_logreg, param_grid_logreg,\n", " cv=cv_splitter, scoring='f1_macro',\n", " n_jobs=-1, verbose=1)\n", "gs_logreg.fit(X_train, y_type_train)\n", "print(f'\\nLogReg stage-1 grid search | time: {time.time()-t0:.1f}s')\n", "print(f'Best Stage-1 CV Macro-F1: {gs_logreg.best_score_:.4f}')\n", "print(f'Best params : {gs_logreg.best_params_}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ---- Build hierarchical model with tuned config ----\n", "best_params_logreg = gs_logreg.best_params_\n", "\n", "def make_logreg_pipeline():\n", " return Pipeline([\n", " ('tfidf', TfidfVectorizer(\n", " ngram_range=best_params_logreg['tfidf__ngram_range'],\n", " max_features=best_params_logreg['tfidf__max_features'],\n", " min_df=best_params_logreg['tfidf__min_df'],\n", " sublinear_tf=True, lowercase=True,\n", " )),\n", " ('clf', LogisticRegression(\n", " C=best_params_logreg['clf__C'], max_iter=2000,\n", " class_weight='balanced', random_state=RANDOM_STATE,\n", " )),\n", " ])\n", "\n", "t0 = time.time()\n", "hmodel_logreg = HierarchicalTextClassifier(make_logreg_pipeline)\n", "hmodel_logreg.fit(X_train, y_type_train, y_cluster_train)\n", "print(f'Hierarchical LogReg trained in {time.time()-t0:.1f}s')\n", "\n", "# Quick held-out sanity check\n", "ev = evaluate_hierarchical(hmodel_logreg, X_test, y_type_test, y_cluster_test)\n", "print(f' Type Accuracy : {ev[\"type_accuracy\"]:.4f}')\n", "print(f' Type Macro-F1 : {ev[\"type_f1_macro\"]:.4f}')\n", "print(f' Full-path Accuracy : {ev[\"full_accuracy\"]:.4f}')\n", "print(f' Full-path Macro-F1 : {ev[\"full_f1_macro\"]:.4f}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.5 — Model 2: Hierarchical TF-IDF + LinearSVC (Calibrated)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pipe_svm = Pipeline([\n", " ('tfidf', TfidfVectorizer(sublinear_tf=True, lowercase=True)),\n", " ('clf', LinearSVC(max_iter=3000, class_weight='balanced', random_state=RANDOM_STATE))\n", "])\n", "\n", "param_grid_svm = {\n", " 'tfidf__ngram_range' : [(1,1), (1,2)],\n", " 'tfidf__max_features' : [3000, 5000, 10000],\n", " 'tfidf__min_df' : [1, 2],\n", " 'clf__C' : [0.1, 1.0, 10.0],\n", "}\n", "\n", "t0 = time.time()\n", "gs_svm = GridSearchCV(pipe_svm, param_grid_svm,\n", " cv=cv_splitter, scoring='f1_macro',\n", " n_jobs=-1, verbose=1)\n", "gs_svm.fit(X_train, y_type_train)\n", "print(f'\\nSVM stage-1 grid search | time: {time.time()-t0:.1f}s')\n", "print(f'Best Stage-1 CV Macro-F1: {gs_svm.best_score_:.4f}')\n", "print(f'Best params : {gs_svm.best_params_}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Build hierarchical model with CALIBRATED sub-classifiers (for probabilities)\n", "best_params_svm = gs_svm.best_params_\n", "\n", "def make_svm_pipeline():\n", " base = Pipeline([\n", " ('tfidf', TfidfVectorizer(\n", " ngram_range=best_params_svm['tfidf__ngram_range'],\n", " max_features=best_params_svm['tfidf__max_features'],\n", " min_df=best_params_svm['tfidf__min_df'],\n", " sublinear_tf=True, lowercase=True,\n", " )),\n", " ('clf', LinearSVC(\n", " C=best_params_svm['clf__C'], max_iter=3000,\n", " class_weight='balanced', random_state=RANDOM_STATE,\n", " )),\n", " ])\n", " # Wrap with calibration so we get predict_proba\n", " return CalibratedClassifierCV(base, method='sigmoid', cv=3)\n", "\n", "t0 = time.time()\n", "hmodel_svm = HierarchicalTextClassifier(make_svm_pipeline)\n", "hmodel_svm.fit(X_train, y_type_train, y_cluster_train)\n", "print(f'Hierarchical calibrated SVM trained in {time.time()-t0:.1f}s')\n", "\n", "ev = evaluate_hierarchical(hmodel_svm, X_test, y_type_test, y_cluster_test)\n", "print(f' Type Accuracy : {ev[\"type_accuracy\"]:.4f}')\n", "print(f' Type Macro-F1 : {ev[\"type_f1_macro\"]:.4f}')\n", "print(f' Full-path Accuracy : {ev[\"full_accuracy\"]:.4f}')\n", "print(f' Full-path Macro-F1 : {ev[\"full_f1_macro\"]:.4f}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.6 — Model 3: Hierarchical TF-IDF + Random Forest" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pipe_rf = Pipeline([\n", " ('tfidf', TfidfVectorizer(sublinear_tf=True, lowercase=True)),\n", " ('clf', RandomForestClassifier(class_weight='balanced', random_state=RANDOM_STATE, n_jobs=-1))\n", "])\n", "\n", "param_grid_rf = {\n", " 'tfidf__ngram_range' : [(1,1), (1,2)],\n", " 'tfidf__max_features' : [3000, 5000],\n", " 'clf__n_estimators' : [200, 400],\n", " 'clf__max_depth' : [None, 40],\n", " 'clf__min_samples_split' : [2, 5],\n", "}\n", "\n", "t0 = time.time()\n", "gs_rf = GridSearchCV(pipe_rf, param_grid_rf,\n", " cv=cv_splitter, scoring='f1_macro',\n", " n_jobs=-1, verbose=1)\n", "gs_rf.fit(X_train, y_type_train)\n", "print(f'\\nRF stage-1 grid search | time: {time.time()-t0:.1f}s')\n", "print(f'Best Stage-1 CV Macro-F1: {gs_rf.best_score_:.4f}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "best_params_rf = gs_rf.best_params_\n", "\n", "def make_rf_pipeline():\n", " return Pipeline([\n", " ('tfidf', TfidfVectorizer(\n", " ngram_range=best_params_rf['tfidf__ngram_range'],\n", " max_features=best_params_rf['tfidf__max_features'],\n", " sublinear_tf=True, lowercase=True,\n", " )),\n", " ('clf', RandomForestClassifier(\n", " n_estimators=best_params_rf['clf__n_estimators'],\n", " max_depth=best_params_rf['clf__max_depth'],\n", " min_samples_split=best_params_rf['clf__min_samples_split'],\n", " class_weight='balanced', random_state=RANDOM_STATE, n_jobs=-1,\n", " )),\n", " ])\n", "\n", "t0 = time.time()\n", "hmodel_rf = HierarchicalTextClassifier(make_rf_pipeline)\n", "hmodel_rf.fit(X_train, y_type_train, y_cluster_train)\n", "print(f'Hierarchical RF trained in {time.time()-t0:.1f}s')\n", "\n", "ev = evaluate_hierarchical(hmodel_rf, X_test, y_type_test, y_cluster_test)\n", "print(f' Type Accuracy : {ev[\"type_accuracy\"]:.4f}')\n", "print(f' Type Macro-F1 : {ev[\"type_f1_macro\"]:.4f}')\n", "print(f' Full-path Accuracy : {ev[\"full_accuracy\"]:.4f}')\n", "print(f' Full-path Macro-F1 : {ev[\"full_f1_macro\"]:.4f}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.7 — Model 4: Hierarchical Sentence-Transformer Embeddings + LogReg" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('Loading all-MiniLM-L6-v2...')\n", "encoder = SentenceTransformer('all-MiniLM-L6-v2', device=str(DEVICE))\n", "print(f'Embedding dimension: {encoder.get_sentence_embedding_dimension()}')\n", "\n", "t0 = time.time()\n", "X_train_emb = encoder.encode(list(X_train), show_progress_bar=True,\n", " convert_to_numpy=True, batch_size=64)\n", "X_test_emb = encoder.encode(list(X_test), show_progress_bar=True,\n", " convert_to_numpy=True, batch_size=64)\n", "print(f'Encoded in {time.time()-t0:.1f}s')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Tune stage-1 classifier on embeddings\n", "param_grid_emb = {\n", " 'C' : [0.1, 1.0, 10.0, 50.0],\n", " 'solver' : ['lbfgs'],\n", " 'class_weight': ['balanced'],\n", "}\n", "\n", "t0 = time.time()\n", "gs_emb = GridSearchCV(\n", " LogisticRegression(max_iter=3000, random_state=RANDOM_STATE),\n", " param_grid_emb, cv=cv_splitter, scoring='f1_macro', n_jobs=-1, verbose=1\n", ")\n", "gs_emb.fit(X_train_emb, y_type_train)\n", "print(f'\\nEmb+LogReg stage-1 grid search | time: {time.time()-t0:.1f}s')\n", "print(f'Best Stage-1 CV Macro-F1: {gs_emb.best_score_:.4f}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Build hierarchical embedding model — works on already-encoded vectors\n", "best_C_emb = gs_emb.best_params_['C']\n", "\n", "class HierarchicalEmbeddingClassifier:\n", " \"\"\"Hierarchical classifier that operates on pre-computed embeddings.\"\"\"\n", " def __init__(self, C=1.0):\n", " self.C = C\n", "\n", " def fit(self, X_emb, y_type, y_cluster):\n", " self.stage1_ = LogisticRegression(C=self.C, max_iter=3000,\n", " class_weight='balanced',\n", " random_state=RANDOM_STATE)\n", " self.stage1_.fit(X_emb, y_type)\n", "\n", " self.stage2_ = {}\n", " self.type_to_clusters_ = {}\n", " for t in sorted(np.unique(y_type)):\n", " mask = y_type == t\n", " clusters_in_type = np.unique(y_cluster[mask])\n", " self.type_to_clusters_[t] = list(clusters_in_type)\n", " if len(clusters_in_type) == 1:\n", " self.stage2_[t] = None\n", " else:\n", " clf = LogisticRegression(C=self.C, max_iter=3000,\n", " class_weight='balanced',\n", " random_state=RANDOM_STATE)\n", " clf.fit(X_emb[mask], y_cluster[mask])\n", " self.stage2_[t] = clf\n", " return self\n", "\n", " def predict_type(self, X_emb):\n", " return self.stage1_.predict(X_emb)\n", "\n", " def predict_cluster(self, X_emb, predicted_types=None):\n", " if predicted_types is None:\n", " predicted_types = self.predict_type(X_emb)\n", " clusters = np.empty(len(X_emb), dtype=object)\n", " for t in np.unique(predicted_types):\n", " mask = predicted_types == t\n", " if self.stage2_.get(t) is None:\n", " clusters[mask] = self.type_to_clusters_[t][0]\n", " else:\n", " clusters[mask] = self.stage2_[t].predict(X_emb[mask])\n", " return clusters\n", "\n", " def predict_type_proba(self, X_emb):\n", " return self.stage1_.predict_proba(X_emb)\n", "\n", "\n", "t0 = time.time()\n", "hmodel_emb = HierarchicalEmbeddingClassifier(C=best_C_emb)\n", "hmodel_emb.fit(X_train_emb, y_type_train, y_cluster_train)\n", "print(f'Hierarchical Embedding model trained in {time.time()-t0:.1f}s')\n", "\n", "# Evaluate\n", "def evaluate_hierarchical_emb(model, X_emb, y_type_true, y_cluster_true):\n", " y_type_pred = model.predict_type(X_emb)\n", " y_cluster_pred = model.predict_cluster(X_emb, y_type_pred)\n", " type_acc = accuracy_score(y_type_true, y_type_pred)\n", " type_f1 = f1_score(y_type_true, y_type_pred, average='macro', zero_division=0)\n", " full_acc = ((y_type_pred == y_type_true) & (y_cluster_pred == y_cluster_true)).mean()\n", " composite_true = np.array([f'{t}||{c}' for t, c in zip(y_type_true, y_cluster_true)])\n", " composite_pred = np.array([f'{t}||{c}' for t, c in zip(y_type_pred, y_cluster_pred)])\n", " full_f1 = f1_score(composite_true, composite_pred, average='macro', zero_division=0)\n", " return {\n", " 'type_accuracy' : type_acc,\n", " 'type_f1_macro' : type_f1,\n", " 'full_accuracy' : full_acc,\n", " 'full_f1_macro' : full_f1,\n", " 'y_type_pred' : y_type_pred,\n", " 'y_cluster_pred' : y_cluster_pred,\n", " }\n", "\n", "ev = evaluate_hierarchical_emb(hmodel_emb, X_test_emb, y_type_test, y_cluster_test)\n", "print(f' Type Accuracy : {ev[\"type_accuracy\"]:.4f}')\n", "print(f' Type Macro-F1 : {ev[\"type_f1_macro\"]:.4f}')\n", "print(f' Full-path Accuracy : {ev[\"full_accuracy\"]:.4f}')\n", "print(f' Full-path Macro-F1 : {ev[\"full_f1_macro\"]:.4f}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.8 — Model 5: Hierarchical Fine-Tuned DistilBERT\n", "\n", "We train one DistilBERT for Stage 1 (8-class objection type prediction). For each objection type with >1 cluster, we fine-tune a separate smaller DistilBERT for stage-2 cluster classification. GPU recommended." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# DistilBERT dataset\n", "MODEL_NAME = 'distilbert-base-uncased'\n", "MAX_LENGTH = 128\n", "BATCH_SIZE = 32\n", "EPOCHS = 3\n", "LEARNING_RATE = 2e-5\n", "\n", "class QuoteDataset(Dataset):\n", " def __init__(self, texts, labels, tokenizer, max_len=128):\n", " self.texts = list(texts)\n", " self.labels = list(labels)\n", " self.tokenizer = tokenizer\n", " self.max_len = max_len\n", "\n", " def __len__(self):\n", " return len(self.texts)\n", "\n", " def __getitem__(self, idx):\n", " enc = self.tokenizer(\n", " str(self.texts[idx]), truncation=True, padding='max_length',\n", " max_length=self.max_len, return_tensors='pt'\n", " )\n", " return {\n", " 'input_ids' : enc['input_ids'].squeeze(0),\n", " 'attention_mask' : enc['attention_mask'].squeeze(0),\n", " 'label' : torch.tensor(self.labels[idx], dtype=torch.long),\n", " }\n", "\n", "\n", "def train_bert_classifier(X_train_text, y_train_labels, epochs=EPOCHS, label_tag=''):\n", " \"\"\"Fine-tune a DistilBERT classification head. Returns model, tokenizer, label_encoder.\"\"\"\n", " from sklearn.preprocessing import LabelEncoder\n", " label_encoder = LabelEncoder()\n", " y_tr = label_encoder.fit_transform(y_train_labels)\n", " n_classes = len(label_encoder.classes_)\n", "\n", " tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)\n", " model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME, num_labels=n_classes).to(DEVICE)\n", "\n", " train_ds = QuoteDataset(X_train_text, y_tr, tokenizer, MAX_LENGTH)\n", " train_loader = DataLoader(train_ds, batch_size=BATCH_SIZE, shuffle=True)\n", "\n", " optimizer = AdamW(model.parameters(), lr=LEARNING_RATE, weight_decay=0.01)\n", " total_steps = len(train_loader) * epochs\n", " scheduler = get_linear_schedule_with_warmup(\n", " optimizer, num_warmup_steps=int(0.1 * total_steps), num_training_steps=total_steps)\n", "\n", " model.train()\n", " for epoch in range(epochs):\n", " epoch_loss = 0.0\n", " correct = 0\n", " total = 0\n", " for batch in train_loader:\n", " input_ids = batch['input_ids'].to(DEVICE)\n", " attention_mask = batch['attention_mask'].to(DEVICE)\n", " labels = batch['label'].to(DEVICE)\n", "\n", " optimizer.zero_grad()\n", " outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)\n", " loss = outputs.loss\n", " loss.backward()\n", " torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n", " optimizer.step()\n", " scheduler.step()\n", "\n", " epoch_loss += loss.item()\n", " preds = outputs.logits.argmax(dim=1)\n", " correct += (preds == labels).sum().item()\n", " total += labels.size(0)\n", " print(f' [{label_tag}] Epoch {epoch+1}/{epochs} | loss={epoch_loss/len(train_loader):.4f} | acc={correct/total:.4f}')\n", "\n", " return model, tokenizer, label_encoder\n", "\n", "\n", "def predict_bert(model, tokenizer, label_encoder, texts, batch_size=64):\n", " \"\"\"Run inference with a fine-tuned DistilBERT.\"\"\"\n", " model.eval()\n", " ds = QuoteDataset(texts, [0]*len(texts), tokenizer, MAX_LENGTH)\n", " loader = DataLoader(ds, batch_size=batch_size, shuffle=False)\n", " all_preds = []\n", " with torch.no_grad():\n", " for batch in loader:\n", " input_ids = batch['input_ids'].to(DEVICE)\n", " attention_mask = batch['attention_mask'].to(DEVICE)\n", " outputs = model(input_ids=input_ids, attention_mask=attention_mask)\n", " preds = outputs.logits.argmax(dim=1).cpu().numpy()\n", " all_preds.append(preds)\n", " all_preds = np.concatenate(all_preds)\n", " return label_encoder.inverse_transform(all_preds)\n", "\n", "print('DistilBERT training helpers defined.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ---- Stage 1: Fine-tune DistilBERT for objection type ----\n", "print('=' * 60)\n", "print('Stage 1 — DistilBERT on Objection Type')\n", "print('=' * 60)\n", "t0 = time.time()\n", "bert_stage1_model, bert_stage1_tok, bert_stage1_le = train_bert_classifier(\n", " X_raw_train, y_type_train, epochs=EPOCHS, label_tag='Type'\n", ")\n", "print(f'Stage 1 training time: {time.time()-t0:.1f}s')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ---- Stage 2: Fine-tune per-type DistilBERT for cluster ----\n", "print('=' * 60)\n", "print('Stage 2 — DistilBERT per objection type')\n", "print('=' * 60)\n", "\n", "bert_stage2_models = {}\n", "bert_stage2_type_to_clusters = {}\n", "\n", "for t in sorted(np.unique(y_type_train)):\n", " mask = y_type_train == t\n", " clusters_in_type = np.unique(y_cluster_train[mask])\n", " bert_stage2_type_to_clusters[t] = list(clusters_in_type)\n", "\n", " if len(clusters_in_type) == 1:\n", " print(f'\\n> {t}: only 1 cluster ({clusters_in_type[0]}) — no stage-2 model needed.')\n", " bert_stage2_models[t] = None\n", " continue\n", "\n", " print(f'\\n> {t}: {len(clusters_in_type)} clusters, training...')\n", " t0 = time.time()\n", " # Use fewer epochs for stage-2 to save time (smaller per-type datasets)\n", " stage2_epochs = 3\n", " m, tok, le = train_bert_classifier(\n", " X_raw_train[mask], y_cluster_train[mask],\n", " epochs=stage2_epochs, label_tag=f'{t[:15]}'\n", " )\n", " bert_stage2_models[t] = {'model': m, 'tokenizer': tok, 'label_encoder': le}\n", " print(f' Training time: {time.time()-t0:.1f}s')\n", "\n", "print('\\n=== Stage 2 training complete ===')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ---- Hierarchical DistilBERT inference & evaluation ----\n", "def bert_hierarchical_predict(X_text):\n", " \"\"\"Run full two-stage DistilBERT inference.\"\"\"\n", " # Stage 1\n", " type_preds = predict_bert(bert_stage1_model, bert_stage1_tok, bert_stage1_le, X_text)\n", " # Stage 2\n", " cluster_preds = np.empty(len(X_text), dtype=object)\n", " for t in np.unique(type_preds):\n", " mask = type_preds == t\n", " if bert_stage2_models.get(t) is None:\n", " cluster_preds[mask] = bert_stage2_type_to_clusters[t][0]\n", " else:\n", " s2 = bert_stage2_models[t]\n", " cluster_preds[mask] = predict_bert(\n", " s2['model'], s2['tokenizer'], s2['label_encoder'], X_text[mask]\n", " )\n", " return type_preds, cluster_preds\n", "\n", "\n", "t0 = time.time()\n", "bert_type_preds, bert_cluster_preds = bert_hierarchical_predict(X_raw_test)\n", "print(f'DistilBERT hierarchical inference time: {time.time()-t0:.1f}s')\n", "\n", "type_acc = accuracy_score(y_type_test, bert_type_preds)\n", "type_f1 = f1_score(y_type_test, bert_type_preds, average='macro', zero_division=0)\n", "full_acc = ((bert_type_preds == y_type_test) & (bert_cluster_preds == y_cluster_test)).mean()\n", "composite_true = np.array([f'{t}||{c}' for t, c in zip(y_type_test, y_cluster_test)])\n", "composite_pred = np.array([f'{t}||{c}' for t, c in zip(bert_type_preds, bert_cluster_preds)])\n", "full_f1 = f1_score(composite_true, composite_pred, average='macro', zero_division=0)\n", "\n", "print(f' Type Accuracy : {type_acc:.4f}')\n", "print(f' Type Macro-F1 : {type_f1:.4f}')\n", "print(f' Full-path Accuracy : {full_acc:.4f}')\n", "print(f' Full-path Macro-F1 : {full_f1:.4f}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.9 — TF-IDF Feature Ablation Study\n", "\n", "Justify the chosen TF-IDF settings by comparing variants on the Stage-1 task. Same analysis as v2 — stage-1 performance is a reliable proxy for feature quality." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sklearn.model_selection import cross_val_score\n", "\n", "best_C = best_params_logreg['clf__C']\n", "\n", "ablation_configs = [\n", " {'name': 'Unigrams only', 'ngram_range': (1,1), 'analyzer': 'word', 'sublinear_tf': True, 'max_features': 5000},\n", " {'name': 'Unigrams + Bigrams', 'ngram_range': (1,2), 'analyzer': 'word', 'sublinear_tf': True, 'max_features': 5000},\n", " {'name': 'Uni+Bi+Trigrams', 'ngram_range': (1,3), 'analyzer': 'word', 'sublinear_tf': True, 'max_features': 5000},\n", " {'name': 'No sublinear_tf', 'ngram_range': (1,2), 'analyzer': 'word', 'sublinear_tf': False, 'max_features': 5000},\n", " {'name': 'Character n-grams (3-5)','ngram_range': (3,5), 'analyzer': 'char_wb', 'sublinear_tf': True, 'max_features': 5000},\n", "]\n", "\n", "ablation_results = []\n", "for cfg in ablation_configs:\n", " pipe = Pipeline([\n", " ('tfidf', TfidfVectorizer(\n", " ngram_range=cfg['ngram_range'],\n", " analyzer=cfg['analyzer'],\n", " sublinear_tf=cfg['sublinear_tf'],\n", " max_features=cfg['max_features'],\n", " lowercase=True, min_df=2,\n", " )),\n", " ('clf', LogisticRegression(max_iter=2000, class_weight='balanced',\n", " C=best_C, random_state=RANDOM_STATE)),\n", " ])\n", " scores = cross_val_score(pipe, X_train, y_type_train, cv=cv_splitter,\n", " scoring='f1_macro', n_jobs=-1)\n", " ablation_results.append({\n", " 'Feature Config': cfg['name'],\n", " 'CV Macro-F1' : scores.mean(),\n", " 'CV Std' : scores.std(),\n", " })\n", " print(f\" {cfg['name']:30s} | {scores.mean():.4f} +- {scores.std():.4f}\")\n", "\n", "ablation_df = pd.DataFrame(ablation_results).sort_values('CV Macro-F1', ascending=False).reset_index(drop=True)\n", "print('\\nAblation ranking (on Stage-1 task):')\n", "print(ablation_df.round(4).to_string(index=False))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.10 — Learning Curves" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sklearn.model_selection import learning_curve\n", "\n", "LC_FOLDS = 5\n", "max_per_fold = int(len(X_train) * (LC_FOLDS - 1) / LC_FOLDS)\n", "train_sizes_abs = [100, 250, 500, 1000, 2000, min(3000, max_per_fold - 50)]\n", "train_sizes_abs = [s for s in train_sizes_abs if s < max_per_fold]\n", "print(f'Using train sizes: {train_sizes_abs}')\n", "\n", "best_pipe = make_logreg_pipeline()\n", "\n", "t0 = time.time()\n", "sizes, train_scores, val_scores = learning_curve(\n", " best_pipe, X_train, y_type_train,\n", " train_sizes=train_sizes_abs, cv=LC_FOLDS,\n", " scoring='f1_macro', n_jobs=-1, random_state=RANDOM_STATE,\n", ")\n", "print(f'Learning curve computed in {time.time()-t0:.1f}s')\n", "\n", "train_mean, train_std = train_scores.mean(axis=1), train_scores.std(axis=1)\n", "val_mean, val_std = val_scores.mean(axis=1), val_scores.std(axis=1)\n", "\n", "fig, ax = plt.subplots(figsize=(10, 6))\n", "ax.plot(sizes, train_mean, 'o-', color='#2E86AB', label='Training Macro-F1')\n", "ax.fill_between(sizes, train_mean - train_std, train_mean + train_std, color='#2E86AB', alpha=0.2)\n", "ax.plot(sizes, val_mean, 's-', color='#E07A5F', label='Validation Macro-F1')\n", "ax.fill_between(sizes, val_mean - val_std, val_mean + val_std, color='#E07A5F', alpha=0.2)\n", "ax.set_xlabel('Training Set Size')\n", "ax.set_ylabel('Macro-F1 (Stage-1)')\n", "ax.set_title('Learning Curve — Hierarchical LogReg (Stage-1 Task)')\n", "ax.legend(loc='lower right')\n", "ax.grid(alpha=0.3)\n", "plt.tight_layout()\n", "plt.savefig(ARTIFACTS_DIR / 'fig_4_10_learning_curve.png', dpi=150, bbox_inches='tight')\n", "plt.show()\n", "\n", "final_slope = (val_mean[-1] - val_mean[-2]) / (sizes[-1] - sizes[-2])\n", "print(f'\\nFinal slope: {final_slope:.6f}')\n", "print('Curve plateau' if final_slope < 1e-4 else 'Still rising — more data could help.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.11 — Consolidated CV Results" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cv_results = pd.DataFrame([\n", " {'Model': 'H-LogReg', 'Stage1_CV_F1': gs_logreg.best_score_},\n", " {'Model': 'H-SVM', 'Stage1_CV_F1': gs_svm.best_score_},\n", " {'Model': 'H-RF', 'Stage1_CV_F1': gs_rf.best_score_},\n", " {'Model': 'H-Embeddings','Stage1_CV_F1': gs_emb.best_score_},\n", " {'Model': 'H-DistilBERT','Stage1_CV_F1': np.nan}, # no CV for BERT (too expensive)\n", "])\n", "cv_results = cv_results.sort_values('Stage1_CV_F1', ascending=False).reset_index(drop=True)\n", "print('Stage-1 Cross-Validation Ranking:')\n", "print(cv_results.round(4).to_string(index=False))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Chapter 5 — Evaluation and Model Selection" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.1 — Held-Out Test Evaluation" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Evaluate all 5 hierarchical models on the held-out test set\n", "results = {}\n", "\n", "# Classical models operate on X_test (preprocessed text)\n", "results['H-LogReg'] = evaluate_hierarchical(hmodel_logreg, X_test, y_type_test, y_cluster_test)\n", "results['H-SVM'] = evaluate_hierarchical(hmodel_svm, X_test, y_type_test, y_cluster_test)\n", "results['H-RF'] = evaluate_hierarchical(hmodel_rf, X_test, y_type_test, y_cluster_test)\n", "results['H-Embeddings'] = evaluate_hierarchical_emb(hmodel_emb, X_test_emb, y_type_test, y_cluster_test)\n", "\n", "# DistilBERT uses raw text\n", "results['H-DistilBERT'] = {\n", " 'type_accuracy' : accuracy_score(y_type_test, bert_type_preds),\n", " 'type_f1_macro' : f1_score(y_type_test, bert_type_preds, average='macro', zero_division=0),\n", " 'full_accuracy' : ((bert_type_preds == y_type_test) & (bert_cluster_preds == y_cluster_test)).mean(),\n", " 'full_f1_macro' : f1_score(\n", " np.array([f'{t}||{c}' for t, c in zip(y_type_test, y_cluster_test)]),\n", " np.array([f'{t}||{c}' for t, c in zip(bert_type_preds, bert_cluster_preds)]),\n", " average='macro', zero_division=0),\n", " 'y_type_pred' : bert_type_preds,\n", " 'y_cluster_pred' : bert_cluster_preds,\n", "}\n", "\n", "# Summary table\n", "summary = pd.DataFrame([\n", " {\n", " 'Model' : name,\n", " 'Type Accuracy' : r['type_accuracy'],\n", " 'Type Macro-F1' : r['type_f1_macro'],\n", " 'Full-path Accuracy' : r['full_accuracy'],\n", " 'Full-path Macro-F1' : r['full_f1_macro'],\n", " }\n", " for name, r in results.items()\n", "])\n", "summary = summary.sort_values('Full-path Macro-F1', ascending=False).reset_index(drop=True)\n", "\n", "print('=' * 80)\n", "print('HELD-OUT TEST RESULTS (HIERARCHICAL)')\n", "print('=' * 80)\n", "print(summary.round(4).to_string(index=False))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.2 — Model Comparison Visualization" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig, axes = plt.subplots(1, 2, figsize=(18, 6))\n", "width = 0.35\n", "\n", "# Left: Type-level accuracy + F1\n", "x = np.arange(len(summary))\n", "axes[0].bar(x - width/2, summary['Type Accuracy'], width, label='Accuracy', color='#2E86AB')\n", "axes[0].bar(x + width/2, summary['Type Macro-F1'], width, label='Macro-F1', color='#E07A5F')\n", "axes[0].set_title('Stage-1: Objection Type Level', fontsize=13)\n", "axes[0].set_xticks(x)\n", "axes[0].set_xticklabels(summary['Model'], rotation=20, ha='right')\n", "axes[0].set_ylim(0, 1.05)\n", "axes[0].set_ylabel('Score')\n", "axes[0].legend(loc='lower right')\n", "axes[0].grid(axis='y', alpha=0.3)\n", "for c in axes[0].containers:\n", " axes[0].bar_label(c, fmt='%.3f', padding=3, fontsize=8)\n", "\n", "# Right: Full-path (both type and cluster correct)\n", "axes[1].bar(x - width/2, summary['Full-path Accuracy'], width, label='Accuracy', color='#2E86AB')\n", "axes[1].bar(x + width/2, summary['Full-path Macro-F1'], width, label='Macro-F1', color='#E07A5F')\n", "axes[1].set_title('Full-Path: Type + Cluster both correct', fontsize=13)\n", "axes[1].set_xticks(x)\n", "axes[1].set_xticklabels(summary['Model'], rotation=20, ha='right')\n", "axes[1].set_ylim(0, 1.05)\n", "axes[1].set_ylabel('Score')\n", "axes[1].legend(loc='lower right')\n", "axes[1].grid(axis='y', alpha=0.3)\n", "for c in axes[1].containers:\n", " axes[1].bar_label(c, fmt='%.3f', padding=3, fontsize=8)\n", "\n", "plt.suptitle('Hierarchical Model Comparison', fontsize=14, fontweight='bold', y=1.02)\n", "plt.tight_layout()\n", "plt.savefig(ARTIFACTS_DIR / 'fig_5_2_model_comparison.png', dpi=150, bbox_inches='tight')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.3 — McNemar's Significance Testing (Full-path)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from scipy.stats import binomtest\n", "\n", "def mcnemar_test(y_true_composite, pred1_composite, pred2_composite):\n", " only1 = int(np.sum((pred1_composite == y_true_composite) & (pred2_composite != y_true_composite)))\n", " only2 = int(np.sum((pred1_composite != y_true_composite) & (pred2_composite == y_true_composite)))\n", " n_disc = only1 + only2\n", " if n_disc == 0:\n", " return 1.0\n", " return binomtest(only1, n_disc, p=0.5, alternative='two-sided').pvalue\n", "\n", "# Compose true and predicted composite labels\n", "composite_true = np.array([f'{t}||{c}' for t, c in zip(y_type_test, y_cluster_test)])\n", "\n", "model_composite_preds = {}\n", "for name, r in results.items():\n", " cp = np.array([f'{t}||{c}' for t, c in zip(r['y_type_pred'], r['y_cluster_pred'])])\n", " model_composite_preds[name] = cp\n", "\n", "# Pairwise p-values\n", "model_names = list(results.keys())\n", "sig_matrix = pd.DataFrame(index=model_names, columns=model_names, dtype=float)\n", "for a in model_names:\n", " for b in model_names:\n", " if a == b:\n", " sig_matrix.loc[a, b] = np.nan\n", " else:\n", " sig_matrix.loc[a, b] = mcnemar_test(composite_true,\n", " model_composite_preds[a],\n", " model_composite_preds[b])\n", "\n", "display_matrix = sig_matrix.astype(float)\n", "annot_matrix = display_matrix.apply(\n", " lambda col: col.map(lambda v: 'ns' if (np.isnan(v) or v >= 0.05) else f'p={v:.3f}')\n", ")\n", "\n", "fig, ax = plt.subplots(figsize=(9, 7))\n", "sns.heatmap(display_matrix, annot=annot_matrix, fmt='', cmap='RdYlGn_r',\n", " vmin=0, vmax=0.1, ax=ax,\n", " cbar_kws={'label': 'p-value (<0.05 = significant)'})\n", "ax.set_title(\"McNemar's Test — Full-Path Pairwise Significance\\n'ns' = not significant\", fontsize=11)\n", "plt.xticks(rotation=20, ha='right')\n", "plt.yticks(rotation=0)\n", "plt.tight_layout()\n", "plt.savefig(ARTIFACTS_DIR / 'fig_5_3_mcnemar.png', dpi=150, bbox_inches='tight')\n", "plt.show()\n", "\n", "best_model_name = summary.iloc[0]['Model']\n", "print(f'\\nSignificance of winner ({best_model_name}) vs others:')\n", "for other in model_names:\n", " if other == best_model_name:\n", " continue\n", " pval = sig_matrix.loc[best_model_name, other]\n", " verdict = 'SIGNIFICANT' if (not np.isnan(pval) and pval < 0.05) else 'not significant'\n", " print(f' vs {other:15s} | p={pval:.4f} | {verdict}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.4 — Confusion Matrices (Stage 1 and Stage 2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Stage 1 confusion (objection type) for best model\n", "best_result = results[best_model_name]\n", "labels_type = sorted(np.unique(np.concatenate([y_type_train, y_type_test])))\n", "cm_type = confusion_matrix(y_type_test, best_result['y_type_pred'], labels=labels_type)\n", "\n", "fig, ax = plt.subplots(figsize=(10, 8))\n", "sns.heatmap(cm_type, annot=True, fmt='d', cmap='Blues', ax=ax,\n", " xticklabels=labels_type, yticklabels=labels_type,\n", " cbar_kws={'label': 'Count'}, linewidths=0.3)\n", "ax.set_title(f'Stage-1 Confusion Matrix — {best_model_name} (Objection Type)', fontsize=13, pad=15)\n", "ax.set_xlabel('Predicted')\n", "ax.set_ylabel('True')\n", "plt.xticks(rotation=45, ha='right')\n", "plt.yticks(rotation=0)\n", "plt.tight_layout()\n", "plt.savefig(ARTIFACTS_DIR / 'fig_5_4a_confusion_type.png', dpi=150, bbox_inches='tight')\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Full-path confusion on composite labels\n", "pair_labels = sorted(set([f'{t}||{c}' for t, c in zip(np.concatenate([y_type_train, y_type_test]),\n", " np.concatenate([y_cluster_train, y_cluster_test]))]))\n", "cm_full = confusion_matrix(composite_true, model_composite_preds[best_model_name], labels=pair_labels)\n", "\n", "fig, ax = plt.subplots(figsize=(16, 14))\n", "# For readability shorten labels\n", "short_labels = [p.replace('||', ' / ') for p in pair_labels]\n", "sns.heatmap(cm_full, annot=True, fmt='d', cmap='Blues', ax=ax,\n", " xticklabels=short_labels, yticklabels=short_labels,\n", " cbar_kws={'label': 'Count'}, linewidths=0.2, annot_kws={'size': 7})\n", "ax.set_title(f'Full-Path Confusion Matrix — {best_model_name}', fontsize=13, pad=15)\n", "ax.set_xlabel('Predicted (type / cluster)')\n", "ax.set_ylabel('True (type / cluster)')\n", "plt.xticks(rotation=60, ha='right', fontsize=8)\n", "plt.yticks(rotation=0, fontsize=8)\n", "plt.tight_layout()\n", "plt.savefig(ARTIFACTS_DIR / 'fig_5_4b_confusion_full.png', dpi=150, bbox_inches='tight')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.5 — Per-Class Performance (Full-path)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(f'Full-path per-class classification report — {best_model_name}')\n", "print('=' * 80)\n", "print(classification_report(composite_true, model_composite_preds[best_model_name], zero_division=0))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Plot per-class F1\n", "report = classification_report(composite_true, model_composite_preds[best_model_name],\n", " output_dict=True, zero_division=0)\n", "per_class = pd.DataFrame(report).T\n", "per_class = per_class.drop(['accuracy', 'macro avg', 'weighted avg'], errors='ignore')\n", "per_class = per_class.sort_values('f1-score', ascending=True)\n", "per_class.index = [idx.replace('||', ' / ') for idx in per_class.index]\n", "\n", "fig, ax = plt.subplots(figsize=(11, 11))\n", "ax.barh(per_class.index, per_class['f1-score'],\n", " color=sns.color_palette('RdYlGn', n_colors=len(per_class)))\n", "ax.axvline(per_class['f1-score'].mean(), color='black', linestyle='--',\n", " label=f\"Mean F1 = {per_class['f1-score'].mean():.3f}\")\n", "ax.set_title(f'Per-Class F1 (Full-Path) — {best_model_name}', fontsize=13)\n", "ax.set_xlabel('F1 Score')\n", "ax.set_xlim(0, 1.05)\n", "ax.legend()\n", "for i, (idx, row) in enumerate(per_class.iterrows()):\n", " ax.text(row['f1-score'] + 0.01, i, f\"{row['f1-score']:.2f}\", va='center', fontsize=7)\n", "plt.tight_layout()\n", "plt.savefig(ARTIFACTS_DIR / 'fig_5_5_per_class_f1.png', dpi=150, bbox_inches='tight')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.6 — Stage-1 vs Stage-2 Error Decomposition\n", "\n", "Where does the best model fail? Errors can be attributed to:\n", "- **Stage-1 errors**: wrong objection type (automatically makes cluster wrong too).\n", "- **Stage-2-only errors**: correct type, wrong cluster within it.\n", "\n", "This decomposition is unique to hierarchical models and highlights where improvement effort should focus." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "stage1_correct = best_result['y_type_pred'] == y_type_test\n", "stage2_correct = best_result['y_cluster_pred'] == y_cluster_test\n", "\n", "stage1_wrong = (~stage1_correct).sum()\n", "stage2_only_wrong = (stage1_correct & ~stage2_correct).sum()\n", "both_correct = (stage1_correct & stage2_correct).sum()\n", "\n", "print(f'Error decomposition for {best_model_name}:')\n", "print(f' Both stages correct : {both_correct:4d} ({both_correct/len(y_type_test)*100:.1f}%)')\n", "print(f' Stage-1 wrong (any) : {stage1_wrong:4d} ({stage1_wrong/len(y_type_test)*100:.1f}%)')\n", "print(f' Stage-2 wrong only : {stage2_only_wrong:4d} ({stage2_only_wrong/len(y_type_test)*100:.1f}%)')\n", "print()\n", "print('Interpretation:')\n", "if stage1_wrong > stage2_only_wrong:\n", " print(' -> Most errors originate at Stage 1. Improving objection-type classification')\n", " print(' would yield the biggest downstream gain.')\n", "else:\n", " print(' -> Stage 1 works well; errors mostly arise in Stage 2 cluster disambiguation.')\n", "\n", "# Visualize\n", "fig, ax = plt.subplots(figsize=(8, 5))\n", "categories = ['Both correct', 'Stage-1 wrong', 'Stage-2 only wrong']\n", "values = [both_correct, stage1_wrong, stage2_only_wrong]\n", "colors = ['#6EC181', '#E24B4A', '#F2CC8F']\n", "ax.bar(categories, values, color=colors)\n", "for i, v in enumerate(values):\n", " ax.text(i, v + 5, str(v), ha='center', fontsize=11, fontweight='bold')\n", "ax.set_ylabel('Test examples')\n", "ax.set_title('Where do errors originate? (Stage 1 vs Stage 2)', fontsize=12)\n", "plt.tight_layout()\n", "plt.savefig(ARTIFACTS_DIR / 'fig_5_6_error_decomp.png', dpi=150, bbox_inches='tight')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.7 — Deep Error Analysis with Quote Inspection" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Top confusion pairs on full-path\n", "errors = []\n", "for idx in range(len(y_type_test)):\n", " if composite_true[idx] != model_composite_preds[best_model_name][idx]:\n", " errors.append({\n", " 'true' : composite_true[idx].replace('||', ' / '),\n", " 'predicted' : model_composite_preds[best_model_name][idx].replace('||', ' / '),\n", " 'quote' : X_raw_test[idx],\n", " })\n", "\n", "error_df = pd.DataFrame(errors)\n", "if len(error_df) == 0:\n", " print('Perfect classification — no errors on test set!')\n", "else:\n", " err_counts = error_df.groupby(['true', 'predicted']).size().reset_index(name='count')\n", " err_counts = err_counts.sort_values('count', ascending=False).reset_index(drop=True)\n", " print('Top 10 full-path confusion pairs:\\n')\n", " print(err_counts.head(10).to_string(index=False))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Inspect quotes from top confusion pairs\n", "if len(error_df) > 0:\n", " print('=' * 80)\n", " print('SAMPLE QUOTES FROM TOP CONFUSION PAIRS')\n", " print('=' * 80)\n", " for rank in range(min(3, len(err_counts))):\n", " row = err_counts.iloc[rank]\n", " true_pair, pred_pair = row['true'], row['predicted']\n", " mask = (error_df['true'] == true_pair) & (error_df['predicted'] == pred_pair)\n", " sample = error_df[mask].head(4)\n", " print(f'\\n#{rank+1}: True \"{true_pair}\" -> Predicted \"{pred_pair}\" ({row[\"count\"]} errors)')\n", " print('-' * 80)\n", " for q in sample['quote']:\n", " print(f' - {q}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.8 — Per-Class PR Curves (Stage 1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# PR curves at the objection type level using the calibrated SVM's probabilities\n", "fig, axes = plt.subplots(2, 4, figsize=(22, 10))\n", "axes = axes.flatten()\n", "\n", "# Use calibrated SVM stage-1 probabilities\n", "stage1_svm = hmodel_svm.stage1_\n", "svm_probs = stage1_svm.predict_proba(X_test)\n", "svm_classes = stage1_svm.classes_\n", "\n", "for i, ot in enumerate(sorted(labels_type)):\n", " if i >= len(axes):\n", " break\n", " class_idx = list(svm_classes).index(ot)\n", " y_bin = (y_type_test == ot).astype(int)\n", " y_score = svm_probs[:, class_idx]\n", "\n", " precision, recall, _ = precision_recall_curve(y_bin, y_score)\n", " ap = (precision * np.diff(np.concatenate([[0], recall]))).sum()\n", "\n", " axes[i].plot(recall, precision, linewidth=2, color='#2E86AB')\n", " axes[i].fill_between(recall, precision, alpha=0.2, color='#2E86AB')\n", " axes[i].set_title(f'{ot}\\nAP {ap:.3f}', fontsize=10)\n", " axes[i].set_xlabel('Recall')\n", " axes[i].set_ylabel('Precision')\n", " axes[i].set_xlim(0, 1.05)\n", " axes[i].set_ylim(0, 1.05)\n", " axes[i].grid(alpha=0.3)\n", "\n", "for j in range(i + 1, len(axes)):\n", " axes[j].axis('off')\n", "\n", "plt.suptitle('Stage-1 PR Curves (Calibrated SVM)', fontsize=13, fontweight='bold', y=1.01)\n", "plt.tight_layout()\n", "plt.savefig(ARTIFACTS_DIR / 'fig_5_8_pr_curves.png', dpi=150, bbox_inches='tight')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.9 — Inference Latency Benchmarking" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "BENCH_QUOTE = 'Your price is too expensive, can you give me a discount?'\n", "N_RUNS = 50\n", "\n", "def bench_hierarchical(model, X_example, uses_emb=False, is_bert=False):\n", " if is_bert:\n", " # Warmup\n", " for _ in range(5):\n", " bert_hierarchical_predict(np.array([BENCH_QUOTE]))\n", " t0 = time.time()\n", " for _ in range(N_RUNS):\n", " bert_hierarchical_predict(np.array([BENCH_QUOTE]))\n", " return (time.time() - t0) / N_RUNS * 1000\n", "\n", " if uses_emb:\n", " # Warmup\n", " for _ in range(5):\n", " emb = encoder.encode([BENCH_QUOTE], convert_to_numpy=True)\n", " _ = model.predict_type(emb)\n", " _ = model.predict_cluster(emb)\n", " t0 = time.time()\n", " for _ in range(N_RUNS):\n", " emb = encoder.encode([BENCH_QUOTE], convert_to_numpy=True)\n", " _ = model.predict_type(emb)\n", " _ = model.predict_cluster(emb)\n", " return (time.time() - t0) / N_RUNS * 1000\n", "\n", " # Classical: preprocess then predict\n", " for _ in range(5):\n", " cleaned = preprocess_text(BENCH_QUOTE)\n", " _ = model.predict(np.array([cleaned]))\n", " t0 = time.time()\n", " for _ in range(N_RUNS):\n", " cleaned = preprocess_text(BENCH_QUOTE)\n", " _ = model.predict(np.array([cleaned]))\n", " return (time.time() - t0) / N_RUNS * 1000\n", "\n", "\n", "bench_records = []\n", "bench_records.append(('H-LogReg', bench_hierarchical(hmodel_logreg, X_test)))\n", "bench_records.append(('H-SVM', bench_hierarchical(hmodel_svm, X_test)))\n", "bench_records.append(('H-RF', bench_hierarchical(hmodel_rf, X_test)))\n", "bench_records.append(('H-Embeddings', bench_hierarchical(hmodel_emb, X_test_emb, uses_emb=True)))\n", "bench_records.append((f'H-DistilBERT ({DEVICE})', bench_hierarchical(None, None, is_bert=True)))\n", "\n", "bench_df = pd.DataFrame(bench_records, columns=['Model', 'Latency (ms/predict)']).sort_values('Latency (ms/predict)')\n", "print(bench_df.round(2).to_string(index=False))\n", "\n", "fig, ax = plt.subplots(figsize=(10, 5))\n", "ax.barh(bench_df['Model'], bench_df['Latency (ms/predict)'],\n", " color=sns.color_palette('RdYlGn_r', len(bench_df)))\n", "ax.set_xlabel('Inference Latency (ms per prediction)')\n", "ax.set_title('Hierarchical Inference Latency')\n", "ax.axvline(1000, color='red', linestyle='--', label='1 second UX target')\n", "ax.legend()\n", "for i, (m, lat) in enumerate(zip(bench_df['Model'], bench_df['Latency (ms/predict)'])):\n", " ax.text(lat + 0.5, i, f'{lat:.1f} ms', va='center', fontsize=10)\n", "plt.tight_layout()\n", "plt.savefig(ARTIFACTS_DIR / 'fig_5_9_latency.png', dpi=150, bbox_inches='tight')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.10 — Top-3 Predictions with Confidence" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Use calibrated SVM's stage-1 probabilities for top-3 objection types\n", "def predict_top3_hierarchical(quote, svm_model):\n", " cleaned = preprocess_text(quote)\n", "\n", " # Stage-1 top-3 types\n", " stage1 = svm_model.stage1_\n", " probs = stage1.predict_proba(np.array([cleaned]))[0]\n", " classes = stage1.classes_\n", " top3_types_idx = probs.argsort()[-3:][::-1]\n", " top3_types = [(str(classes[i]), float(probs[i])) for i in top3_types_idx]\n", "\n", " # Stage-2 cluster for the TOP-1 type\n", " top_type = top3_types[0][0]\n", " if svm_model.stage2_[top_type] is None:\n", " top_cluster = svm_model.type_to_clusters_[top_type][0]\n", " top_cluster_conf = 1.0\n", " else:\n", " s2 = svm_model.stage2_[top_type]\n", " cp = s2.predict_proba(np.array([cleaned]))[0]\n", " cc = s2.classes_\n", " best_idx = int(np.argmax(cp))\n", " top_cluster = str(cc[best_idx])\n", " top_cluster_conf = float(cp[best_idx])\n", "\n", " return top3_types, top_cluster, top_cluster_conf\n", "\n", "\n", "demo_quotes = [\n", " 'Your price is too expensive, can you give me a discount?',\n", " 'If I do not go to your office, can we interview via Zoom?',\n", " 'My friend told me you have a low visa success rate, is it true?',\n", " 'I do not have a bank statement, what should I do?',\n", " 'I want to go work in Korea, can you help?',\n", "]\n", "\n", "print('Top-3 objection types + predicted cluster (calibrated SVM):')\n", "print('=' * 80)\n", "for q in demo_quotes:\n", " top3_types, cluster, cluster_conf = predict_top3_hierarchical(q, hmodel_svm)\n", " print(f'\\nQuote: {q}')\n", " for rank, (t, p) in enumerate(top3_types, 1):\n", " bar = '#' * int(p * 30)\n", " print(f' Type #{rank}. [{p:.0%}] {t:30s} {bar}')\n", " print(f' -> Predicted Cluster (within top-1 type): {cluster} ({cluster_conf:.0%})')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.11 — Out-of-Distribution Detection" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sklearn.metrics.pairwise import cosine_similarity\n", "\n", "# OOD threshold from training-set self-similarity\n", "train_self_sim = cosine_similarity(X_train_emb, X_train_emb)\n", "np.fill_diagonal(train_self_sim, 0)\n", "mean_sim = train_self_sim.max(axis=1).mean()\n", "std_sim = train_self_sim.max(axis=1).std()\n", "OOD_THRESHOLD = float(mean_sim - 2 * std_sim)\n", "\n", "print(f'Training self-similarity: mean={mean_sim:.4f}, std={std_sim:.4f}')\n", "print(f'OOD threshold : {OOD_THRESHOLD:.4f}')\n", "\n", "# Test set\n", "sim_to_train = cosine_similarity(X_test_emb, X_train_emb).max(axis=1)\n", "ood_flags = sim_to_train < OOD_THRESHOLD\n", "print(f'Test quotes flagged OOD : {ood_flags.sum()} / {len(sim_to_train)}')\n", "\n", "fig, ax = plt.subplots(figsize=(11, 5))\n", "ax.hist(sim_to_train, bins=40, color='#2E86AB', edgecolor='white', alpha=0.85, label='Test quotes')\n", "ax.axvline(OOD_THRESHOLD, color='red', linestyle='--', linewidth=2, label=f'OOD threshold ({OOD_THRESHOLD:.3f})')\n", "ax.set_title('Test Quote Similarity to Training Data')\n", "ax.set_xlabel('Max cosine similarity to any training quote')\n", "ax.set_ylabel('Frequency')\n", "ax.legend()\n", "plt.tight_layout()\n", "plt.savefig(ARTIFACTS_DIR / 'fig_5_11_ood.png', dpi=150, bbox_inches='tight')\n", "plt.show()\n", "\n", "# Demo\n", "def is_ood(quote, threshold=OOD_THRESHOLD):\n", " emb = encoder.encode([preprocess_text(quote)], convert_to_numpy=True)\n", " sim = float(cosine_similarity(emb, X_train_emb).max())\n", " return (sim < threshold, sim)\n", "\n", "ood_tests = [\n", " ('What is the weather in Phnom Penh today?', 'OOD'),\n", " ('Can you help me buy pizza?', 'OOD'),\n", " ('Your price is too expensive for me.', 'in-distribution'),\n", " ('I need help with my bank statement.', 'in-distribution'),\n", " ('Tell me a joke about cats.', 'OOD'),\n", " ('Brother, I worry the embassy will reject me.', 'in-distribution'),\n", "]\n", "\n", "print('\\nOOD detection demo:')\n", "for q, expected in ood_tests:\n", " ood, sim = is_ood(q)\n", " flag = 'OOD' if ood else 'IN-DIST'\n", " print(f' [{flag:7s}] sim={sim:.3f} | expected={expected:15s} | \"{q}\"')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.12 — Final Model Selection" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('=' * 80)\n", "print('FINAL MODEL SELECTION (HIERARCHICAL)')\n", "print('=' * 80)\n", "print(f'Winner : {best_model_name}')\n", "print(f'Type Accuracy : {best_result[\"type_accuracy\"]:.4f}')\n", "print(f'Type Macro-F1 : {best_result[\"type_f1_macro\"]:.4f}')\n", "print(f'Full-path Accuracy : {best_result[\"full_accuracy\"]:.4f}')\n", "print(f'Full-path Macro-F1 : {best_result[\"full_f1_macro\"]:.4f}')\n", "print()\n", "print('Decision rationale:')\n", "print(' - Selected by highest full-path Macro-F1 on held-out test set')\n", "print(\" - McNemar's test confirms significance against weaker baselines\")\n", "print(' - Latency benchmarks confirm the winner is deployable')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.13 — Save Artifacts for the Webapp" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# The webapp needs a classical model (to fit within memory limits).\n", "# We bundle the best CLASSICAL hierarchical model (excluding DistilBERT).\n", "classical_subset = summary[~summary['Model'].str.contains('DistilBERT')]\n", "best_classical_name = classical_subset.iloc[0]['Model']\n", "\n", "# Get the actual fitted model object\n", "classical_models = {\n", " 'H-LogReg' : hmodel_logreg,\n", " 'H-SVM' : hmodel_svm,\n", " 'H-RF' : hmodel_rf,\n", " 'H-Embeddings' : hmodel_emb,\n", "}\n", "best_classical_model = classical_models[best_classical_name]\n", "\n", "# Build type-to-clusters lookup (used by webapp for UI)\n", "cluster_to_type = dict()\n", "for t, c in zip(y_type_train, y_cluster_train):\n", " cluster_to_type[(t, c)] = t # key includes type to handle duplicates\n", "\n", "final_bundle = {\n", " # Headline model (reference only)\n", " 'best_model_name' : best_model_name,\n", "\n", " # Classical winner — used by webapp for inference\n", " 'classical_model_name' : best_classical_name,\n", " 'classical_model' : best_classical_model,\n", " 'classical_uses_embeddings': best_classical_name == 'H-Embeddings',\n", "\n", " # Calibrated SVM always saved (for top-3 probabilities)\n", " 'svm_cluster_calibrated' : hmodel_svm,\n", " 'svm_type_calibrated' : hmodel_svm, # same hierarchical model has both\n", " 'hierarchical_svm' : hmodel_svm,\n", "\n", " # Sentence encoder info (loaded by name at runtime)\n", " 'encoder_name' : 'all-MiniLM-L6-v2',\n", "\n", " # Labels\n", " 'type_labels' : sorted(np.unique(y_type_train)),\n", " 'cluster_labels' : sorted(np.unique(y_cluster_train)),\n", " 'type_to_clusters' : {t: sorted(np.unique(y_cluster_train[y_type_train == t])) for t in np.unique(y_type_train)},\n", "\n", " # OOD detection\n", " 'ood_threshold' : OOD_THRESHOLD,\n", " 'train_embeddings' : X_train_emb,\n", "\n", " # Reporting metrics\n", " 'test_metrics' : summary.to_dict('records'),\n", " 'latency_ms' : bench_df.to_dict('records'),\n", "}\n", "\n", "with open(ARTIFACTS_DIR / 'final_model.pkl', 'wb') as f:\n", " pickle.dump(final_bundle, f)\n", "\n", "# Save summary CSVs\n", "summary.round(4).to_csv(ARTIFACTS_DIR / 'ch5_summary.csv', index=False)\n", "ablation_df.round(4).to_csv(ARTIFACTS_DIR / 'ch4_ablation.csv', index=False)\n", "\n", "# Save DistilBERT models separately\n", "bert_dir = ARTIFACTS_DIR / 'distilbert_stage1'\n", "bert_dir.mkdir(exist_ok=True)\n", "bert_stage1_model.save_pretrained(bert_dir)\n", "bert_stage1_tok.save_pretrained(bert_dir)\n", "with open(bert_dir / 'label_encoder.pkl', 'wb') as f:\n", " pickle.dump(bert_stage1_le, f)\n", "print(f'Saved DistilBERT stage-1 -> {bert_dir}')\n", "\n", "for t, s2 in bert_stage2_models.items():\n", " if s2 is None:\n", " continue\n", " safe_t = re.sub(r'[^a-zA-Z0-9]+', '_', t)\n", " tdir = ARTIFACTS_DIR / f'distilbert_stage2_{safe_t}'\n", " tdir.mkdir(exist_ok=True)\n", " s2['model'].save_pretrained(tdir)\n", " s2['tokenizer'].save_pretrained(tdir)\n", " with open(tdir / 'label_encoder.pkl', 'wb') as f:\n", " pickle.dump(s2['label_encoder'], f)\n", "print(f'Saved DistilBERT stage-2 sub-models')\n", "\n", "# Copy responses.csv if present\n", "responses_src = Path('responses.csv')\n", "if responses_src.exists():\n", " import shutil\n", " shutil.copy(responses_src, ARTIFACTS_DIR / 'responses.csv')\n", "\n", "print('\\nAll artifacts persisted:')\n", "for p in sorted(ARTIFACTS_DIR.rglob('*')):\n", " if p.is_file():\n", " print(f' {p} ({p.stat().st_size / 1024:.1f} KB)')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.14 — Demo Inference Cell" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# End-to-end chatbot demo using the saved bundle\n", "with open(ARTIFACTS_DIR / 'final_model.pkl', 'rb') as f:\n", " bundle = pickle.load(f)\n", "\n", "demo_encoder = SentenceTransformer(bundle['encoder_name'], device=str(DEVICE))\n", "hsvm = bundle['hierarchical_svm']\n", "\n", "\n", "def predict_objection(quote):\n", " cleaned = preprocess_text(quote)\n", "\n", " # OOD check\n", " emb = demo_encoder.encode([cleaned], convert_to_numpy=True)\n", " max_sim = float(cosine_similarity(emb, bundle['train_embeddings']).max())\n", " is_ood = max_sim < bundle['ood_threshold']\n", "\n", " # Top-3 types\n", " stage1 = hsvm.stage1_\n", " probs = stage1.predict_proba(np.array([cleaned]))[0]\n", " classes = stage1.classes_\n", " top3_idx = probs.argsort()[-3:][::-1]\n", " top3_types = [(str(classes[i]), float(probs[i])) for i in top3_idx]\n", "\n", " # Best cluster within the top-1 type\n", " top_type = top3_types[0][0]\n", " if hsvm.stage2_[top_type] is None:\n", " top_cluster = hsvm.type_to_clusters_[top_type][0]\n", " top_cluster_conf = 1.0\n", " else:\n", " s2 = hsvm.stage2_[top_type]\n", " cp = s2.predict_proba(np.array([cleaned]))[0]\n", " cc = s2.classes_\n", " best_idx = int(np.argmax(cp))\n", " top_cluster = str(cc[best_idx])\n", " top_cluster_conf = float(cp[best_idx])\n", "\n", " return {\n", " 'quote' : quote,\n", " 'objection_type' : top_type,\n", " 'type_confidence' : top3_types[0][1],\n", " 'cluster' : top_cluster,\n", " 'cluster_confidence': top_cluster_conf,\n", " 'top3_types' : top3_types,\n", " 'ood_flag' : is_ood,\n", " 'max_similarity' : max_sim,\n", " }\n", "\n", "\n", "demo_quotes = [\n", " 'Your price is too expensive, can you give me a discount?',\n", " 'I do not have a bank statement, what should I do?',\n", " 'My friend told me you have a low visa success rate, is it true?',\n", " 'If I do not go to your office, can we interview via Zoom?',\n", " 'What is the weather today?', # OOD\n", "]\n", "\n", "print('=' * 80)\n", "print('HIERARCHICAL CHATBOT DEMO')\n", "print('=' * 80)\n", "for q in demo_quotes:\n", " r = predict_objection(q)\n", " print(f'\\nQuote: \"{r[\"quote\"]}\"')\n", " if r['ood_flag']:\n", " print(f' [OOD detected] sim={r[\"max_similarity\"]:.3f} — would escalate to human.')\n", " else:\n", " print(f' Objection Type : {r[\"objection_type\"]} ({r[\"type_confidence\"]:.0%})')\n", " print(f' Cluster : {r[\"cluster\"]} ({r[\"cluster_confidence\"]:.0%})')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5.15 — Chapter Summary\n", "\n", "**What this v3 notebook accomplishes:**\n", "\n", "1. **Hierarchical architecture** — every one of the 5 models is trained as a two-stage classifier (type → cluster). This correctly handles duplicate cluster names across objection types.\n", "2. **Full rigor preserved** — 10-fold CV, grid search, ablation, learning curves, McNemar's test, OOD detection, latency benchmarks.\n", "3. **Clean reporting** — both Type-level and Full-path metrics shown separately, plus Stage-1 vs Stage-2 error decomposition.\n", "4. **Webapp-ready artifacts** — `final_model.pkl` contains the hierarchical SVM ready for the chatbot, with top-3 confidence and OOD detection.\n", "\n", "**Next step:** Update the webapp `loader.py` and `chat.py` to use the new hierarchical bundle. The saved format is compatible with minor loader tweaks — the chat page will now show `Objection Type -> Cluster` predictions as you requested." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.11.0" } }, "nbformat": 4, "nbformat_minor": 5 }