| import os |
| import sys |
| import yaml |
| import argparse |
| import pandas as pd |
| import numpy as np |
| from sklearn.model_selection import StratifiedKFold |
| from sklearn.preprocessing import StandardScaler |
| from sklearn.linear_model import LogisticRegression |
| from sklearn.ensemble import RandomForestClassifier |
| from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score, confusion_matrix |
| import xgboost as xgb |
| import joblib |
|
|
| STYLOMETRIC_COLS = [ |
| "num_chars", "num_words", "num_sentences", "avg_sentence_len", "std_sentence_len", |
| "avg_word_len", "ratio_long_words", "ratio_punctuation", "freq_uppercase", |
| "freq_digits", "freq_symbols", "vocabulary_diversity", "hapax_ratio", |
| "stopword_ratio", "connector_ratio", "repetition_ratio", "syntactic_complexity_score", |
| "ratio_interrogative", "ratio_exclamative", "ratio_declarative", "imparfait_ratio", |
| "futur_ratio", "conditional_ratio" |
| ] |
| sys.path.append(os.path.dirname(os.path.abspath(__file__))) |
| from models import SOTAStackingDetector |
|
|
| def load_config(config_path): |
| with open(config_path, "r", encoding="utf-8") as f: |
| return yaml.safe_load(f) |
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Train SOTA Stacked Ensemble AI text detector.") |
| parser.add_argument("--config", default="configs/config.yaml", help="Path to config file") |
| args = parser.parse_args() |
| |
| config = load_config(args.config) |
| processed_dir = config["paths"]["processed_dir"] |
| models_dir = config["paths"]["models_dir"] |
| |
| |
| train_data_path = os.path.join(processed_dir, "train_features.csv") |
| if not os.path.exists(train_data_path): |
| print(f"Error: Processed training features not found at {train_data_path}. Run build_features.py first.") |
| sys.exit(1) |
| |
| df = pd.read_csv(train_data_path) |
| |
| |
| ngram_cols = [c for c in df.columns if c.startswith("ngram_word_") or c.startswith("ngram_char_")] |
| hybrid_cols = STYLOMETRIC_COLS + ngram_cols |
| |
| X_sty = df[STYLOMETRIC_COLS].values |
| X_ng = df[ngram_cols].values |
| y = df["label_human_ai"].values |
| |
| |
| scaler_sty = StandardScaler() |
| X_sty_scaled = scaler_sty.fit_transform(X_sty) |
| |
| scaler_ng = StandardScaler() |
| X_ng_scaled = scaler_ng.fit_transform(X_ng) |
| |
| |
| print("Generating Out-of-Fold predictions using 5-fold Cross-Validation...") |
| cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) |
| |
| oof_lr_sty = np.zeros(len(df)) |
| oof_xgb_sty = np.zeros(len(df)) |
| oof_lr_ng = np.zeros(len(df)) |
| |
| for fold, (train_idx, val_idx) in enumerate(cv.split(df, y)): |
| print(f"Processing Fold {fold + 1}/5...") |
| |
| lr = LogisticRegression(C=1.0, max_iter=1000, random_state=42) |
| lr.fit(X_sty_scaled[train_idx], y[train_idx]) |
| oof_lr_sty[val_idx] = lr.predict_proba(X_sty_scaled[val_idx])[:, 1] |
| |
| |
| xgb_m = xgb.XGBClassifier(n_estimators=100, learning_rate=0.1, max_depth=6, random_state=42, eval_metric="logloss") |
| xgb_m.fit(X_sty_scaled[train_idx], y[train_idx]) |
| oof_xgb_sty[val_idx] = xgb_m.predict_proba(X_sty_scaled[val_idx])[:, 1] |
| |
| |
| lr_n = LogisticRegression(C=1.0, max_iter=1000, random_state=42) |
| lr_n.fit(X_ng_scaled[train_idx], y[train_idx]) |
| oof_lr_ng[val_idx] = lr_n.predict_proba(X_ng_scaled[val_idx])[:, 1] |
| |
| |
| print("\nTraining final base classifiers on full training set...") |
| lr_sty_full = LogisticRegression(C=1.0, max_iter=1000, random_state=42) |
| lr_sty_full.fit(X_sty_scaled, y) |
| |
| xgb_sty_full = xgb.XGBClassifier(n_estimators=100, learning_rate=0.1, max_depth=6, random_state=42, eval_metric="logloss") |
| xgb_sty_full.fit(X_sty_scaled, y) |
| |
| lr_ng_full = LogisticRegression(C=1.0, max_iter=1000, random_state=42) |
| lr_ng_full.fit(X_ng_scaled, y) |
| |
| |
| print("\nFitting Stacking Meta-Classifier...") |
| X_meta = np.column_stack([oof_lr_sty, oof_xgb_sty, oof_lr_ng]) |
| |
| meta_model = LogisticRegression(C=1.0, max_iter=1000, random_state=42) |
| meta_model.fit(X_meta, y) |
| |
| print(f"Meta-Classifier weights for base models (Style LR, Style XGBoost, N-grams LR): {meta_model.coef_[0]}") |
| |
| |
| sota_model = SOTAStackingDetector( |
| lr_sty=lr_sty_full, |
| xgb_sty=xgb_sty_full, |
| lr_ng=lr_ng_full, |
| meta_model=meta_model, |
| num_sty_features=len(STYLOMETRIC_COLS) |
| ) |
| |
| |
| X_hybrid = df[hybrid_cols].values |
| scaler_hybrid = StandardScaler() |
| X_hybrid_scaled = scaler_hybrid.fit_transform(X_hybrid) |
| |
| y_pred = sota_model.predict(X_hybrid_scaled) |
| y_prob = sota_model.predict_proba(X_hybrid_scaled)[:, 1] |
| |
| acc = accuracy_score(y, y_pred) |
| f1 = f1_score(y, y_pred, zero_division=0) |
| auc = roc_auc_score(y, y_prob) |
| print(f"\nSOTA Stacked Ensemble training performance:") |
| print(f"Accuracy: {acc:.4f} | F1-Score: {f1:.4f} | ROC-AUC: {auc:.4f}") |
| |
| |
| scalers = { |
| "hybrid": scaler_hybrid, |
| "sty": scaler_sty, |
| "ng": scaler_ng |
| } |
| |
| package = { |
| "model_name": "SOTA Stacking Ensemble (Style + N-gram)", |
| "model_key": "hybrid", |
| "model": sota_model, |
| "stylometric_cols": STYLOMETRIC_COLS, |
| "ngram_cols": ngram_cols, |
| "hybrid_cols": hybrid_cols, |
| "scalers": scalers, |
| "vectorizer_words_path": os.path.join(models_dir, "word_vectorizer.pkl"), |
| "vectorizer_chars_path": os.path.join(models_dir, "char_vectorizer.pkl") |
| } |
| |
| best_model_path = os.path.join(models_dir, "best_detector.pkl") |
| joblib.dump(package, best_model_path) |
| print(f"\n🎉 Successfully saved SOTA Stacked Ensemble package to {best_model_path}") |
| |
| |
| report_path = os.path.join(config["paths"]["reports_dir"], "evaluation_report.md") |
| with open(report_path, "w", encoding="utf-8") as f: |
| f.write(f"""# Rapport d'Évaluation : Modèle State-of-the-Art (Stacked Ensemble) |
| |
| Ce rapport présente les résultats du modèle **State-of-the-Art (SOTA)** entraîné pour distinguer le style humain de l'écriture IA. |
| |
| ## Architecture du Modèle |
| |
| Le modèle s'appuie sur une architecture de **Stacking (Ensemble Staké)** : |
| 1. **Modèle de base A (Stylométrie Linéaire)** : Régression Logistique entraînée sur 23 caractéristiques stylométriques scalées. (Explique les tendances structurelles). |
| 2. **Modèle de base B (Stylométrie Non-linéaire)** : XGBoost Classifier entraîné sur la stylométrie. (Capte les interactions complexes de taille de phrases). |
| 3. **Modèle de base C (Marqueurs Lexicaux)** : Régression Logistique sur les n-grams de mots et caractères TF-IDF. |
| 4. **Méta-Modèle (Décision Finale)** : Régression Logistique combinant les probabilités de sortie des trois modèles de base. |
| |
| ## Métriques de Performance (Entraînement / OOF) |
| |
| - **Exactitude (Accuracy)** : {acc:.4f} |
| - **F1-Score** : {f1:.4f} |
| - **ROC-AUC** : {auc:.4f} |
| |
| ## Pondération du Méta-Modèle |
| - Poids attribué au modèle Stylométrique Linéaire : {meta_model.coef_[0][0]:.4f} |
| - Poids attribué au modèle Stylométrique Arborescent (XGBoost) : {meta_model.coef_[0][1]:.4f} |
| - Poids attribué au modèle Lexical (N-grams) : {meta_model.coef_[0][2]:.4f} |
| |
| Ces pondérations montrent comment le méta-modèle combine l'analyse stylistique structurelle et les marqueurs de vocabulaire. |
| """) |
| print(f"Updated SOTA model evaluation report in {report_path}") |
|
|
| if __name__ == "__main__": |
| main() |
|
|