| 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.metrics import accuracy_score, f1_score, roc_auc_score, precision_score, recall_score, classification_report |
| import xgboost as xgb |
| import joblib |
| import shap |
|
|
| sys.path.append(os.path.dirname(os.path.abspath(__file__))) |
| from models_v2 import SOTAHybridDetector |
|
|
| |
| STYLOMETRIC_COLS_V2 = [ |
| 'num_chars', 'num_words', 'num_sentences', 'avg_sentence_len', 'std_sentence_len', |
| 'slv_normalized', 'avg_word_len', 'ratio_long_words', |
| 'vocabulary_diversity', 'hapax_ratio', 'yules_k', 'maas_index', |
| 'information_entropy', 'brunet_w', |
| 'ratio_punctuation', 'freq_uppercase', 'freq_digits', |
| 'connector_ratio', 'connector_diversity', 'repetition_ratio', |
| 'stopword_ratio', 'mean_polarity_diff', |
| 'syntactic_complexity_score', 'ratio_interrogative', 'ratio_exclamative', |
| 'ratio_declarative', 'imparfait_ratio', 'futur_ratio', |
| 'conditional_ratio', 'passive_voice_ratio' |
| ] |
|
|
| 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="Entraînement du détecteur SOTA hybride (Stylométrie + CamemBERT + XGBoost).") |
| parser.add_argument("--config", default="configs/config.yaml", help="Chemin vers le fichier de config") |
| args = parser.parse_args() |
| |
| config = load_config(args.config) |
| processed_dir = config["paths"]["processed_dir"] |
| models_dir = config["paths"]["models_dir"] |
| reports_dir = config["paths"]["reports_dir"] |
| os.makedirs(models_dir, exist_ok=True) |
| os.makedirs(reports_dir, exist_ok=True) |
| |
| |
| print("=" * 60) |
| print("ENTRAÎNEMENT DU DÉTECTEUR SOTA HYBRIDE v2") |
| print("Architecture: Stylométrie (30) + CamemBERT (768) → XGBoost") |
| print("=" * 60) |
| |
| |
| train_sty_path = os.path.join(processed_dir, "train_features_v2.csv") |
| if not os.path.exists(train_sty_path): |
| print(f"ERREUR: {train_sty_path} introuvable. Lancez build_features_v2.py d'abord.") |
| sys.exit(1) |
| df_sty = pd.read_csv(train_sty_path) |
| |
| |
| train_emb_path = os.path.join(processed_dir, "train_embeddings_camembert.csv") |
| if not os.path.exists(train_emb_path): |
| print(f"ERREUR: {train_emb_path} introuvable. Lancez camembert_encoder.py d'abord.") |
| sys.exit(1) |
| df_emb = pd.read_csv(train_emb_path) |
| |
| print(f"Features stylométriques: {df_sty.shape}") |
| print(f"Embeddings CamemBERT: {df_emb.shape}") |
| |
| |
| X_sty = df_sty[STYLOMETRIC_COLS_V2].values |
| emb_cols = [c for c in df_emb.columns if c.startswith("camembert_")] |
| X_emb = df_emb[emb_cols].values |
| y = df_sty["label_human_ai"].values |
| |
| print(f"\nDimensions: Stylométrie={X_sty.shape[1]}, CamemBERT={X_emb.shape[1]}, Total={X_sty.shape[1]+X_emb.shape[1]}") |
| print(f"Classes: Humain={np.sum(y==0)}, IA={np.sum(y==1)}") |
| |
| |
| print("\nNormalisation des features...") |
| scaler_sty = StandardScaler() |
| X_sty_scaled = scaler_sty.fit_transform(X_sty) |
| |
| scaler_emb = StandardScaler() |
| X_emb_scaled = scaler_emb.fit_transform(X_emb) |
| |
| |
| X_combined = np.hstack([X_sty_scaled, X_emb_scaled]) |
| print(f"Vecteur combiné final: {X_combined.shape}") |
| |
| |
| print("\n" + "=" * 60) |
| print("VALIDATION CROISÉE STRATIFIÉE (5-Fold)") |
| print("=" * 60) |
| |
| cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) |
| oof_preds = np.zeros(len(y)) |
| oof_probs = np.zeros(len(y)) |
| fold_metrics = [] |
| |
| for fold, (train_idx, val_idx) in enumerate(cv.split(X_combined, y)): |
| print(f"\n--- Fold {fold+1}/5 ---") |
| X_train, X_val = X_combined[train_idx], X_combined[val_idx] |
| y_train, y_val = y[train_idx], y[val_idx] |
| |
| xgb_model = xgb.XGBClassifier( |
| n_estimators=300, |
| learning_rate=0.05, |
| max_depth=8, |
| min_child_weight=3, |
| subsample=0.8, |
| colsample_bytree=0.8, |
| gamma=0.1, |
| reg_alpha=0.1, |
| reg_lambda=1.0, |
| random_state=42, |
| eval_metric="logloss", |
| tree_method="hist" |
| ) |
| xgb_model.fit( |
| X_train, y_train, |
| eval_set=[(X_val, y_val)], |
| verbose=False |
| ) |
| |
| fold_probs = xgb_model.predict_proba(X_val)[:, 1] |
| fold_preds = (fold_probs >= 0.5).astype(int) |
| oof_probs[val_idx] = fold_probs |
| oof_preds[val_idx] = fold_preds |
| |
| fold_acc = accuracy_score(y_val, fold_preds) |
| fold_f1 = f1_score(y_val, fold_preds) |
| fold_auc = roc_auc_score(y_val, fold_probs) |
| fold_metrics.append({"fold": fold+1, "accuracy": fold_acc, "f1": fold_f1, "auc": fold_auc}) |
| print(f" Accuracy: {fold_acc:.4f} | F1: {fold_f1:.4f} | AUC: {fold_auc:.4f}") |
| |
| |
| oof_acc = accuracy_score(y, oof_preds) |
| oof_f1 = f1_score(y, oof_preds) |
| oof_auc = roc_auc_score(y, oof_probs) |
| oof_prec = precision_score(y, oof_preds) |
| oof_rec = recall_score(y, oof_preds) |
| |
| print(f"\n{'=' * 60}") |
| print(f"RÉSULTATS OUT-OF-FOLD (Validation Croisée Complète)") |
| print(f"{'=' * 60}") |
| print(f"Accuracy: {oof_acc:.4f}") |
| print(f"Precision: {oof_prec:.4f}") |
| print(f"Recall: {oof_rec:.4f}") |
| print(f"F1-Score: {oof_f1:.4f}") |
| print(f"ROC-AUC: {oof_auc:.4f}") |
| |
| |
| print(f"\nEntraînement du modèle final sur l'intégralité des données...") |
| xgb_final = xgb.XGBClassifier( |
| n_estimators=300, |
| learning_rate=0.05, |
| max_depth=8, |
| min_child_weight=3, |
| subsample=0.8, |
| colsample_bytree=0.8, |
| gamma=0.1, |
| reg_alpha=0.1, |
| reg_lambda=1.0, |
| random_state=42, |
| eval_metric="logloss", |
| tree_method="hist" |
| ) |
| xgb_final.fit(X_combined, y, verbose=False) |
| |
| |
| print("\nCalcul des valeurs SHAP (TreeExplainer)...") |
| all_feature_names = STYLOMETRIC_COLS_V2 + emb_cols |
| |
| explainer = shap.TreeExplainer(xgb_final) |
| |
| sample_size = min(500, len(X_combined)) |
| np.random.seed(42) |
| sample_idx = np.random.choice(len(X_combined), sample_size, replace=False) |
| shap_values = explainer.shap_values(X_combined[sample_idx]) |
| |
| |
| mean_shap = np.abs(shap_values).mean(axis=0) |
| top_indices = np.argsort(mean_shap)[::-1][:20] |
| print("\nTop 20 features par importance SHAP moyenne:") |
| for rank, idx in enumerate(top_indices): |
| fname = all_feature_names[idx] if idx < len(all_feature_names) else f"feature_{idx}" |
| print(f" {rank+1:2d}. {fname:40s} SHAP moyen: {mean_shap[idx]:.4f}") |
| |
| |
| |
| ngram_cols = [c for c in df_sty.columns if c.startswith("ngram_word_") or c.startswith("ngram_char_")] |
| |
| |
| sty_friendly = { |
| 'num_chars': 'Nombre de caractères', |
| 'num_words': 'Nombre de mots', |
| 'num_sentences': 'Nombre de phrases', |
| 'avg_sentence_len': 'Longueur moyenne des phrases', |
| 'std_sentence_len': 'Écart-type longueur des phrases', |
| 'slv_normalized': 'Variance normalisée des phrases (SLV)', |
| 'avg_word_len': 'Longueur moyenne des mots', |
| 'ratio_long_words': 'Ratio de mots longs (>6 chars)', |
| 'vocabulary_diversity': 'Diversité lexicale (TTR)', |
| 'hapax_ratio': "Ratio d'Hapax (mots uniques)", |
| 'yules_k': 'K de Yule (richesse vocabulaire)', |
| 'maas_index': 'Indice de Maas (diversité log)', |
| 'information_entropy': 'Entropie informationnelle (burstiness)', |
| 'brunet_w': 'W de Brunet (richesse)', |
| 'ratio_punctuation': 'Ratio de ponctuation', |
| 'freq_uppercase': 'Fréquence des majuscules', |
| 'freq_digits': 'Fréquence des chiffres', |
| 'connector_ratio': 'Ratio de connecteurs logiques', |
| 'connector_diversity': 'Diversité des connecteurs', |
| 'repetition_ratio': 'Ratio de répétitions lexicales', |
| 'stopword_ratio': 'Ratio de mots vides', |
| 'mean_polarity_diff': 'Variation de polarité inter-phrases', |
| 'syntactic_complexity_score': 'Complexité syntaxique', |
| 'ratio_interrogative': 'Ratio phrases interrogatives', |
| 'ratio_exclamative': 'Ratio phrases exclamatives', |
| 'ratio_declarative': 'Ratio phrases déclaratives', |
| 'imparfait_ratio': "Ratio verbes à l'imparfait", |
| 'futur_ratio': 'Ratio verbes au futur', |
| 'conditional_ratio': 'Ratio verbes au conditionnel', |
| 'passive_voice_ratio': 'Ratio de voix passive' |
| } |
| |
| friendly_names_sty = [sty_friendly.get(c, c) for c in STYLOMETRIC_COLS_V2] |
| friendly_names_emb = [f"CamemBERT dim {i}" for i in range(len(emb_cols))] |
| |
| detector = SOTAHybridDetector( |
| xgb_meta=xgb_final, |
| scaler_sty=scaler_sty, |
| scaler_emb=scaler_emb, |
| num_sty_features=len(STYLOMETRIC_COLS_V2), |
| num_emb_features=len(emb_cols), |
| feature_names_sty=friendly_names_sty, |
| feature_names_emb=friendly_names_emb |
| ) |
| |
| package = { |
| "model_name": "SOTA Hybrid Detector v2 (Stylométrie + CamemBERT + XGBoost)", |
| "model_key": "hybrid_v2", |
| "model": detector, |
| "xgb_raw": xgb_final, |
| "stylometric_cols": STYLOMETRIC_COLS_V2, |
| "emb_cols": emb_cols, |
| "ngram_cols": ngram_cols, |
| "scalers": {"sty": scaler_sty, "emb": scaler_emb}, |
| "shap_explainer": explainer, |
| "shap_mean_abs": mean_shap, |
| "feature_names_all": all_feature_names, |
| "friendly_names_sty": friendly_names_sty, |
| "friendly_names_emb": friendly_names_emb, |
| "vectorizer_words_path": os.path.join(models_dir, "word_vectorizer_v2.pkl"), |
| "vectorizer_chars_path": os.path.join(models_dir, "char_vectorizer_v2.pkl"), |
| "oof_metrics": { |
| "accuracy": oof_acc, "precision": oof_prec, "recall": oof_rec, |
| "f1": oof_f1, "auc": oof_auc |
| }, |
| "fold_metrics": fold_metrics, |
| "top_shap_features": [(all_feature_names[i], float(mean_shap[i])) for i in top_indices] |
| } |
| |
| model_path = os.path.join(models_dir, "best_detector_v2.pkl") |
| joblib.dump(package, model_path) |
| print(f"\n🎉 Modèle SOTA v2 sauvegardé dans {model_path}") |
| |
| |
| report_path = os.path.join(reports_dir, "evaluation_report_v2.md") |
| with open(report_path, "w", encoding="utf-8") as f: |
| f.write(f"""# Rapport d'Évaluation — Détecteur SOTA Hybride v2\n\n""") |
| f.write(f"**Date d'entraînement** : Juin 2026\n") |
| f.write(f"**Architecture** : Stylométrie (30 features) + CamemBERT gelé (768 dims) → XGBoost\n\n") |
| f.write(f"## Résultats de Validation Croisée (5-Fold OOF)\n\n") |
| f.write(f"| Métrique | Score |\n|---|---|\n") |
| f.write(f"| Accuracy | {oof_acc:.4f} |\n") |
| f.write(f"| Precision | {oof_prec:.4f} |\n") |
| f.write(f"| Recall | {oof_rec:.4f} |\n") |
| f.write(f"| F1-Score | {oof_f1:.4f} |\n") |
| f.write(f"| ROC-AUC | {oof_auc:.4f} |\n\n") |
| f.write(f"## Résultats par Fold\n\n") |
| f.write(f"| Fold | Accuracy | F1 | AUC |\n|---|---|---|---|\n") |
| for m in fold_metrics: |
| f.write(f"| {m['fold']} | {m['accuracy']:.4f} | {m['f1']:.4f} | {m['auc']:.4f} |\n") |
| f.write(f"\n## Top 20 Features SHAP\n\n") |
| f.write(f"| Rang | Feature | SHAP moyen |\n|---|---|---|\n") |
| for rank, idx in enumerate(top_indices): |
| fname = all_feature_names[idx] if idx < len(all_feature_names) else f"feature_{idx}" |
| f.write(f"| {rank+1} | {fname} | {mean_shap[idx]:.4f} |\n") |
| f.write(f"\n## Description de l'Architecture\n\n") |
| f.write(f"""### Phase 1 : Module Stylométrique (30 features invariantes) |
| Extraction de 30 caractéristiques linguistiques prouvées résistantes aux attaques de paraphrase :\n- **Structure** : longueur/variance des phrases, SLV normalisée\n- **Richesse lexicale** : K de Yule, Indice de Maas, W de Brunet, Entropie\n- **Discours** : connecteurs, polarité, répétitions\n- **Syntaxe** : complexité, temps verbaux, voix passive\n\n### Phase 2 : Module Neural (CamemBERT gelé) |
| Embeddings denses de 768 dimensions extraits du token [CLS] de `almanach/camembert-base`.\nPoids entièrement gelés — aucun fine-tuning pour préserver la généralisation.\n\n### Phase 3 : Méta-Classifieur XGBoost |
| XGBoost Classifier entraîné sur le vecteur concaténé de 798 dimensions.\nHyperparamètres optimisés : 300 estimateurs, lr=0.05, depth=8.\n\n### Phase 4 : Explainabilité SHAP (TreeExplainer) |
| Valeurs SHAP calculées par TreeExplainer pour décomposer chaque prédiction\nen contributions individuelles de chaque feature.\n""") |
| |
| print(f"📊 Rapport d'évaluation sauvegardé dans {report_path}") |
| print(f"\n✅ Pipeline d'entraînement SOTA v2 terminé avec succès.") |
|
|
| if __name__ == "__main__": |
| main() |
|
|