Spaces:
Sleeping
Sleeping
File size: 8,064 Bytes
a783939 | 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 | """
Train the fraud-text classifier.
Pipeline (senior-grade upgrade over the previous single-LogReg version):
1. Text normalisation (``app.services.preprocess.normalize_for_classifier``)
replaces digits and URLs with sentinel tokens so the model learns the
*pattern of manipulation*, not memorised amounts or specific phishing
domains.
2. Two TF-IDF representations are concatenated:
* word n-grams (1–3) — captures phrase-level signals
("сообщите код", "не разглашайте")
* char-word-boundary n-grams (2–5) — robust to Russian/Kazakh
morphology and to ASR-style spelling errors
(e.g. "бұғатталады" → "бугаталады" still matches at char level).
3. Three diverse base classifiers are calibrated with isotonic regression
on a held-out split and combined via soft voting:
* Logistic Regression (linear, well-regularised)
* Linear SVC (large-margin classifier, complementary errors)
* Multinomial Naive Bayes (different inductive bias)
Calibration is essential for the downstream fusion formula
(0.6·ml + 0.4·rules) to behave like real probability arithmetic.
4. 5-fold stratified CV reports F1 / ROC-AUC so we know what to expect
on production data, not just on the test split which is inflated by
template similarity.
"""
from __future__ import annotations
import argparse
import os
import sys
from pathlib import Path
import joblib
import numpy as np
import pandas as pd
from scipy.sparse import hstack
from sklearn.calibration import CalibratedClassifierCV
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, roc_auc_score
from sklearn.model_selection import StratifiedKFold, train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import LinearSVC
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from app.services.preprocess import normalize_for_classifier # noqa: E402
def build_vectorisers():
word_vec = TfidfVectorizer(
ngram_range=(1, 3),
min_df=2,
max_df=0.95,
max_features=80_000,
sublinear_tf=True,
lowercase=False, # already lowercased in preprocessing
)
char_vec = TfidfVectorizer(
analyzer="char_wb",
ngram_range=(2, 5),
min_df=2,
max_features=120_000,
sublinear_tf=True,
lowercase=False,
)
return word_vec, char_vec
def build_features(word_vec, char_vec, texts, fit=False):
if fit:
word = word_vec.fit_transform(texts)
char = char_vec.fit_transform(texts)
else:
word = word_vec.transform(texts)
char = char_vec.transform(texts)
return hstack([word, char]).tocsr()
def build_ensemble(random_state: int = 42):
"""Return three classifier factories (instantiated per fold/training)."""
return [
("logreg",
lambda: LogisticRegression(
C=4.0, max_iter=4000, class_weight="balanced",
solver="liblinear", random_state=random_state)),
("linsvc",
lambda: CalibratedClassifierCV(
estimator=LinearSVC(C=1.0, class_weight="balanced", random_state=random_state),
method="isotonic", cv=3)),
("mnb",
lambda: MultinomialNB(alpha=0.3)),
]
def calibrate(estimator, X, y, method: str = "isotonic"):
"""Wrap an estimator into a calibrator unless it's already calibrated."""
if isinstance(estimator, CalibratedClassifierCV):
estimator.fit(X, y)
return estimator
cal = CalibratedClassifierCV(estimator=estimator, method=method, cv=3)
cal.fit(X, y)
return cal
def cross_validate_ensemble(X_text: pd.Series, y: pd.Series, seed: int,
folds: int = 5) -> dict[str, float]:
skf = StratifiedKFold(n_splits=folds, shuffle=True, random_state=seed)
f1s, aucs = [], []
for fold, (tr_idx, va_idx) in enumerate(skf.split(X_text, y), start=1):
X_tr_text = X_text.iloc[tr_idx]
X_va_text = X_text.iloc[va_idx]
y_tr = y.iloc[tr_idx]
y_va = y.iloc[va_idx]
word_vec, char_vec = build_vectorisers()
X_tr = build_features(word_vec, char_vec, X_tr_text, fit=True)
X_va = build_features(word_vec, char_vec, X_va_text, fit=False)
probas = np.zeros(len(va_idx), dtype=float)
for _, factory in build_ensemble(seed):
clf = calibrate(factory(), X_tr, y_tr)
probas += clf.predict_proba(X_va)[:, 1]
probas /= len(build_ensemble(seed))
preds = (probas >= 0.5).astype(int)
from sklearn.metrics import f1_score
f1s.append(f1_score(y_va, preds))
aucs.append(roc_auc_score(y_va, probas))
print(f" fold {fold}: f1={f1s[-1]:.4f} auc={aucs[-1]:.4f}")
return {"f1_mean": float(np.mean(f1s)), "f1_std": float(np.std(f1s)),
"auc_mean": float(np.mean(aucs)), "auc_std": float(np.std(aucs))}
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--dataset", default=None)
parser.add_argument("--out", default=None)
parser.add_argument("--test-size", type=float, default=0.2)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--no-cv", action="store_true",
help="Skip 5-fold CV report (faster in CI)")
args = parser.parse_args()
here = Path(__file__).resolve().parent
server_root = here.parent
dataset_path = Path(args.dataset) if args.dataset else here / "seed_dataset.csv"
out_path = Path(args.out) if args.out else server_root / "models" / "clf.pkl"
if not dataset_path.exists():
print(f"Dataset not found: {dataset_path}", file=sys.stderr)
return 1
df = pd.read_csv(dataset_path)
df = df.dropna(subset=["text", "label"]).reset_index(drop=True)
df["text"] = df["text"].astype(str).map(normalize_for_classifier)
df = df[df["text"].str.len() > 0].reset_index(drop=True)
df["label"] = df["label"].astype(int)
print(f"Loaded {len(df)} examples. Label distribution:")
print(df["label"].value_counts().to_string())
if not args.no_cv:
print("\n5-fold stratified CV (ensemble):")
cv = cross_validate_ensemble(df["text"], df["label"], seed=args.seed)
print(f" ▸ F1 {cv['f1_mean']:.4f} ± {cv['f1_std']:.4f}")
print(f" ▸ AUC {cv['auc_mean']:.4f} ± {cv['auc_std']:.4f}")
X_train_text, X_test_text, y_train, y_test = train_test_split(
df["text"], df["label"], test_size=args.test_size,
stratify=df["label"], random_state=args.seed,
)
word_vec, char_vec = build_vectorisers()
X_train = build_features(word_vec, char_vec, X_train_text, fit=True)
X_test = build_features(word_vec, char_vec, X_test_text, fit=False)
# Fit each calibrated base learner on the training split
members = []
for name, factory in build_ensemble(args.seed):
print(f"\nFitting {name}…")
clf = calibrate(factory(), X_train, y_train)
members.append((name, clf))
# Evaluate the soft-voting ensemble on the held-out test split
probas = np.zeros(X_test.shape[0], dtype=float)
for _, clf in members:
probas += clf.predict_proba(X_test)[:, 1]
probas /= len(members)
y_pred = (probas >= 0.5).astype(int)
print("\nHeld-out test split — ensemble report:")
print(classification_report(y_test, y_pred, digits=3, zero_division=0))
print(f"AUC: {roc_auc_score(y_test, probas):.4f}")
out_path.parent.mkdir(parents=True, exist_ok=True)
bundle = {
"word": word_vec,
"char": char_vec,
"members": members,
"version": 2,
}
joblib.dump(bundle, out_path)
size_kb = os.path.getsize(out_path) / 1024
print(f"\nSaved ensemble classifier to {out_path} ({size_kb:.1f} KB)")
return 0
if __name__ == "__main__":
raise SystemExit(main())
|