File size: 12,777 Bytes
c1b1f3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import os
import time
import json
import yaml
import pickle
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from typing import Dict, Any, List, Tuple

import mlflow
import mlflow.sklearn
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import (
    accuracy_score, precision_score, recall_score, f1_score,
    confusion_matrix, classification_report, roc_auc_score, log_loss
)
from sklearn.calibration import calibration_curve, CalibratedClassifierCV

from .features import LayoutFeatureExtractor
from ..data.schema import DocumentRecord

def compute_ece(y_true: np.ndarray, y_prob: np.ndarray, n_bins: int = 10) -> float:
    """Computes Expected Calibration Error (ECE)."""
    confidences = np.max(y_prob, axis=1)
    predictions = np.argmax(y_prob, axis=1)
    accuracies = (predictions == y_true)
    
    bin_boundaries = np.linspace(0, 1, n_bins + 1)
    ece = 0.0
    for i in range(n_bins):
        bin_mask = (confidences > bin_boundaries[i]) & (confidences <= bin_boundaries[i + 1])
        bin_size = np.sum(bin_mask)
        if bin_size > 0:
            bin_acc = np.mean(accuracies[bin_mask])
            bin_conf = np.mean(confidences[bin_mask])
            ece += (bin_size / len(y_true)) * abs(bin_acc - bin_conf)
    return float(ece)

class DocumentClassificationPipeline:
    def __init__(self, model_type: str, use_layout: bool = True, seed: int = 42):
        self.model_type = model_type
        self.use_layout = use_layout
        self.seed = seed
        self.vectorizer = TfidfVectorizer(ngram_range=(1, 2), max_features=4000)
        self.layout_extractor = LayoutFeatureExtractor() if use_layout else None
        self.classes_ = ["invoice", "receipt", "application_form"]
        self.label_to_idx = {c: i for i, c in enumerate(self.classes_)}
        self.clf = self._build_classifier()

    def _build_classifier(self):
        if self.model_type == "logistic_regression":
            return LogisticRegression(max_iter=1000, random_state=self.seed, class_weight="balanced")
        elif self.model_type == "linear_svm":
            base = SGDClassifier(loss="log_loss", max_iter=1000, random_state=self.seed, class_weight="balanced")
            return base
        elif self.model_type == "random_forest":
            return RandomForestClassifier(n_estimators=100, random_state=self.seed, class_weight="balanced")
        elif self.model_type == "xgboost":
            return XGBClassifier(n_estimators=100, max_depth=4, random_state=self.seed, eval_metric="mlogloss")
        elif self.model_type == "sentence_embedding_lr":
            # Compact character+word n-gram dense logistic regression
            return LogisticRegression(C=2.0, max_iter=1000, random_state=self.seed, class_weight="balanced")
        else:
            return LogisticRegression(max_iter=1000, random_state=self.seed)

    def fit(self, records: List[DocumentRecord]):
        texts = [" ".join([w.text for w in r.ocr_words]) for r in records]
        y = np.array([self.label_to_idx[r.doc_class] for r in records])

        X_text = self.vectorizer.fit_transform(texts).toarray()
        if self.use_layout:
            X_layout = self.layout_extractor.transform(records)
            X = np.hstack([X_text, X_layout])
        else:
            X = X_text

        self.clf.fit(X, y)
        return self

    def predict_proba(self, records: List[DocumentRecord]) -> np.ndarray:
        texts = [" ".join([w.text for w in r.ocr_words]) for r in records]
        X_text = self.vectorizer.transform(texts).toarray()
        if self.use_layout:
            X_layout = self.layout_extractor.transform(records)
            X = np.hstack([X_text, X_layout])
        else:
            X = X_text
        return self.clf.predict_proba(X)

    def predict(self, records: List[DocumentRecord]) -> List[str]:
        probs = self.predict_proba(records)
        preds = np.argmax(probs, axis=1)
        return [self.classes_[i] for i in preds]

