File size: 12,281 Bytes
eb72d30 | 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 | import os
import sys
import yaml
import argparse
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
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"
]
def load_config(config_path):
with open(config_path, "r", encoding="utf-8") as f:
return yaml.safe_load(f)
def evaluate_model(model_name, y_true, y_pred, y_prob):
"""Calculates all metrics for model evaluation."""
acc = accuracy_score(y_true, y_pred)
prec = precision_score(y_true, y_pred, zero_division=0)
rec = recall_score(y_true, y_pred, zero_division=0)
f1 = f1_score(y_true, y_pred, zero_division=0)
auc = roc_auc_score(y_true, y_prob)
cm = confusion_matrix(y_true, y_pred)
return {
"model": model_name,
"accuracy": acc,
"precision": prec,
"recall": rec,
"f1": f1,
"auc": auc,
"cm": cm
}
def main():
parser = argparse.ArgumentParser(description="Train and evaluate French political AI text detectors.")
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"]
os.makedirs(models_dir, exist_ok=True)
# Load training features
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}. Please run build_features.py first.")
sys.exit(1)
df = pd.read_csv(train_data_path)
# Separate stylometric and n-gram features
ngram_cols = [c for c in df.columns if c.startswith("ngram_word_") or c.startswith("ngram_char_")]
hybrid_cols = STYLOMETRIC_COLS + ngram_cols
y = df["label_human_ai"].values
# Train-test split
test_size = config["training"]["test_size"]
random_state = config["training"]["random_state"]
df_train, df_test, y_train, y_test = train_test_split(df, y, test_size=test_size, random_state=random_state, stratify=y)
print(f"Train size: {len(df_train)}, Test size: {len(df_test)}")
results = []
trained_models = {}
scalers = {}
# Set up models
# 1. Baseline 1: Logistic Regression on Stylometrics
print("\nTraining Model 1: Logistic Regression on Stylometrics...")
scaler_sty = StandardScaler()
X_train_sty = scaler_sty.fit_transform(df_train[STYLOMETRIC_COLS])
X_test_sty = scaler_sty.transform(df_test[STYLOMETRIC_COLS])
lr_sty = LogisticRegression(C=config["training"]["logistic_regression"]["C"],
max_iter=config["training"]["logistic_regression"]["max_iter"],
random_state=random_state)
lr_sty.fit(X_train_sty, y_train)
y_pred = lr_sty.predict(X_test_sty)
y_prob = lr_sty.predict_proba(X_test_sty)[:, 1]
results.append(evaluate_model("Logistic Regression (Stylometrics)", y_test, y_pred, y_prob))
trained_models["logistic_regression_sty"] = lr_sty
scalers["sty"] = scaler_sty
# 2. Baseline 2: XGBoost on Stylometrics
print("Training Model 2: XGBoost on Stylometrics...")
xgb_sty = xgb.XGBClassifier(n_estimators=config["training"]["xgboost"]["n_estimators"],
learning_rate=config["training"]["xgboost"]["learning_rate"],
max_depth=config["training"]["xgboost"]["max_depth"],
random_state=random_state,
eval_metric="logloss")
xgb_sty.fit(df_train[STYLOMETRIC_COLS], y_train)
y_pred = xgb_sty.predict(df_test[STYLOMETRIC_COLS])
y_prob = xgb_sty.predict_proba(df_test[STYLOMETRIC_COLS])[:, 1]
results.append(evaluate_model("XGBoost (Stylometrics)", y_test, y_pred, y_prob))
trained_models["xgb_sty"] = xgb_sty
# 3. Model 3: Logistic Regression on N-grams
print("Training Model 3: Logistic Regression on N-grams...")
X_train_ng = df_train[ngram_cols].values
X_test_ng = df_test[ngram_cols].values
lr_ng = LogisticRegression(C=config["training"]["logistic_regression"]["C"],
max_iter=config["training"]["logistic_regression"]["max_iter"],
random_state=random_state)
lr_ng.fit(X_train_ng, y_train)
y_pred = lr_ng.predict(X_test_ng)
y_prob = lr_ng.predict_proba(X_test_ng)[:, 1]
results.append(evaluate_model("Logistic Regression (N-grams)", y_test, y_pred, y_prob))
trained_models["logistic_regression_ng"] = lr_ng
# 4. Model 4: Hybrid Model (Logistic Regression on Stylometrics + N-grams)
print("Training Model 4: Hybrid Model (Logistic Regression on All Features)...")
scaler_hybrid = StandardScaler()
# Let's scale everything together
X_train_hyb = scaler_hybrid.fit_transform(df_train[hybrid_cols])
X_test_hyb = scaler_hybrid.transform(df_test[hybrid_cols])
lr_hybrid = LogisticRegression(C=config["training"]["logistic_regression"]["C"],
max_iter=config["training"]["logistic_regression"]["max_iter"],
random_state=random_state)
lr_hybrid.fit(X_train_hyb, y_train)
y_pred = lr_hybrid.predict(X_test_hyb)
y_prob = lr_hybrid.predict_proba(X_test_hyb)[:, 1]
results.append(evaluate_model("Hybrid Model (Logistic Regression)", y_test, y_pred, y_prob))
trained_models["hybrid"] = lr_hybrid
scalers["hybrid"] = scaler_hybrid
# Compare models
df_results = pd.DataFrame(results)
print("\nEvaluation Results:")
print(df_results[["model", "accuracy", "precision", "recall", "f1", "auc"]].to_string(index=False))
# Pick the best model based on F1-Score
best_idx = df_results["f1"].idxmax()
best_row = df_results.iloc[best_idx]
best_model_name = best_row["model"]
print(f"\nBest model: {best_model_name} with F1-score: {best_row['f1']:.4f}")
# Map friendly name to key
model_mapping = {
"Logistic Regression (Stylometrics)": "logistic_regression_sty",
"XGBoost (Stylometrics)": "xgb_sty",
"Logistic Regression (N-grams)": "logistic_regression_ng",
"Hybrid Model (Logistic Regression)": "hybrid"
}
best_key = model_mapping[best_model_name]
best_model = trained_models[best_key]
# Save the best model details
package = {
"model_name": best_model_name,
"model_key": best_key,
"model": best_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"Saved best model package to {best_model_path}")
# Retrieve feature importance / coefficients for explanation
# Only applicable if best model is linear (Logistic Regression) or tree-based (XGBoost)
importance_report = ""
if "Logistic Regression" in best_model_name:
coefs = best_model.coef_[0]
feats = STYLOMETRIC_COLS if best_key == "logistic_regression_sty" else (ngram_cols if best_key == "logistic_regression_ng" else hybrid_cols)
# Load vectorizers to map n-gram index back to text if hybrid or n-gram
word_vectorizer = joblib.load(os.path.join(models_dir, "word_vectorizer.pkl"))
char_vectorizer = joblib.load(os.path.join(models_dir, "char_vectorizer.pkl"))
feature_names = []
for f in feats:
if f.startswith("ngram_word_"):
idx = int(f.split("_")[-1])
feature_names.append(f"Word n-gram: '{word_vectorizer.get_feature_names_out()[idx]}'")
elif f.startswith("ngram_char_"):
idx = int(f.split("_")[-1])
feature_names.append(f"Char n-gram: '{char_vectorizer.get_feature_names_out()[idx]}'")
else:
feature_names.append(f)
coef_df = pd.DataFrame({"feature": feature_names, "coefficient": coefs})
coef_df["abs_coef"] = coef_df["coefficient"].abs()
coef_df = coef_df.sort_values(by="coefficient", ascending=False)
print("\nTop 10 features indicating AI:")
print(coef_df.head(10)[["feature", "coefficient"]].to_string(index=False))
print("\nTop 10 features indicating Human:")
print(coef_df.tail(10)[["feature", "coefficient"]].to_string(index=False))
# Create report string
importance_report = "### Feature Explanations (Logistic Regression Coefficients)\n\n"
importance_report += "#### Features predicting AI (positive coefficients):\n"
for _, row in coef_df.head(10).iterrows():
importance_report += f"- **{row['feature']}**: {row['coefficient']:.4f}\n"
importance_report += "\n#### Features predicting Human (negative coefficients):\n"
for _, row in coef_df.tail(10).iterrows():
importance_report += f"- **{row['feature']}**: {row['coefficient']:.4f}\n"
elif "XGBoost" in best_model_name:
importances = best_model.feature_importances_
imp_df = pd.DataFrame({"feature": STYLOMETRIC_COLS, "importance": importances})
imp_df = imp_df.sort_values(by="importance", ascending=False)
print("\nTop 10 feature importances (XGBoost):")
print(imp_df.head(10).to_string(index=False))
importance_report = "### Feature Importances (XGBoost)\n\n"
for _, row in imp_df.head(10).iterrows():
importance_report += f"- **{row['feature']}**: {row['importance']:.4f}\n"
# Generate reports/evaluation_report.md
report_path = os.path.join(config["paths"]["reports_dir"], "evaluation_report.md")
report_content = f"""# Rapport d'Évaluation des Modèles de Détection d'IA
Ce rapport présente les performances des différents modèles entraînés pour distinguer les discours politiques rédigés par des humains de ceux générés par intelligence artificielle.
## Performances des Modèles
| Modèle | Accuracy | Précision | Rappel | F1-Score | ROC-AUC |
| :--- | :---: | :---: | :---: | :---: | :---: |
"""
for r in results:
report_content += f"| {r['model']} | {r['accuracy']:.4f} | {r['precision']:.4f} | {r['recall']:.4f} | {r['f1']:.4f} | {r['auc']:.4f} |\n"
report_content += f"""
### Meilleur Modèle Sélectionné
Le modèle **{best_model_name}** a été sélectionné comme le meilleur détecteur. Il offre un F1-score de **{best_row['f1']:.4f}** et une aire sous la courbe ROC de **{best_row['auc']:.4f}**.
{importance_report}
## Matrices de Confusion
"""
for r in results:
cm = r["cm"]
report_content += f"""#### {r['model']}
- Vrais Humains (Corrects): {cm[0, 0]} | Faux IA (Faux Positifs): {cm[0, 1]}
- Faux Humains (Faux Négatifs): {cm[1, 0]} | Vrais IA (Corrects): {cm[1, 1]}
"""
with open(report_path, "w", encoding="utf-8") as f:
f.write(report_content)
print(f"\nWritten model evaluation report to {report_path}")
if __name__ == "__main__":
main()
|