AI_DETECTOR_SOTA / scripts /train_detector.py
simonlesaumon's picture
Upload folder using huggingface_hub
eb72d30 verified
Raw
History Blame Contribute Delete
12.3 kB
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()