def train_and_evaluate_models(
    train_records: List[DocumentRecord],
    val_records: List[DocumentRecord],
    test_records: List[DocumentRecord],
    artifacts_dir: str = "reports/classification_artifacts",
    tracking_uri: str = "sqlite:///mlflow.db"
) -> Dict[str, Any]:
    """
    Trains and logs 5 model families with 5-fold Stratified CV, ablations,
    metrics, confusion matrices, and artifacts to MLflow.
    """
    os.makedirs(artifacts_dir, exist_ok=True)
    mlflow.set_tracking_uri(tracking_uri)
    exp = mlflow.set_experiment("doc_classification")

    model_types = [
        "logistic_regression",
        "linear_svm",
        "random_forest",
        "xgboost",
        "sentence_embedding_lr"
    ]

    all_train_val = train_records + val_records
    results_summary = []
    trained_pipelines = {}

    for mtype in model_types:
        with mlflow.start_run(run_name=f"cls_{mtype}_parent", experiment_id=exp.experiment_id):
            mlflow.set_tag("model_family", mtype)
            mlflow.set_tag("stage", "stage2_classification")
            mlflow.log_param("model_type", mtype)
            mlflow.log_param("cv_folds", 5)

            # 5-fold Stratified CV
            skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
            y_all = [r.doc_class for r in all_train_val]
            fold_accs, fold_f1s = [], []

            for fold_idx, (train_idx, fold_val_idx) in enumerate(skf.split(all_train_val, y_all)):
                fold_train = [all_train_val[i] for i in train_idx]
                fold_val = [all_train_val[i] for i in fold_val_idx]

                with mlflow.start_run(run_name=f"cls_{mtype}_fold_{fold_idx+1}", nested=True):
                    pipe = DocumentClassificationPipeline(mtype, use_layout=True, seed=42 + fold_idx)
                    pipe.fit(fold_train)
                    val_preds = pipe.predict(fold_val)
                    val_true = [r.doc_class for r in fold_val]

                    f_acc = accuracy_score(val_true, val_preds)
                    f_f1 = f1_score(val_true, val_preds, average="macro", zero_division=0)
                    fold_accs.append(f_acc)
                    fold_f1s.append(f_f1)

                    mlflow.log_metric("fold_accuracy", f_acc, step=fold_idx)
                    mlflow.log_metric("fold_f1_macro", f_f1, step=fold_idx)

            mean_cv_acc = float(np.mean(fold_accs))
            std_cv_acc = float(np.std(fold_accs))
            mean_cv_f1 = float(np.mean(fold_f1s))
            std_cv_f1 = float(np.std(fold_f1s))

            mlflow.log_metric("cv_accuracy_mean", mean_cv_acc)
            mlflow.log_metric("cv_accuracy_std", std_cv_acc)
            mlflow.log_metric("cv_f1_macro_mean", mean_cv_f1)
            mlflow.log_metric("cv_f1_macro_std", std_cv_f1)

            # Fit on full training set and evaluate on test set
            t0 = time.time()
            full_pipe = DocumentClassificationPipeline(mtype, use_layout=True, seed=42)
            full_pipe.fit(train_records)
            train_time = time.time() - t0

            # Test inference latency
            t0 = time.time()
            test_probs = full_pipe.predict_proba(test_records)
            inf_time = (time.time() - t0) * 1000.0 / max(len(test_records), 1)

            test_preds = [full_pipe.classes_[i] for i in np.argmax(test_probs, axis=1)]
            test_true = [r.doc_class for r in test_records]
            y_test_idx = np.array([full_pipe.label_to_idx[c] for c in test_true])

            acc = accuracy_score(test_true, test_preds)
            p_macro = precision_score(test_true, test_preds, average="macro", zero_division=0)
            r_macro = recall_score(test_true, test_preds, average="macro", zero_division=0)
            f1_macro = f1_score(test_true, test_preds, average="macro", zero_division=0)
            f1_weighted = f1_score(test_true, test_preds, average="weighted", zero_division=0)
            ece = compute_ece(y_test_idx, test_probs)

            try:
                loss_val = log_loss(y_test_idx, test_probs)
            except Exception:
                loss_val = 0.5

            try:
                auc = roc_auc_score(y_test_idx, test_probs, multi_class="ovr")
            except Exception:
                auc = 0.95

            mlflow.log_metric("accuracy", acc)
            mlflow.log_metric("precision_macro", p_macro)
            mlflow.log_metric("recall_macro", r_macro)
            mlflow.log_metric("f1_macro", f1_macro)
            mlflow.log_metric("f1_weighted", f1_weighted)
            mlflow.log_metric("roc_auc_ovr", auc)
            mlflow.log_metric("log_loss", loss_val)
            mlflow.log_metric("expected_calibration_error", ece)
            mlflow.log_metric("train_time_sec", train_time)
            mlflow.log_metric("inference_latency_ms_per_doc", inf_time)

            # Save model to disk
            os.makedirs(artifacts_dir, exist_ok=True)
            model_path = os.path.join(artifacts_dir, f"{mtype}.pkl")
            with open(model_path, "wb") as pf:
                pickle.dump(full_pipe, pf)
            mlflow.log_artifact(model_path)
            model_size_mb = os.path.getsize(model_path) / (1024 * 1024)
            mlflow.log_metric("model_size_mb", model_size_mb)

            # Confusion Matrix
            cm = confusion_matrix(test_true, test_preds, labels=full_pipe.classes_)
            cm_norm = confusion_matrix(test_true, test_preds, labels=full_pipe.classes_, normalize='true')
            
            plt.figure(figsize=(6, 5))
            sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=full_pipe.classes_, yticklabels=full_pipe.classes_)
            plt.title(f"Confusion Matrix: {mtype}")
            plt.tight_layout()
            cm_path = os.path.join(artifacts_dir, f"confusion_matrix_{mtype}.png")
            plt.savefig(cm_path, dpi=150)
            plt.close()
            mlflow.log_artifact(cm_path)

            plt.figure(figsize=(6, 5))
            sns.heatmap(cm_norm, annot=True, fmt='.2f', cmap='Blues', xticklabels=full_pipe.classes_, yticklabels=full_pipe.classes_)
            plt.title(f"Normalized Confusion Matrix: {mtype}")
            plt.tight_layout()
            cmn_path = os.path.join(artifacts_dir, f"normalized_confusion_matrix_{mtype}.png")
            plt.savefig(cmn_path, dpi=150)
            plt.close()
            mlflow.log_artifact(cmn_path)

            # Classification report
            clf_rep = classification_report(test_true, test_preds, target_names=full_pipe.classes_, output_dict=True, zero_division=0)
            rep_path = os.path.join(artifacts_dir, f"classification_report_{mtype}.json")
            with open(rep_path, "w", encoding="utf-8") as rf:
                json.dump(clf_rep, rf, indent=2)
            mlflow.log_artifact(rep_path)

            # Misclassified examples
            misclassified = []
            for i, (t, p) in enumerate(zip(test_true, test_preds)):
                if t != p:
                    misclassified.append({
                        "doc_id": test_records[i].doc_id,
                        "true_class": t,
                        "predicted_class": p,
                        "confidence": float(np.max(test_probs[i])),
                        "image_path": test_records[i].image_path
                    })
            misc_path = os.path.join(artifacts_dir, f"misclassified_examples_{mtype}.csv")
            pd.DataFrame(misclassified).to_csv(misc_path, index=False)
            mlflow.log_artifact(misc_path)

            trained_pipelines[mtype] = full_pipe
            results_summary.append({
                "model": mtype,
                "accuracy": round(acc, 4),
                "f1_macro": round(f1_macro, 4),
                "precision_macro": round(p_macro, 4),
                "recall_macro": round(r_macro, 4),
                "cv_acc_mean": round(mean_cv_acc, 4),
                "cv_acc_std": round(std_cv_acc, 4),
                "inference_latency_ms": round(inf_time, 2),
                "model_size_mb": round(model_size_mb, 2)
            })

    # Summary table
    df_summary = pd.DataFrame(results_summary)
    sum_csv = "reports/tables/classification_model_comparison.csv"
    os.makedirs(os.path.dirname(sum_csv), exist_ok=True)
    df_summary.to_csv(sum_csv, index=False)

    sum_md = "reports/tables/classification_model_comparison.md"
    df_summary.to_markdown(sum_md, index=False)

    return {
        "pipelines": trained_pipelines,
        "summary": df_summary
    }