ASI-Engineer commited on
Commit
e8e37bc
·
verified ·
1 Parent(s): 2303c41

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. main.py +175 -0
main.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Pipeline principal d'entraînement du modèle Employee Turnover.
4
+
5
+ Ce script enchaîne:
6
+ 1. Chargement et préprocessing des données
7
+ 2. Entraînement du modèle XGBoost avec RandomizedSearchCV et SMOTE
8
+ 3. Logging des résultats dans MLflow (params, metrics, artifacts, model)
9
+ 4. Sauvegarde des encoders et scaler pour utilisation future
10
+
11
+ Usage:
12
+ python main.py
13
+
14
+ Le modèle et les artifacts sont enregistrés dans MLflow pour:
15
+ - Suivi des expérimentations
16
+ - Reproductibilité
17
+ Déploiement via Model Registry
18
+ """
19
+ from pathlib import Path
20
+
21
+ import joblib
22
+ import mlflow
23
+ import mlflow.sklearn
24
+ from ml_model.preprocess import preprocess_data
25
+ from ml_model.train_model import train_model
26
+
27
+
28
+ def main():
29
+ """Pipeline principal d'entraînement."""
30
+ print("=" * 80)
31
+ print("🚀 PIPELINE D'ENTRAÎNEMENT - Employee Turnover Prediction")
32
+ print("=" * 80)
33
+ print()
34
+
35
+ # Configuration MLflow
36
+ mlflow.set_tracking_uri("sqlite:///mlflow.db")
37
+ mlflow.set_experiment("Employee_Turnover_Training")
38
+
39
+ print("📊 Configuration MLflow:")
40
+ print(f" Tracking URI: {mlflow.get_tracking_uri()}")
41
+ print(" Experiment: Employee_Turnover_Training")
42
+ print()
43
+
44
+ # Chemins des données
45
+ data_paths = {
46
+ "sondage_path": "data/extrait_sondage.csv",
47
+ "eval_path": "data/extrait_eval.csv",
48
+ "sirh_path": "data/extrait_sirh.csv",
49
+ }
50
+
51
+ # Vérifier que les fichiers existent
52
+ for name, path in data_paths.items():
53
+ if not Path(path).exists():
54
+ raise FileNotFoundError(f"❌ Fichier manquant: {path}")
55
+
56
+ print("✅ Fichiers de données trouvés")
57
+ print()
58
+
59
+ # ========================================================================
60
+ # ÉTAPE 1 : Préprocessing
61
+ # ========================================================================
62
+ print("1️⃣ PRÉPROCESSING")
63
+ print("-" * 80)
64
+
65
+ X, y, scaler, onehot_encoder, ordinal_encoder = preprocess_data(data_paths)
66
+
67
+ print(f" Forme X: {X.shape}")
68
+ print(f" Forme y: {y.shape}")
69
+ print(f" Classes: {y.value_counts().to_dict()}")
70
+ print(f" Ratio déséquilibre: {(y == 0).sum() / (y == 1).sum():.2f}:1")
71
+ print()
72
+
73
+ # ========================================================================
74
+ # ÉTAPE 2 : Entraînement avec MLflow tracking
75
+ # ========================================================================
76
+ print("2️⃣ ENTRAÎNEMENT")
77
+ print("-" * 80)
78
+
79
+ # Entraînement (déjà avec MLflow tracking dans train_model.py)
80
+ model, best_params, cv_f1 = train_model(X, y)
81
+
82
+ print(" ✅ Modèle entraîné")
83
+ print(f" 🏆 Meilleur F1 CV: {cv_f1:.4f}")
84
+ print()
85
+
86
+ # Récupérer le run actif pour sauvegarder les artifacts
87
+ active_run = mlflow.active_run()
88
+ if active_run is None:
89
+ # Si train_model a fermé le run, on en ouvre un nouveau
90
+ active_run = mlflow.start_run()
91
+ run_id = active_run.info.run_id
92
+ should_end_run = True
93
+ else:
94
+ run_id = active_run.info.run_id
95
+ should_end_run = False
96
+
97
+ # Log des infos dataset
98
+ mlflow.log_param("n_samples", len(X))
99
+ mlflow.log_param("n_features", X.shape[1])
100
+ mlflow.log_param("class_ratio", f"{(y == 0).sum()}:{(y == 1).sum()}")
101
+
102
+ # ========================================================================
103
+ # ÉTAPE 3 : Sauvegarde des artifacts (encoders, scaler)
104
+ # ========================================================================
105
+ print("3️⃣ SAUVEGARDE DES ARTIFACTS")
106
+ print("-" * 80)
107
+
108
+ # Créer dossier temporaire pour artifacts
109
+ artifacts_dir = Path("artifacts_temp")
110
+ artifacts_dir.mkdir(exist_ok=True)
111
+
112
+ # Sauvegarder scaler
113
+ scaler_path = artifacts_dir / "scaler.joblib"
114
+ joblib.dump(scaler, scaler_path)
115
+ mlflow.log_artifact(str(scaler_path), artifact_path="preprocessing")
116
+ print(" ✅ Scaler sauvegardé")
117
+
118
+ # Sauvegarder encoders (onehot et ordinal)
119
+ onehot_path = artifacts_dir / "onehot_encoder.joblib"
120
+ joblib.dump(onehot_encoder, onehot_path)
121
+ mlflow.log_artifact(str(onehot_path), artifact_path="preprocessing")
122
+
123
+ ordinal_path = artifacts_dir / "ordinal_encoder.joblib"
124
+ joblib.dump(ordinal_encoder, ordinal_path)
125
+ mlflow.log_artifact(str(ordinal_path), artifact_path="preprocessing")
126
+ print(" ✅ Encoders sauvegardés (OneHot + Ordinal)")
127
+
128
+ # Log git commit si disponible
129
+ try:
130
+ import subprocess
131
+
132
+ git_commit = (
133
+ subprocess.check_output(["git", "rev-parse", "HEAD"])
134
+ .strip()
135
+ .decode("utf-8")
136
+ )
137
+ mlflow.set_tag("git_commit", git_commit[:8])
138
+ print(f" ✅ Git commit: {git_commit[:8]}")
139
+ except Exception:
140
+ pass
141
+
142
+ # Nettoyer artifacts temporaires
143
+ scaler_path.unlink()
144
+ onehot_path.unlink()
145
+ ordinal_path.unlink()
146
+ artifacts_dir.rmdir()
147
+
148
+ print()
149
+
150
+ # Fermer le run si on l'a ouvert
151
+ if should_end_run:
152
+ mlflow.end_run()
153
+
154
+ # ========================================================================
155
+ # RÉSUMÉ
156
+ # ========================================================================
157
+ print("=" * 80)
158
+ print("✅ ENTRAÎNEMENT TERMINÉ")
159
+ print("=" * 80)
160
+ print()
161
+ print(f"📊 Run ID: {run_id}")
162
+ print(f"🎯 F1 Score (CV): {cv_f1:.4f}")
163
+ print("📦 Artifacts sauvegardés dans MLflow")
164
+ print()
165
+ print("🌐 Pour visualiser les résultats:")
166
+ print(" ./scripts/start_mlflow.sh")
167
+ print(" ou: mlflow ui --backend-store-uri sqlite:///mlflow.db")
168
+ print()
169
+ print("📝 Pour charger le modèle:")
170
+ print(f" model = mlflow.sklearn.load_model('runs:/{run_id}/model')")
171
+ print()
172
+
173
+
174
+ if __name__ == "__main__":
175
+ main()