OthmaneW commited on
Commit
e5ddd67
·
verified ·
1 Parent(s): f0d9c0a

Déploiement initial de l'IA (RF + SHAP)

Browse files
Files changed (9) hide show
  1. .gitattributes +1 -0
  2. api.py +407 -0
  3. app.py +169 -0
  4. creditcard.csv +3 -0
  5. data_prep.py +207 -0
  6. explain.py +305 -0
  7. requirements.txt +31 -0
  8. train_autoencoder.py +388 -0
  9. train_baseline.py +272 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ creditcard.csv filter=lfs diff=lfs merge=lfs -text
api.py ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ api.py — API de Détection de Fraude v2.0
3
+ ==========================================
4
+ PFA : Système de Détection d'Anomalies dans les Transactions Financières
5
+
6
+ Auteurs : Othmane & Ramzi
7
+ Framework : FastAPI + Uvicorn
8
+ Session 1 : POST /predict — Random Forest
9
+ Session 2 : POST /explain — RF + SHAP
10
+ POST /analyze — RF + Autoencoder + SHAP (pipeline complet)
11
+
12
+ Usage : uvicorn api:app --host 0.0.0.0 --port 8000 --reload
13
+ Docs : http://localhost:8000/docs
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import time
20
+ from contextlib import asynccontextmanager
21
+ from typing import Any, Optional
22
+
23
+ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
24
+
25
+ import joblib
26
+ import numpy as np
27
+ from fastapi import FastAPI, HTTPException
28
+ from pydantic import BaseModel, Field, field_validator
29
+
30
+ import shap
31
+
32
+
33
+ # ─────────────────────────────────────────────────────────────
34
+ # Chemins
35
+ # ─────────────────────────────────────────────────────────────
36
+
37
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
38
+ MODEL_PATH = os.path.join(BASE_DIR, "models", "baseline_model.pkl")
39
+ SCALER_PATH = os.path.join(BASE_DIR, "data", "scaler.pkl")
40
+ AE_PATH = os.path.join(BASE_DIR, "models", "autoencoder.keras")
41
+ THRESHOLD_PATH = os.path.join(BASE_DIR, "models", "threshold.pkl")
42
+
43
+ N_FEATURES = 30
44
+ FEATURE_NAMES = [f"V{i}" for i in range(1, 29)] + ["Time", "Amount"]
45
+
46
+
47
+ # ─────────────────────────────────────────────────────────────
48
+ # Ressources globales (chargées une seule fois)
49
+ # ─────────────────────────────────────────────────────────────
50
+
51
+ resources: dict[str, Any] = {
52
+ "rf_model": None,
53
+ "scaler": None,
54
+ "ae_model": None,
55
+ "threshold": None,
56
+ "explainer": None,
57
+ "ae_ready": False,
58
+ }
59
+
60
+
61
+ @asynccontextmanager
62
+ async def lifespan(app: FastAPI):
63
+ """Charge tous les modèles au démarrage."""
64
+ print("Demarrage de l'API v2.0 — Chargement des modeles...")
65
+
66
+ # ── Random Forest (obligatoire) ───────────────────────────
67
+ if not os.path.exists(MODEL_PATH):
68
+ raise RuntimeError(f"Modele introuvable : {MODEL_PATH} → python train_baseline.py")
69
+ resources["rf_model"] = joblib.load(MODEL_PATH)
70
+ print(f" [OK] Random Forest charge")
71
+
72
+ # ── Scaler (obligatoire) ──────────────────────────────────
73
+ if not os.path.exists(SCALER_PATH):
74
+ raise RuntimeError(f"Scaler introuvable : {SCALER_PATH} → python data_prep.py")
75
+ resources["scaler"] = joblib.load(SCALER_PATH)
76
+ print(f" [OK] Scaler charge")
77
+
78
+ # ── SHAP TreeExplainer ────────────────────────────────────
79
+ resources["explainer"] = shap.TreeExplainer(resources["rf_model"])
80
+ print(f" [OK] SHAP TreeExplainer pret")
81
+
82
+ # ── Autoencoder (optionnel — Session 2) ───────────────────
83
+ if os.path.exists(AE_PATH) and os.path.exists(THRESHOLD_PATH):
84
+ try:
85
+ import tensorflow as tf
86
+ resources["ae_model"] = tf.keras.models.load_model(AE_PATH)
87
+ resources["threshold"] = joblib.load(THRESHOLD_PATH)
88
+ resources["ae_ready"] = True
89
+ print(f" [OK] Autoencoder charge (seuil = {resources['threshold']:.6f})")
90
+ except Exception as e:
91
+ print(f" [!] Autoencoder non disponible : {e}")
92
+ else:
93
+ print(f" [!] Autoencoder non trouve — /analyze utilisera RF seul")
94
+
95
+ print(" API prete sur http://localhost:8000/docs\n")
96
+ yield
97
+
98
+ for k in resources:
99
+ resources[k] = None
100
+ print("Arret de l'API.")
101
+
102
+
103
+ # ─────────────────────────────────────────────────────────────
104
+ # Application
105
+ # ─────────────────────────────────────────────────────────────
106
+
107
+ app = FastAPI(
108
+ title="API Detection de Fraude — PFA",
109
+ description=(
110
+ "Systeme IA hybride de detection d'anomalies dans les transactions financieres.\n\n"
111
+ "**Auteurs** : Othmane & Ramzi — 4eme annee IA/Data\n\n"
112
+ "**Session 1** : Random Forest Baseline\n"
113
+ "**Session 2** : Autoencoder + SHAP XAI\n"
114
+ "**Dataset** : Kaggle Credit Card Fraud Detection"
115
+ ),
116
+ version="2.0.0",
117
+ lifespan=lifespan,
118
+ )
119
+
120
+
121
+ # ─────────────────────────────────────────────────────────────
122
+ # Schémas Pydantic
123
+ # ─────────────────────────────────────────────────────────────
124
+
125
+ class TransactionRequest(BaseModel):
126
+ """
127
+ Payload d'une transaction. Features dans l'ordre :
128
+ [V1, V2, ..., V28, Time (secondes), Amount (euros)]
129
+ """
130
+ features: list[float] = Field(
131
+ ...,
132
+ min_length=N_FEATURES,
133
+ max_length=N_FEATURES,
134
+ description="30 features : V1-V28 + Time (s) + Amount (EUR)",
135
+ example=[
136
+ -1.36, -0.07, 2.54, 1.38, -0.34, 0.46, 0.24, 0.10,
137
+ 0.36, 0.09, -0.55, -0.62, -0.99, -0.31, 1.47, -0.47,
138
+ 0.21, 0.03, 0.40, 0.25, -0.02, 0.28, -0.11, 0.07,
139
+ 0.13, -0.19, 0.13, -0.02, 0.0, 149.62,
140
+ ],
141
+ )
142
+
143
+ @field_validator("features")
144
+ @classmethod
145
+ def check_length(cls, v):
146
+ if len(v) != N_FEATURES:
147
+ raise ValueError(f"Attendu {N_FEATURES} features, recu {len(v)}")
148
+ return v
149
+
150
+
151
+ class FeatureContribution(BaseModel):
152
+ rank: int
153
+ feature: str
154
+ shap_value: float
155
+ feature_value: float
156
+ direction: str
157
+
158
+
159
+ class PredictionResponse(BaseModel):
160
+ prediction: int
161
+ label: str
162
+ probability_fraud: float
163
+ confidence: str
164
+ latency_ms: float
165
+
166
+
167
+ class ExplainResponse(BaseModel):
168
+ prediction: int
169
+ label: str
170
+ probability_fraud: float
171
+ confidence: str
172
+ top_features: list[FeatureContribution]
173
+ base_value: float
174
+ latency_ms: float
175
+
176
+
177
+ class AnalyzeResponse(BaseModel):
178
+ # Prédictions
179
+ rf_prediction: int
180
+ rf_probability: float
181
+ ae_prediction: Optional[int]
182
+ ae_error: Optional[float]
183
+ ae_threshold: Optional[float]
184
+ final_prediction: int
185
+ label: str
186
+ confidence: str
187
+ # Explication
188
+ top_features: list[FeatureContribution]
189
+ # Méta
190
+ ae_available: bool
191
+ latency_ms: float
192
+
193
+
194
+ class HealthResponse(BaseModel):
195
+ model_config = {"protected_namespaces": ()}
196
+ status: str
197
+ model_loaded: bool
198
+ ae_available: bool
199
+ version: str
200
+
201
+
202
+ # ─────────────────────────────────────────────────────────────
203
+ # Utilitaires internes
204
+ # ─────────────────────────────────────────────────────────────
205
+
206
+ def _normalize(features: np.ndarray) -> np.ndarray:
207
+ """Normalise Time et Amount avec le scaler, laisse V1-V28 intacts."""
208
+ feat = features.copy()
209
+ ta_scaled = resources["scaler"].transform(feat[:, 28:30])
210
+ feat[:, 28] = ta_scaled[:, 0]
211
+ feat[:, 29] = ta_scaled[:, 1]
212
+ return feat
213
+
214
+
215
+ def _get_confidence(prob: float) -> str:
216
+ if prob >= 0.8: return "Tres elevee"
217
+ if prob >= 0.5: return "Elevee"
218
+ if prob >= 0.2: return "Moderee"
219
+ return "Faible"
220
+
221
+
222
+ def _shap_top_features(X: np.ndarray, top_n: int = 5) -> tuple[list, float]:
223
+ """Retourne top N features SHAP + base_value."""
224
+ shap_vals_all = resources["explainer"].shap_values(X)
225
+ if isinstance(shap_vals_all, list):
226
+ sv = shap_vals_all[1][0]
227
+ else:
228
+ sv = shap_vals_all[0, :, 1] if len(shap_vals_all.shape) == 3 else shap_vals_all[0]
229
+ base = (resources["explainer"].expected_value[1]
230
+ if isinstance(resources["explainer"].expected_value, (list, np.ndarray))
231
+ else resources["explainer"].expected_value)
232
+
233
+ sorted_idx = np.argsort(np.abs(sv))[::-1]
234
+ top = []
235
+ for rank, idx in enumerate(sorted_idx[:top_n]):
236
+ i = int(idx)
237
+ top.append(FeatureContribution(
238
+ rank=rank + 1,
239
+ feature=FEATURE_NAMES[i],
240
+ shap_value=round(float(sv[i]), 6),
241
+ feature_value=round(float(X[0, i]), 6),
242
+ direction="Augmente risque fraude" if sv[i] > 0 else "Reduit risque fraude",
243
+ ))
244
+ return top, float(base)
245
+
246
+
247
+ # ─────────────────────────────────────────────────────────────
248
+ # Routes
249
+ # ─────────────────────────────────────────────────────────────
250
+
251
+ @app.get("/health", response_model=HealthResponse, tags=["Monitoring"])
252
+ async def health_check():
253
+ """Statut de l'API et des modèles chargés."""
254
+ return HealthResponse(
255
+ status="healthy" if resources["rf_model"] else "degraded",
256
+ model_loaded=resources["rf_model"] is not None,
257
+ ae_available=resources["ae_ready"],
258
+ version="2.0.0",
259
+ )
260
+
261
+
262
+ @app.post(
263
+ "/predict",
264
+ response_model=PredictionResponse,
265
+ summary="Prediction (Random Forest)",
266
+ tags=["Session 1 — Detection"],
267
+ )
268
+ async def predict(request: TransactionRequest) -> PredictionResponse:
269
+ """
270
+ **Session 1** — Prédit si une transaction est frauduleuse via Random Forest.
271
+
272
+ Retourne la classe (0/1), la probabilité de fraude et le niveau de confiance.
273
+ """
274
+ if resources["rf_model"] is None:
275
+ raise HTTPException(503, "Modele RF non disponible")
276
+
277
+ t0 = time.perf_counter()
278
+
279
+ X = np.array(request.features, dtype=np.float64).reshape(1, -1)
280
+ X = _normalize(X)
281
+
282
+ pred = int(resources["rf_model"].predict(X)[0])
283
+ prob = float(resources["rf_model"].predict_proba(X)[0, 1])
284
+ latency = round((time.perf_counter() - t0) * 1000, 3)
285
+
286
+ return PredictionResponse(
287
+ prediction=pred,
288
+ label="Fraude" if pred == 1 else "Legitime",
289
+ probability_fraud=round(prob, 6),
290
+ confidence=_get_confidence(prob),
291
+ latency_ms=latency,
292
+ )
293
+
294
+
295
+ @app.post(
296
+ "/explain",
297
+ response_model=ExplainResponse,
298
+ summary="Prediction + Explication SHAP",
299
+ tags=["Session 2 — XAI"],
300
+ )
301
+ async def explain(request: TransactionRequest) -> ExplainResponse:
302
+ """
303
+ **Session 2** — Prédit + explique via SHAP TreeExplainer.
304
+
305
+ Retourne les **5 features** qui ont le plus influencé la décision,
306
+ avec leur valeur SHAP (positive = pousse vers fraude, négative = légitime).
307
+ """
308
+ if resources["rf_model"] is None:
309
+ raise HTTPException(503, "Modele RF non disponible")
310
+
311
+ t0 = time.perf_counter()
312
+
313
+ X = np.array(request.features, dtype=np.float64).reshape(1, -1)
314
+ X = _normalize(X)
315
+
316
+ pred = int(resources["rf_model"].predict(X)[0])
317
+ prob = float(resources["rf_model"].predict_proba(X)[0, 1])
318
+ top_features, base_val = _shap_top_features(X)
319
+ latency = round((time.perf_counter() - t0) * 1000, 3)
320
+
321
+ return ExplainResponse(
322
+ prediction=pred,
323
+ label="Fraude" if pred == 1 else "Legitime",
324
+ probability_fraud=round(prob, 6),
325
+ confidence=_get_confidence(prob),
326
+ top_features=top_features,
327
+ base_value=round(base_val, 6),
328
+ latency_ms=latency,
329
+ )
330
+
331
+
332
+ @app.post(
333
+ "/analyze",
334
+ response_model=AnalyzeResponse,
335
+ summary="Analyse Complete (RF + Autoencoder + SHAP)",
336
+ tags=["Session 2 — XAI"],
337
+ )
338
+ async def analyze(request: TransactionRequest) -> AnalyzeResponse:
339
+ """
340
+ **Session 2** — Pipeline complet de détection et d'explication.
341
+
342
+ 1. **Random Forest** : détection supervisée (post-SMOTE)
343
+ 2. **Autoencoder** : détection par anomalie de reconstruction (si disponible)
344
+ 3. **Règle de fusion** : fraude si RF **OU** Autoencoder dit fraude
345
+ 4. **SHAP** : explication des 5 features les plus influentes (RF)
346
+
347
+ C'est la route principale du système hybride.
348
+ """
349
+ if resources["rf_model"] is None:
350
+ raise HTTPException(503, "Modele RF non disponible")
351
+
352
+ t0 = time.perf_counter()
353
+
354
+ X = np.array(request.features, dtype=np.float64).reshape(1, -1)
355
+ X = _normalize(X)
356
+
357
+ # ── Random Forest ──────────────────────────────────────────
358
+ rf_pred = int(resources["rf_model"].predict(X)[0])
359
+ rf_prob = float(resources["rf_model"].predict_proba(X)[0, 1])
360
+
361
+ # ── Autoencoder ───────────────────────────────────────────
362
+ ae_pred = ae_err = ae_thr = None
363
+ if resources["ae_ready"] and resources["ae_model"] is not None:
364
+ reconstruction = resources["ae_model"].predict(X, verbose=0)
365
+ ae_err = float(np.mean(np.power(X - reconstruction, 2)))
366
+ ae_thr = float(resources["threshold"])
367
+ ae_pred = int(ae_err > ae_thr)
368
+
369
+ # ── Fusion OR ─────────────────────────────────────────────
370
+ if ae_pred is not None:
371
+ final_pred = int(max(rf_pred, ae_pred))
372
+ else:
373
+ final_pred = rf_pred
374
+
375
+ # Probabilité finale : max des deux signaux
376
+ final_prob = rf_prob
377
+ if ae_pred is not None and ae_thr and ae_thr > 0:
378
+ ae_prob = min(ae_err / (ae_thr * 3), 1.0)
379
+ final_prob = max(rf_prob, ae_prob)
380
+
381
+ # ── SHAP ──────────────────────────────────────────────────
382
+ top_features, _ = _shap_top_features(X)
383
+
384
+ latency = round((time.perf_counter() - t0) * 1000, 3)
385
+
386
+ return AnalyzeResponse(
387
+ rf_prediction=rf_pred,
388
+ rf_probability=round(rf_prob, 6),
389
+ ae_prediction=ae_pred,
390
+ ae_error=round(ae_err, 6) if ae_err is not None else None,
391
+ ae_threshold=round(ae_thr, 6) if ae_thr is not None else None,
392
+ final_prediction=final_pred,
393
+ label="Fraude" if final_pred == 1 else "Legitime",
394
+ confidence=_get_confidence(final_prob),
395
+ top_features=top_features,
396
+ ae_available=resources["ae_ready"],
397
+ latency_ms=latency,
398
+ )
399
+
400
+
401
+ # ─────────────────────────────────────────────────────────────
402
+ # Entry point
403
+ # ─────────────────────────────────────────────────────────────
404
+
405
+ if __name__ == "__main__":
406
+ import uvicorn
407
+ uvicorn.run("api:app", host="0.0.0.0", port=8000, reload=True, log_level="info")
app.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ app.py — Interface Graphique pour Hugging Face Spaces (Gradio)
3
+ ==============================================================
4
+ PFA : Système de Détection d'Anomalies dans les Transactions Financières
5
+
6
+ Auteurs : Othmane & Ramzi
7
+ Technologie: Gradio, scikit-learn, SHAP
8
+ Déploiement: Hugging Face Spaces
9
+
10
+ Usage local: python app.py
11
+ """
12
+
13
+ import os
14
+ import joblib
15
+ import numpy as np
16
+ import pandas as pd
17
+ import gradio as gr
18
+ import matplotlib.pyplot as plt
19
+
20
+ # Import notre module XAI
21
+ from explain import load_explainer, explain_transaction, plot_waterfall
22
+
23
+ # ─────────────────────────────────────────────────────────────
24
+ # Chemins
25
+ # ─────────────────────────────────────────────────────────────
26
+
27
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
28
+ MODEL_PATH = os.path.join(BASE_DIR, "models", "baseline_model.pkl")
29
+ SCALER_PATH = os.path.join(BASE_DIR, "data", "scaler.pkl")
30
+
31
+ # ─────────────────────────────────────────────────────────────
32
+ # Initialisation Globale
33
+ # ─────────────────────────────────────────────────────────────
34
+
35
+ print("Chargement des modèles et des données pour l'interface...")
36
+
37
+ # 1. Modèle et Scaler
38
+ try:
39
+ rf_model = joblib.load(MODEL_PATH)
40
+ scaler = joblib.load(SCALER_PATH)
41
+ explainer, _ = load_explainer(MODEL_PATH)
42
+ except Exception as e:
43
+ raise RuntimeError(f"Erreur au chargement des modèles : {e}")
44
+
45
+ # 2. Données de test pour les exemples
46
+ X_test = joblib.load(os.path.join(BASE_DIR, "data", "X_test.pkl"))
47
+ y_test = joblib.load(os.path.join(BASE_DIR, "data", "y_test.pkl"))
48
+
49
+ if hasattr(X_test, 'values'):
50
+ X_test_arr = X_test.values
51
+ y_test_arr = np.array(y_test)
52
+ else:
53
+ X_test_arr = X_test
54
+ y_test_arr = np.array(y_test)
55
+
56
+ # Extraire 5 fraudes et 5 légitimes pour notre menu déroulant
57
+ fraud_idx = np.where(y_test_arr == 1)[0][:5]
58
+ legit_idx = np.where(y_test_arr == 0)[0][:5]
59
+
60
+ # Dictionnaire associant un nom clair à l'index de la transaction
61
+ examples_dict = {}
62
+ for i, idx in enumerate(fraud_idx):
63
+ examples_dict[f"🔴 Cas de Fraude #{i+1}"] = idx
64
+ for i, idx in enumerate(legit_idx):
65
+ examples_dict[f"🟢 Transaction Légitime #{i+1}"] = idx
66
+
67
+ example_names = list(examples_dict.keys())
68
+
69
+
70
+ # ─────────────────────────────────────────────────────────────
71
+ # Logique de prédiction et d'explication
72
+ # ─────────────────────────────────────────────────────────────
73
+
74
+ def analyze_transaction(selected_example: str):
75
+ """
76
+ Fonction appelée lorsque l'utilisateur clique sur "Analyser".
77
+ """
78
+ if not selected_example:
79
+ return "Veuillez sélectionner une transaction.", None
80
+
81
+ # 1. Récupération des features
82
+ idx = examples_dict[selected_example]
83
+ features_raw = X_test_arr[idx].reshape(1, -1)
84
+
85
+ # NB: Dans notre pipeline actuel, X_test contient des features DÉJÀ normalisées
86
+ # car data_prep.py normalise avant le split.
87
+ # Le modèle peut donc consommer ces données directement.
88
+ features = features_raw
89
+ true_label = int(y_test_arr[idx])
90
+
91
+ # 2. Prédiction
92
+ pred = int(rf_model.predict(features)[0])
93
+ prob = float(rf_model.predict_proba(features)[0, 1])
94
+
95
+ # 3. Explication SHAP
96
+ shap_result = explain_transaction(features, explainer)
97
+
98
+ # 4. Génération de l'image Waterfall
99
+ plot_path = plot_waterfall(
100
+ features=features,
101
+ shap_result=shap_result,
102
+ transaction_id=str(idx),
103
+ prediction=pred
104
+ )
105
+
106
+ # 5. Formatage de la réponse texte
107
+ texte_resultat = f"### Résultat du Modèle IA\n\n"
108
+ if pred == 1:
109
+ texte_resultat += f"**Verdict** : 🚨 FRAUDE DÉTECTÉE\n"
110
+ texte_resultat += f"**Confiance** : {prob*100:.1f} %\n"
111
+ else:
112
+ texte_resultat += f"**Verdict** : ✅ TRANSACTION LÉGITIME\n"
113
+ texte_resultat += f"**Risque de fraude** : {prob*100:.1f} %\n"
114
+
115
+ texte_resultat += f"\n*Classe réelle dans le dataset : {'Fraude 🔴' if true_label == 1 else 'Légitime 🟢'}*"
116
+
117
+ return texte_resultat, plot_path
118
+
119
+
120
+ # ─────────────────────────────────────────────────────────────
121
+ # Interface Graphique Gradio
122
+ # ───────────────────────���─────────────────────────────────────
123
+
124
+ # Thème élégant personnalisé
125
+ theme = gr.themes.Soft(
126
+ primary_hue="blue",
127
+ secondary_hue="gray",
128
+ font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"]
129
+ )
130
+
131
+ with gr.Blocks(theme=theme, title="Détection de Fraude") as demo:
132
+ gr.Markdown(
133
+ """
134
+ # 🕵️‍♂️ Système Hybride de Détection de Fraude Financière
135
+ **Projet de Fin d'Année (IA & Data)** — Othmane & Ramzi
136
+
137
+ Cette interface montre l'action de notre modèle **Random Forest** accompagné d'une **IA Explicable (XAI)** via SHAP pour comprendre *pourquoi* une transaction est bloquée ou autorisée.
138
+ """
139
+ )
140
+
141
+ with gr.Row():
142
+ with gr.Column(scale=1):
143
+ gr.Markdown("### 1. Sélectionner une transaction test")
144
+ dropdown = gr.Dropdown(
145
+ choices=example_names,
146
+ label="Transaction à analyser",
147
+ info="Choisissez parmi des exemples réels tirés de notre test set."
148
+ )
149
+ btn_analyze = gr.Button("🔍 Analyser la transaction", variant="primary")
150
+
151
+ output_text = gr.Markdown()
152
+
153
+ with gr.Column(scale=2):
154
+ gr.Markdown("### 2. Explication de la décision (SHAP)")
155
+ output_image = gr.Image(label="Waterfall Plot (XAI)", type="filepath")
156
+
157
+ # Connecter le bouton à la fonction
158
+ btn_analyze.click(
159
+ fn=analyze_transaction,
160
+ inputs=[dropdown],
161
+ outputs=[output_text, output_image]
162
+ )
163
+
164
+ # ─────────────────────────────────────────────────────────────
165
+ # Lancement Local
166
+ # ─────────────────────────────────────────────────────────────
167
+ if __name__ == "__main__":
168
+ print("Démarrage du serveur Gradio...")
169
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
creditcard.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:76274b691b16a6c49d3f159c883398e03ccd6d1ee12d9d8ee38f4b4b98551a89
3
+ size 150828752
data_prep.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ data_prep.py — Pipeline de Préparation des Données
3
+ ====================================================
4
+ PFA : Système de Détection d'Anomalies dans les Transactions Financières
5
+
6
+ Auteurs : Othmane & Ramzi
7
+ Dataset : Kaggle Credit Card Fraud Detection (creditcard.csv)
8
+ Sortie : Datasets transformés dans ./data/ (format .pkl)
9
+
10
+ Usage : python data_prep.py
11
+ """
12
+
13
+ import os
14
+ import joblib
15
+ import pandas as pd
16
+ import numpy as np
17
+ from sklearn.model_selection import train_test_split
18
+ from sklearn.preprocessing import StandardScaler
19
+ from imblearn.over_sampling import SMOTE
20
+
21
+
22
+ # ─────────────────────────────────────────────────────────────
23
+ # Configuration
24
+ # ─────────────────────────────────────────────────────────────
25
+
26
+ DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
27
+ CSV_PATH = os.path.join(os.path.dirname(__file__), "creditcard.csv")
28
+ RANDOM_STATE = 42
29
+ TEST_SIZE = 0.2
30
+
31
+
32
+ # ─────────────────────────────────────────────────────────────
33
+ # 1. Chargement des données
34
+ # ─────────────────────────────────────────────────────────────
35
+
36
+ def load_data(path: str) -> pd.DataFrame:
37
+ """Charge le CSV et affiche les statistiques de base."""
38
+ print(f"[1/5] Chargement du dataset : {path}")
39
+ df = pd.read_csv(path)
40
+
41
+ print(f" Shape : {df.shape}")
42
+ print(f" Colonnes : {list(df.columns)}")
43
+ print(f" Valeurs NaN : {df.isnull().sum().sum()}")
44
+
45
+ n_fraud = (df["Class"] == 1).sum()
46
+ n_legit = (df["Class"] == 0).sum()
47
+ pct_fraud = n_fraud / len(df) * 100
48
+ print(f"\n Distribution des classes :")
49
+ print(f" Légitimes (0) : {n_legit:,} ({100 - pct_fraud:.2f}%)")
50
+ print(f" Fraudes (1) : {n_fraud:,} ({pct_fraud:.4f}%)")
51
+
52
+ return df
53
+
54
+
55
+ # ─────────────────────────────────────────────────────────────
56
+ # 2. Préprocessing
57
+ # ─────────────────────────────────────────────────────────────
58
+
59
+ def preprocess(df: pd.DataFrame) -> tuple[pd.DataFrame, pd.Series, StandardScaler]:
60
+ """
61
+ Normalise les colonnes 'Time' et 'Amount' avec StandardScaler.
62
+ Les features V1–V28 sont déjà normalisées (résultat de PCA sur le dataset original).
63
+
64
+ Retourne : X (features), y (labels), scaler (pour réutilisation en inférence)
65
+ """
66
+ print("\n[2/5] Préprocessing — Normalisation de Time et Amount")
67
+
68
+ df = df.copy()
69
+
70
+ scaler = StandardScaler()
71
+ df[["Time", "Amount"]] = scaler.fit_transform(df[["Time", "Amount"]])
72
+
73
+ X = df.drop(columns=["Class"])
74
+ y = df["Class"]
75
+
76
+ print(f" Features : {X.shape[1]} colonnes")
77
+ print(f" Target : 'Class' (0=Légitime, 1=Fraude)")
78
+
79
+ return X, y, scaler
80
+
81
+
82
+ # ─────────────────────────────────────────────────────────────
83
+ # 3. Split Train / Test
84
+ # ─────────────────────────────────────────────────────────────
85
+
86
+ def split_data(
87
+ X: pd.DataFrame,
88
+ y: pd.Series,
89
+ test_size: float = TEST_SIZE,
90
+ random_state: int = RANDOM_STATE,
91
+ ) -> tuple:
92
+ """
93
+ Split stratifié 80/20.
94
+ La stratification garantit que la proportion de fraudes est préservée
95
+ dans les deux splits, malgré le déséquilibre extrême du dataset.
96
+ """
97
+ print(f"\n[3/5] Split Train/Test (stratifié, test_size={test_size})")
98
+
99
+ X_train, X_test, y_train, y_test = train_test_split(
100
+ X, y,
101
+ test_size=test_size,
102
+ random_state=random_state,
103
+ stratify=y,
104
+ )
105
+
106
+ print(f" Train : {X_train.shape[0]:,} samples "
107
+ f"(fraudes : {y_train.sum():,} — {y_train.mean()*100:.4f}%)")
108
+ print(f" Test : {X_test.shape[0]:,} samples "
109
+ f"(fraudes : {y_test.sum():,} — {y_test.mean()*100:.4f}%)")
110
+
111
+ return X_train, X_test, y_train, y_test
112
+
113
+
114
+ # ─────────────────────────────────────────────────────────────
115
+ # 4. SMOTE — Rééquilibrage (Train uniquement !)
116
+ # ────────────────���────────────────────────────────────────────
117
+
118
+ def apply_smote(
119
+ X_train: pd.DataFrame,
120
+ y_train: pd.Series,
121
+ random_state: int = RANDOM_STATE,
122
+ ) -> tuple[pd.DataFrame, pd.Series]:
123
+ """
124
+ Applique SMOTE sur le jeu d'entraînement UNIQUEMENT.
125
+
126
+ Raison critique : Appliquer SMOTE sur le test set provoquerait du
127
+ data leakage et des métriques artificiellement gonflées. Le test
128
+ set doit rester dans sa distribution naturelle (déséquilibrée)
129
+ pour simuler des conditions réelles de détection.
130
+ """
131
+ print("\n[4/5] Application de SMOTE (sur X_train/y_train uniquement)")
132
+ print(f" Avant SMOTE : {y_train.value_counts().to_dict()}")
133
+
134
+ smote = SMOTE(random_state=random_state)
135
+ X_train_res, y_train_res = smote.fit_resample(X_train, y_train)
136
+
137
+ print(f" Après SMOTE : {pd.Series(y_train_res).value_counts().to_dict()}")
138
+ print(f" Ratio : 1:1 (parfaitement équilibré)")
139
+
140
+ return X_train_res, y_train_res
141
+
142
+
143
+ # ─────────────────────────────────────────────────────────────
144
+ # 5. Sauvegarde des Artifacts
145
+ # ─────────────────────────────────────────────────────────────
146
+
147
+ def save_artifacts(
148
+ X_train: pd.DataFrame | np.ndarray,
149
+ X_test: pd.DataFrame | np.ndarray,
150
+ y_train: pd.Series | np.ndarray,
151
+ y_test: pd.Series | np.ndarray,
152
+ scaler: StandardScaler,
153
+ ) -> None:
154
+ """Sauvegarde tous les artifacts dans ./data/ au format .pkl."""
155
+ print(f"\n[5/5] Sauvegarde dans : {DATA_DIR}/")
156
+ os.makedirs(DATA_DIR, exist_ok=True)
157
+
158
+ artifacts = {
159
+ "X_train_balanced.pkl": X_train,
160
+ "X_test.pkl": X_test,
161
+ "y_train_balanced.pkl": y_train,
162
+ "y_test.pkl": y_test,
163
+ "scaler.pkl": scaler,
164
+ }
165
+
166
+ for filename, obj in artifacts.items():
167
+ path = os.path.join(DATA_DIR, filename)
168
+ joblib.dump(obj, path)
169
+ size_mb = os.path.getsize(path) / 1_000_000
170
+ print(f" [OK] {filename:<30} ({size_mb:.2f} MB)")
171
+
172
+ print("\n[DONE] Pipeline de donnees terminee avec succes.")
173
+
174
+
175
+ # ─────────────────────────────────────────────────────────────
176
+ # Main
177
+ # ─────────────────────────────────────────────────────────────
178
+
179
+ def main():
180
+ print("=" * 60)
181
+ print(" PFA — Pipeline de Préparation des Données")
182
+ print("=" * 60)
183
+
184
+ # 1. Chargement
185
+ df = load_data(CSV_PATH)
186
+
187
+ # 2. Préprocessing
188
+ X, y, scaler = preprocess(df)
189
+
190
+ # 3. Split
191
+ X_train, X_test, y_train, y_test = split_data(X, y)
192
+
193
+ # 4. SMOTE (train uniquement)
194
+ X_train_balanced, y_train_balanced = apply_smote(X_train, y_train)
195
+
196
+ # 5. Sauvegarde
197
+ save_artifacts(X_train_balanced, X_test, y_train_balanced, y_test, scaler)
198
+
199
+ print("\n--- Recapitulatif final ---")
200
+ print(f" X_train_balanced : {X_train_balanced.shape}")
201
+ print(f" X_test : {X_test.shape}")
202
+ print(f" y_train_balanced : {pd.Series(y_train_balanced).value_counts().to_dict()}")
203
+ print(f" y_test : {y_test.value_counts().to_dict()}")
204
+
205
+
206
+ if __name__ == "__main__":
207
+ main()
explain.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ explain.py — Module XAI : Explainabilité avec SHAP
3
+ ====================================================
4
+ PFA : Système de Détection d'Anomalies dans les Transactions Financières
5
+
6
+ Auteurs : Othmane & Ramzi
7
+ Technologie: SHAP (TreeExplainer pour Random Forest)
8
+
9
+ Ce module est réutilisable :
10
+ - Par l'API (route /explain)
11
+ - En standalone pour générer des rapports d'explication
12
+
13
+ Usage : python explain.py
14
+ """
15
+
16
+ import os
17
+ import json
18
+ import joblib
19
+ import numpy as np
20
+ import matplotlib
21
+ matplotlib.use("Agg")
22
+ import matplotlib.pyplot as plt
23
+
24
+ import shap
25
+
26
+
27
+ # ─────────────────────────────────────────────────────────────
28
+ # Configuration
29
+ # ─────────────────────────────────────────────────────────────
30
+
31
+ DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
32
+ MODELS_DIR = os.path.join(os.path.dirname(__file__), "models")
33
+ REPORTS_DIR = os.path.join(os.path.dirname(__file__), "reports")
34
+
35
+ FEATURE_NAMES = [f"V{i}" for i in range(1, 29)] + ["Time", "Amount"]
36
+ TOP_N_FEATURES = 5
37
+
38
+
39
+ # ─────────────────────────────────────────────────────────────
40
+ # Chargement des ressources
41
+ # ─────────────────────────────────────────────────────────────
42
+
43
+ def load_explainer(model_path: str = None) -> shap.TreeExplainer:
44
+ """
45
+ Charge le Random Forest et crée un TreeExplainer SHAP.
46
+
47
+ TreeExplainer est la méthode optimale pour les modèles basés
48
+ sur des arbres (Random Forest, XGBoost, LightGBM). Il calcule
49
+ les valeurs SHAP de manière exacte en O(TLD) où :
50
+ T = nombre d'arbres, L = feuilles max, D = profondeur max.
51
+ """
52
+ if model_path is None:
53
+ model_path = os.path.join(MODELS_DIR, "baseline_model.pkl")
54
+
55
+ if not os.path.exists(model_path):
56
+ raise FileNotFoundError(
57
+ f"Modèle introuvable : {model_path}\n"
58
+ "→ Lancez d'abord : python train_baseline.py"
59
+ )
60
+
61
+ model = joblib.load(model_path)
62
+ explainer = shap.TreeExplainer(model)
63
+ return explainer, model
64
+
65
+
66
+ # ─────────────────────────────────────────────────────────────
67
+ # Explication d'une transaction
68
+ # ─────────────────────────────────────────────────────────────
69
+
70
+ def explain_transaction(
71
+ features: np.ndarray,
72
+ explainer: shap.TreeExplainer,
73
+ top_n: int = TOP_N_FEATURES,
74
+ ) -> dict:
75
+ """
76
+ Calcule les valeurs SHAP pour une transaction et retourne
77
+ les N features les plus influentes.
78
+
79
+ Args:
80
+ features : array (1, 30) — features normalisées
81
+ explainer : TreeExplainer pré-chargé
82
+ top_n : nombre de features à retourner
83
+
84
+ Returns:
85
+ dict contenant :
86
+ - shap_values : valeurs SHAP pour la classe fraude
87
+ - top_features : top N features (nom + valeur SHAP + valeur originale)
88
+ - base_value : valeur de base (prior du modèle)
89
+ - prediction_contribution : somme des SHAP (= logit shift)
90
+ """
91
+ if features.ndim == 1:
92
+ features = features.reshape(1, -1)
93
+
94
+ # Calcul SHAP — classe 1 (fraude)
95
+ shap_values_all = explainer.shap_values(features)
96
+
97
+ # Pour un RF binaire, shap_values est une liste [class0, class1]
98
+ if isinstance(shap_values_all, list):
99
+ shap_fraud = shap_values_all[1][0]
100
+ else:
101
+ if len(shap_values_all.shape) == 3:
102
+ shap_fraud = shap_values_all[0, :, 1]
103
+ else:
104
+ shap_fraud = shap_values_all[0]
105
+
106
+ base_value = (
107
+ explainer.expected_value[1]
108
+ if isinstance(explainer.expected_value, (list, np.ndarray))
109
+ else explainer.expected_value
110
+ )
111
+
112
+ # Tri par valeur absolue SHAP décroissante
113
+ abs_shap = np.abs(shap_fraud)
114
+ sorted_idx = np.argsort(abs_shap)[::-1]
115
+
116
+ top_features = []
117
+ for rank, idx in enumerate(sorted_idx[:top_n]):
118
+ i = int(idx)
119
+ top_features.append({
120
+ "rank": rank + 1,
121
+ "feature": FEATURE_NAMES[i],
122
+ "shap_value": round(float(shap_fraud[i]), 6),
123
+ "feature_value": round(float(features[0, i]), 6),
124
+ "direction": "↑ Fraude" if shap_fraud[i] > 0 else "↓ Légitime",
125
+ })
126
+
127
+ return {
128
+ "shap_values": shap_fraud.tolist(),
129
+ "base_value": round(float(base_value), 6),
130
+ "prediction_contribution": round(float(shap_fraud.sum()), 6),
131
+ "top_features": top_features,
132
+ }
133
+
134
+
135
+ # ─────────────────────────────────────────────────────────────
136
+ # Visualisations
137
+ # ─────────────────────────────────────────────────────────────
138
+
139
+ def plot_waterfall(
140
+ features: np.ndarray,
141
+ shap_result: dict,
142
+ transaction_id: str = "0",
143
+ prediction: int = 0,
144
+ ) -> str:
145
+ """
146
+ Génère un waterfall plot SHAP pour une transaction.
147
+ Retourne le chemin du fichier PNG sauvegardé.
148
+ """
149
+ os.makedirs(REPORTS_DIR, exist_ok=True)
150
+
151
+ shap_vals = np.array(shap_result["shap_values"])
152
+ base_val = shap_result["base_value"]
153
+ feat_vals = features.flatten()
154
+
155
+ top_n = 10
156
+ sorted_idx = np.argsort(np.abs(shap_vals))[::-1][:top_n]
157
+ top_names = [FEATURE_NAMES[i] for i in sorted_idx]
158
+ top_shap = shap_vals[sorted_idx]
159
+ top_fvals = feat_vals[sorted_idx]
160
+
161
+ colors = ["#e74c3c" if v > 0 else "#2ecc71" for v in top_shap]
162
+
163
+ fig, ax = plt.subplots(figsize=(10, 6))
164
+ y_pos = range(len(top_names))
165
+
166
+ bars = ax.barh(
167
+ y_pos, top_shap, color=colors, edgecolor="white",
168
+ height=0.7, alpha=0.9,
169
+ )
170
+
171
+ # Labels
172
+ for i, (bar, name, sv, fv) in enumerate(
173
+ zip(bars, top_names, top_shap, top_fvals)
174
+ ):
175
+ label = f"{name} = {fv:.3f} → SHAP : {sv:+.4f}"
176
+ x_pos = sv + (0.001 if sv > 0 else -0.001)
177
+ ax.text(
178
+ x_pos, i, label,
179
+ va="center",
180
+ ha="left" if sv > 0 else "right",
181
+ fontsize=8.5, color="#2c3e50",
182
+ )
183
+
184
+ ax.set_yticks([])
185
+ ax.axvline(0, color="#7f8c8d", linewidth=1)
186
+ ax.set_xlabel("Valeur SHAP (impact sur la prédiction de fraude)")
187
+
188
+ label_str = "FRAUDE" if prediction == 1 else "LEGITIME"
189
+ color_title = "#e74c3c" if prediction == 1 else "#27ae60"
190
+ ax.set_title(
191
+ f"Explication SHAP — Transaction #{transaction_id} → {label_str}",
192
+ fontsize=12, color=color_title, fontweight="bold", pad=15,
193
+ )
194
+ ax.grid(axis="x", alpha=0.3)
195
+
196
+ plt.tight_layout()
197
+ save_path = os.path.join(REPORTS_DIR, f"shap_waterfall_{transaction_id}.png")
198
+ plt.savefig(save_path, dpi=150, bbox_inches="tight")
199
+ plt.close()
200
+
201
+ return save_path
202
+
203
+
204
+ def plot_summary(X_sample: np.ndarray, explainer: shap.TreeExplainer) -> str:
205
+ """
206
+ Génère un SHAP summary plot (beeswarm) sur un échantillon du test set.
207
+ Montre l'impact global de chaque feature sur la prédiction de fraude.
208
+ """
209
+ os.makedirs(REPORTS_DIR, exist_ok=True)
210
+
211
+ print(f" Calcul SHAP sur {X_sample.shape[0]} transactions...")
212
+ shap_values_all = explainer.shap_values(X_sample)
213
+
214
+ if isinstance(shap_values_all, list):
215
+ sv_fraud = shap_values_all[1]
216
+ else:
217
+ sv_fraud = shap_values_all
218
+
219
+ # Bar plot (plus lisible que beeswarm en non-interactif)
220
+ mean_abs_shap = np.mean(np.abs(sv_fraud), axis=0)
221
+ sorted_idx = np.argsort(mean_abs_shap)
222
+ top15 = sorted_idx[-15:]
223
+
224
+ fig, ax = plt.subplots(figsize=(9, 6))
225
+ ax.barh(
226
+ [FEATURE_NAMES[i] for i in top15],
227
+ mean_abs_shap[top15],
228
+ color="steelblue", edgecolor="white", alpha=0.85,
229
+ )
230
+ ax.set_xlabel("Importance SHAP moyenne (|valeur|)")
231
+ ax.set_title("SHAP — Importance globale des features (classe Fraude)", fontsize=12)
232
+ ax.grid(axis="x", alpha=0.3)
233
+ plt.tight_layout()
234
+
235
+ save_path = os.path.join(REPORTS_DIR, "shap_summary.png")
236
+ plt.savefig(save_path, dpi=150, bbox_inches="tight")
237
+ plt.close()
238
+
239
+ print(f" [OK] SHAP summary sauvegardé : {save_path}")
240
+ return save_path
241
+
242
+
243
+ # ─────────────────────────────────────────────────────────────
244
+ # Démonstration standalone
245
+ # ─────────────────────────────────────────────────────────────
246
+
247
+ def main():
248
+ print("=" * 60)
249
+ print(" PFA — Module XAI (SHAP TreeExplainer)")
250
+ print("=" * 60)
251
+
252
+ # Chargement
253
+ print("\n[1/3] Chargement du modèle et création de l'explainer...")
254
+ explainer, model = load_explainer()
255
+ print(" [OK] TreeExplainer prêt.")
256
+
257
+ # Chargement test set pour le summary plot
258
+ X_test = joblib.load(os.path.join(DATA_DIR, "X_test.pkl"))
259
+ y_test = joblib.load(os.path.join(DATA_DIR, "y_test.pkl"))
260
+
261
+ if hasattr(X_test, 'values'):
262
+ X_test_arr = X_test.values
263
+ y_test_arr = np.array(y_test)
264
+ else:
265
+ X_test_arr = X_test
266
+ y_test_arr = np.array(y_test)
267
+
268
+ # Summary plot sur 500 transactions (rapide)
269
+ print("\n[2/3] Génération du SHAP Summary Plot (500 transactions)...")
270
+ X_sample = X_test_arr[:500]
271
+ summary_path = plot_summary(X_sample, explainer)
272
+
273
+ # Explication de 3 cas : 2 légitimes + 1 fraude
274
+ print("\n[3/3] Exemples d'explication par transaction")
275
+ fraud_idx = np.where(y_test_arr == 1)[0][:2]
276
+ legit_idx = np.where(y_test_arr == 0)[0][:1]
277
+
278
+ for idx, label in zip(
279
+ list(fraud_idx) + list(legit_idx),
280
+ ["Fraude #1", "Fraude #2", "Légitime #1"]
281
+ ):
282
+ features = X_test_arr[idx].reshape(1, -1)
283
+ prediction = model.predict(features)[0]
284
+ result = explain_transaction(features, explainer)
285
+
286
+ print(f"\n --- {label} ---")
287
+ print(f" Prédiction RF : {'FRAUDE' if prediction == 1 else 'LEGITIME'}")
288
+ print(f" Base value SHAP : {result['base_value']}")
289
+ print(f" Top {TOP_N_FEATURES} features influentes :")
290
+ for f in result["top_features"]:
291
+ print(f" [{f['rank']}] {f['feature']:<10} "
292
+ f"valeur={f['feature_value']:>8.3f} "
293
+ f"SHAP={f['shap_value']:>+.4f} {f['direction']}")
294
+
295
+ wp = plot_waterfall(features, result,
296
+ transaction_id=str(idx),
297
+ prediction=int(prediction))
298
+ print(f" Waterfall plot → {wp}")
299
+
300
+ print("\n[OK] Tous les rapports SHAP générés dans ./reports/")
301
+ print(" → Intégration API : route POST /explain disponible dans api.py")
302
+
303
+
304
+ if __name__ == "__main__":
305
+ main()
requirements.txt ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # PFA — Système de Détection d'Anomalies Financières
3
+ # Dépendances — Session 1
4
+ # ============================================================
5
+
6
+ # --- Data Manipulation ---
7
+ pandas==2.2.2
8
+ numpy==1.26.4
9
+
10
+ # --- Machine Learning ---
11
+ scikit-learn==1.4.2
12
+ imbalanced-learn==0.12.3
13
+
14
+ # --- API ---
15
+ fastapi==0.111.0
16
+ uvicorn[standard]==0.29.0
17
+ pydantic==2.7.1
18
+
19
+ # --- Explainability (XAI) — Session 2 ---
20
+ shap==0.45.1
21
+
22
+ # --- Visualization ---
23
+ matplotlib==3.9.0
24
+ seaborn==0.13.2
25
+
26
+ # --- Utilities ---
27
+ joblib==1.4.2
28
+ python-multipart==0.0.9
29
+
30
+ # --- UI (Hugging Face) ---
31
+ gradio==4.36.1
train_autoencoder.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ train_autoencoder.py — Deep Learning : Autoencoder de Détection d'Anomalies
3
+ =============================================================================
4
+ PFA : Système de Détection d'Anomalies dans les Transactions Financières
5
+
6
+ Auteurs : Othmane & Ramzi
7
+ Modèle : Autoencoder (TensorFlow/Keras)
8
+ Principe : Entraîné UNIQUEMENT sur transactions légitimes.
9
+ Une fraude = transaction que l'autoencoder ne "reconnaît" pas
10
+ → erreur de reconstruction (MSE) élevée → alerte.
11
+
12
+ Sortie : models/autoencoder.keras + models/threshold.pkl
13
+
14
+ Usage : python train_autoencoder.py
15
+ """
16
+
17
+ import os
18
+ import sys
19
+ import numpy as np
20
+ import joblib
21
+ import matplotlib
22
+ matplotlib.use("Agg")
23
+ import matplotlib.pyplot as plt
24
+ import seaborn as sns
25
+
26
+ # Suppression des logs verbeux TensorFlow
27
+ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
28
+
29
+ import tensorflow as tf
30
+ from tensorflow import keras
31
+ from tensorflow.keras import layers, callbacks, regularizers
32
+ from sklearn.metrics import (
33
+ classification_report, confusion_matrix,
34
+ f1_score, recall_score, precision_score,
35
+ precision_recall_curve, auc,
36
+ )
37
+
38
+
39
+ # ─────────────────────────────────────────────────────────────
40
+ # Configuration
41
+ # ─────────────────────────────────────────────────────────────
42
+
43
+ DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
44
+ MODELS_DIR = os.path.join(os.path.dirname(__file__), "models")
45
+
46
+ RANDOM_STATE = 42
47
+ EPOCHS = 50
48
+ BATCH_SIZE = 512
49
+ LATENT_DIM = 4 # Dimension du bottleneck
50
+ SIGMA_FACTOR = 2.0 # Seuil = mean_err + SIGMA_FACTOR * std_err
51
+ VALIDATION_SPLIT = 0.1 # 10% du train légitime pour tuning du seuil
52
+
53
+ tf.random.set_seed(RANDOM_STATE)
54
+ np.random.seed(RANDOM_STATE)
55
+
56
+
57
+ # ─────────────────────────────────────────────────────────────
58
+ # 1. Chargement des données
59
+ # ─────────────────────────────────────────────────────────────
60
+
61
+ def load_datasets():
62
+ """Charge les données depuis ./data/ (produites par data_prep.py)."""
63
+ print("[1/5] Chargement des datasets")
64
+ os.makedirs(MODELS_DIR, exist_ok=True)
65
+
66
+ for f in ["X_train_balanced.pkl", "X_test.pkl",
67
+ "y_train_balanced.pkl", "y_test.pkl"]:
68
+ if not os.path.exists(os.path.join(DATA_DIR, f)):
69
+ raise FileNotFoundError(
70
+ f"Fichier manquant : {f} → lancez d'abord data_prep.py"
71
+ )
72
+
73
+ X_train_full = joblib.load(os.path.join(DATA_DIR, "X_train_balanced.pkl"))
74
+ X_test = joblib.load(os.path.join(DATA_DIR, "X_test.pkl"))
75
+ y_train_full = joblib.load(os.path.join(DATA_DIR, "y_train_balanced.pkl"))
76
+ y_test = joblib.load(os.path.join(DATA_DIR, "y_test.pkl"))
77
+
78
+ # Conversion en arrays numpy
79
+ y_train_arr = np.array(y_train_full)
80
+ y_test_arr = np.array(y_test)
81
+
82
+ # IMPORTANT : l'autoencoder est entraîné UNIQUEMENT sur les légitimes
83
+ # On prend les légitimes du train set original (avant SMOTE synthétiques)
84
+ # Pour avoir les vrais légitimes : indices où y == 0, premières 227451 entrées
85
+ legit_mask = y_train_arr == 0
86
+ X_train_legit = X_train_full[legit_mask]
87
+
88
+ print(f" Train légitime : {X_train_legit.shape[0]:,} samples")
89
+ print(f" Test total : {X_test.shape[0]:,} samples")
90
+ print(f" Fraudes test : {int(y_test_arr.sum())} / {len(y_test_arr)}")
91
+
92
+ if hasattr(X_train_legit, 'values'):
93
+ X_train_legit = X_train_legit.values
94
+ if hasattr(X_test, 'values'):
95
+ X_test = X_test.values
96
+
97
+ return X_train_legit, X_test, y_test_arr
98
+
99
+
100
+ # ─────────────────────────────────────────────────────────────
101
+ # 2. Architecture de l'Autoencoder
102
+ # ─────────────────────────────────────────────────────────────
103
+
104
+ def build_autoencoder(input_dim: int) -> keras.Model:
105
+ """
106
+ Autoencoder symétrique avec Batch Normalization et Dropout.
107
+
108
+ Architecture :
109
+ Encoder : input_dim → 16 → 8 → LATENT_DIM
110
+ Decoder : LATENT_DIM → 8 → 16 → input_dim
111
+
112
+ Le bottleneck (LATENT_DIM=4) force le réseau à apprendre
113
+ une représentation compressée des transactions NORMALES.
114
+ Une fraude ne peut pas être bien reconstruite → MSE élevée.
115
+ """
116
+ inp = keras.Input(shape=(input_dim,), name="transaction_input")
117
+
118
+ # ── Encoder ─────────────���─────────────────────────────────
119
+ x = layers.Dense(16, activation="relu",
120
+ kernel_regularizer=regularizers.l2(1e-4),
121
+ name="enc_dense_1")(inp)
122
+ x = layers.BatchNormalization(name="enc_bn_1")(x)
123
+ x = layers.Dropout(0.1, name="enc_drop_1")(x)
124
+
125
+ x = layers.Dense(8, activation="relu",
126
+ kernel_regularizer=regularizers.l2(1e-4),
127
+ name="enc_dense_2")(x)
128
+ x = layers.BatchNormalization(name="enc_bn_2")(x)
129
+
130
+ encoded = layers.Dense(LATENT_DIM, activation="relu",
131
+ name="bottleneck")(x)
132
+
133
+ # ── Decoder ───────────────────────────────────────────────
134
+ x = layers.Dense(8, activation="relu", name="dec_dense_1")(encoded)
135
+ x = layers.BatchNormalization(name="dec_bn_1")(x)
136
+
137
+ x = layers.Dense(16, activation="relu", name="dec_dense_2")(x)
138
+ x = layers.BatchNormalization(name="dec_bn_2")(x)
139
+ x = layers.Dropout(0.1, name="dec_drop_1")(x)
140
+
141
+ decoded = layers.Dense(input_dim, activation="linear",
142
+ name="reconstruction")(x)
143
+
144
+ model = keras.Model(inputs=inp, outputs=decoded, name="FraudAutoencoder")
145
+ return model
146
+
147
+
148
+ # ─────────────────────────────────────────────────────────────
149
+ # 3. Entraînement
150
+ # ─────────────────────────────────────────────────────────────
151
+
152
+ def train_autoencoder(X_train_legit: np.ndarray) -> keras.Model:
153
+ """Entraîne l'autoencoder sur les transactions légitimes uniquement."""
154
+ print(f"\n[2/5] Construction et entraînement de l'Autoencoder")
155
+ print(f" Architecture : {X_train_legit.shape[1]} → 16 → 8 → {LATENT_DIM} → 8 → 16 → {X_train_legit.shape[1]}")
156
+ print(f" Epochs : {EPOCHS} | Batch size : {BATCH_SIZE}")
157
+
158
+ model = build_autoencoder(input_dim=X_train_legit.shape[1])
159
+ model.compile(
160
+ optimizer=keras.optimizers.Adam(learning_rate=1e-3),
161
+ loss="mse",
162
+ )
163
+ model.summary()
164
+
165
+ training_callbacks = [
166
+ callbacks.EarlyStopping(
167
+ monitor="val_loss",
168
+ patience=7,
169
+ restore_best_weights=True,
170
+ verbose=1,
171
+ ),
172
+ callbacks.ReduceLROnPlateau(
173
+ monitor="val_loss",
174
+ factor=0.5,
175
+ patience=3,
176
+ min_lr=1e-6,
177
+ verbose=1,
178
+ ),
179
+ ]
180
+
181
+ history = model.fit(
182
+ X_train_legit, X_train_legit, # X = y (autoencoder)
183
+ epochs=EPOCHS,
184
+ batch_size=BATCH_SIZE,
185
+ validation_split=VALIDATION_SPLIT,
186
+ callbacks=training_callbacks,
187
+ verbose=1,
188
+ )
189
+
190
+ _plot_training(history)
191
+ print(" [OK] Entraînement terminé.")
192
+ return model
193
+
194
+
195
+ def _plot_training(history) -> None:
196
+ """Courbes de loss train/validation."""
197
+ fig, ax = plt.subplots(figsize=(9, 4))
198
+ ax.plot(history.history["loss"], label="Train Loss (MSE)", linewidth=2)
199
+ ax.plot(history.history["val_loss"], label="Val Loss (MSE)", linewidth=2, linestyle="--")
200
+ ax.set_xlabel("Epoch")
201
+ ax.set_ylabel("MSE")
202
+ ax.set_title("Autoencoder — Courbes d'entraînement")
203
+ ax.legend()
204
+ ax.grid(alpha=0.4)
205
+ plt.tight_layout()
206
+ plt.savefig(os.path.join(MODELS_DIR, "autoencoder_training.png"), dpi=150)
207
+ plt.close()
208
+ print(f" [OK] Courbe d'entraînement sauvegardée.")
209
+
210
+
211
+ # ─────────────────────────────────────────────────────────────
212
+ # 4. Calcul du seuil de détection
213
+ # ─────────────────────────────────────────────────────────────
214
+
215
+ def compute_threshold(model: keras.Model, X_train_legit: np.ndarray) -> float:
216
+ """
217
+ Calcule le seuil de détection sur les transactions légitimes du train.
218
+
219
+ Logique :
220
+ 1. Calculer l'erreur de reconstruction (MSE par transaction) sur légitimes
221
+ 2. Seuil = mean(MSE) + SIGMA_FACTOR * std(MSE)
222
+ → Au-dessus du seuil : transaction anormale (fraude potentielle)
223
+
224
+ On utilise SIGMA_FACTOR=2 pour un bon équilibre Recall/Precision.
225
+ """
226
+ print(f"\n[3/5] Calcul du seuil de détection (sigma_factor={SIGMA_FACTOR})")
227
+
228
+ reconstructions = model.predict(X_train_legit, batch_size=1024, verbose=0)
229
+ mse_errors = np.mean(np.power(X_train_legit - reconstructions, 2), axis=1)
230
+
231
+ threshold = float(np.mean(mse_errors) + SIGMA_FACTOR * np.std(mse_errors))
232
+
233
+ print(f" MSE légitimes — mean : {np.mean(mse_errors):.6f}")
234
+ print(f" MSE légitimes — std : {np.std(mse_errors):.6f}")
235
+ print(f" Seuil retenu : {threshold:.6f}")
236
+
237
+ # Distribution des erreurs
238
+ _plot_error_distribution(mse_errors, threshold)
239
+
240
+ return threshold
241
+
242
+
243
+ def _plot_error_distribution(errors: np.ndarray, threshold: float) -> None:
244
+ """Histogramme des erreurs de reconstruction."""
245
+ fig, ax = plt.subplots(figsize=(9, 4))
246
+ ax.hist(errors, bins=100, color="steelblue", alpha=0.7, edgecolor="white",
247
+ label="MSE (légitimes train)")
248
+ ax.axvline(threshold, color="red", linewidth=2, linestyle="--",
249
+ label=f"Seuil = {threshold:.4f}")
250
+ ax.set_xlabel("Erreur de reconstruction (MSE)")
251
+ ax.set_ylabel("Nombre de transactions")
252
+ ax.set_title("Distribution des erreurs — Autoencoder")
253
+ ax.legend()
254
+ ax.grid(alpha=0.3)
255
+ plt.tight_layout()
256
+ plt.savefig(os.path.join(MODELS_DIR, "autoencoder_errors.png"), dpi=150)
257
+ plt.close()
258
+ print(f" [OK] Distribution des erreurs sauvegardée.")
259
+
260
+
261
+ # ─────────────────────────────────────────────────────────────
262
+ # 5. Évaluation
263
+ # ─────────────────────────────────────────────────────────────
264
+
265
+ def evaluate(model: keras.Model, threshold: float,
266
+ X_test: np.ndarray, y_test: np.ndarray) -> dict:
267
+ """
268
+ Évalue l'autoencoder seul + combinaison avec le Random Forest.
269
+ """
270
+ print(f"\n[4/5] Évaluation sur le Test Set")
271
+
272
+ # Prédictions autoencoder
273
+ reconstructions = model.predict(X_test, batch_size=1024, verbose=0)
274
+ mse_errors = np.mean(np.power(X_test - reconstructions, 2), axis=1)
275
+ y_pred_ae = (mse_errors > threshold).astype(int)
276
+
277
+ # Métriques autoencoder seul
278
+ f1_ae = f1_score(y_test, y_pred_ae, pos_label=1, zero_division=0)
279
+ recall_ae = recall_score(y_test, y_pred_ae, pos_label=1, zero_division=0)
280
+ prec_ae = precision_score(y_test, y_pred_ae, pos_label=1, zero_division=0)
281
+
282
+ print("\n ── Autoencoder seul ──")
283
+ print(f" F1-Score : {f1_ae:.4f}")
284
+ print(f" Recall : {recall_ae:.4f}")
285
+ print(f" Precision : {prec_ae:.4f}")
286
+
287
+ # Combinaison avec Random Forest (vote : fraude si AU MOINS UN dit fraude)
288
+ rf_model_path = os.path.join(MODELS_DIR, "baseline_model.pkl")
289
+ if os.path.exists(rf_model_path):
290
+ rf_model = joblib.load(rf_model_path)
291
+ y_pred_rf = rf_model.predict(X_test)
292
+
293
+ # Règle : fraude si RF dit fraude OU autoencoder dit fraude
294
+ y_pred_combined = np.maximum(y_pred_rf, y_pred_ae)
295
+
296
+ f1_comb = f1_score(y_test, y_pred_combined, pos_label=1, zero_division=0)
297
+ recall_comb = recall_score(y_test, y_pred_combined, pos_label=1, zero_division=0)
298
+ prec_comb = precision_score(y_test, y_pred_combined, pos_label=1, zero_division=0)
299
+
300
+ cm = confusion_matrix(y_test, y_pred_combined)
301
+ tn, fp, fn, tp = cm.ravel()
302
+
303
+ print("\n ── Combinaison RF + Autoencoder (OR) ──")
304
+ print(f" F1-Score : {f1_comb:.4f}")
305
+ print(f" Recall : {recall_comb:.4f} ← métrique prioritaire")
306
+ print(f" Precision : {prec_comb:.4f}")
307
+ print(f"\n TN (Légitimes corrects) : {tn:,}")
308
+ print(f" FP (Fausses alertes) : {fp:,}")
309
+ print(f" FN (Fraudes manquées) : {fn:,} ← Critique")
310
+ print(f" TP (Fraudes détectées) : {tp:,}")
311
+
312
+ print("\n ── Rapport complet (RF + AE) ──")
313
+ print(classification_report(y_test, y_pred_combined,
314
+ target_names=["Légitime", "Fraude"]))
315
+
316
+ _plot_confusion_matrix(cm, "RF + Autoencoder Combined")
317
+
318
+ metrics = {
319
+ "ae_f1": round(f1_ae, 4),
320
+ "ae_recall": round(recall_ae, 4),
321
+ "combined_f1": round(f1_comb, 4),
322
+ "combined_recall": round(recall_comb, 4),
323
+ "combined_precision": round(prec_comb, 4),
324
+ "tp": int(tp), "fp": int(fp), "fn": int(fn), "tn": int(tn),
325
+ }
326
+ else:
327
+ print(" [!] baseline_model.pkl introuvable — évaluation AE seule uniquement.")
328
+ metrics = {"ae_f1": round(f1_ae, 4), "ae_recall": round(recall_ae, 4)}
329
+
330
+ return metrics
331
+
332
+
333
+ def _plot_confusion_matrix(cm: np.ndarray, title: str) -> None:
334
+ fig, ax = plt.subplots(figsize=(7, 5))
335
+ sns.heatmap(cm, annot=True, fmt="d", cmap="Blues",
336
+ xticklabels=["Prédit Légitime", "Prédit Fraude"],
337
+ yticklabels=["Réel Légitime", "Réel Fraude"], ax=ax)
338
+ ax.set_title(f"Matrice de Confusion — {title}", pad=15)
339
+ plt.tight_layout()
340
+ plt.savefig(os.path.join(MODELS_DIR, "autoencoder_confusion.png"), dpi=150)
341
+ plt.close()
342
+ print(f" [OK] Matrice de confusion sauvegardée.")
343
+
344
+
345
+ # ─────────────────────────────────────────────────────────────
346
+ # 6. Sauvegarde
347
+ # ─────────────────────────────────────────────────────────────
348
+
349
+ def save_artifacts(model: keras.Model, threshold: float) -> None:
350
+ """Sauvegarde le modèle et le seuil."""
351
+ print(f"\n[5/5] Sauvegarde des artifacts")
352
+
353
+ ae_path = os.path.join(MODELS_DIR, "autoencoder.keras")
354
+ model.save(ae_path)
355
+ print(f" [OK] autoencoder.keras sauvegardé ({os.path.getsize(ae_path)/1e6:.1f} MB)")
356
+
357
+ thresh_path = os.path.join(MODELS_DIR, "threshold.pkl")
358
+ joblib.dump(threshold, thresh_path)
359
+ print(f" [OK] threshold.pkl sauvegardé ({threshold:.6f})")
360
+
361
+
362
+ # ─────────────────────────────────────────────────────────────
363
+ # Main
364
+ # ─────────────────────────────────────────────────────────────
365
+
366
+ def main():
367
+ print("=" * 60)
368
+ print(" PFA — Session 2 : Autoencoder Deep Learning")
369
+ print("=" * 60)
370
+
371
+ X_train_legit, X_test, y_test = load_datasets()
372
+ model = train_autoencoder(X_train_legit)
373
+ threshold = compute_threshold(model, X_train_legit)
374
+ metrics = evaluate(model, threshold, X_test, y_test)
375
+ save_artifacts(model, threshold)
376
+
377
+ print("\n" + "=" * 60)
378
+ print(" Résumé Session 2")
379
+ print("=" * 60)
380
+ print(f" Autoencoder seul → Recall : {metrics.get('ae_recall', 'N/A')}")
381
+ print(f" RF + Autoencoder (OR) → Recall : {metrics.get('combined_recall', 'N/A')} ← amélioration vs baseline 0.85")
382
+ print(f" Fraudes manquées (FN) : {metrics.get('fn', 'N/A')}")
383
+ print(f"\n Artifacts : models/autoencoder.keras + models/threshold.pkl")
384
+ print(f" → Prochaine étape : python explain.py (SHAP)")
385
+
386
+
387
+ if __name__ == "__main__":
388
+ main()
train_baseline.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ train_baseline.py — Entraînement du Modèle Baseline
3
+ =====================================================
4
+ PFA : Système de Détection d'Anomalies dans les Transactions Financières
5
+
6
+ Auteurs : Othmane & Ramzi
7
+ Modèle : Random Forest Classifier
8
+ Dataset : Datasets équilibrés depuis ./data/ (post-SMOTE)
9
+ Sortie : ./models/baseline_model.pkl
10
+
11
+ Usage : python train_baseline.py
12
+ """
13
+
14
+ import os
15
+ import joblib
16
+ import numpy as np
17
+ import matplotlib.pyplot as plt
18
+ import seaborn as sns
19
+
20
+ from sklearn.ensemble import RandomForestClassifier
21
+ from sklearn.metrics import (
22
+ classification_report,
23
+ confusion_matrix,
24
+ f1_score,
25
+ recall_score,
26
+ precision_score,
27
+ precision_recall_curve,
28
+ auc,
29
+ ConfusionMatrixDisplay,
30
+ )
31
+
32
+
33
+ # ─────────────────────────────────────────────────────────────
34
+ # Configuration
35
+ # ─────────────────────────────────────────────────────────────
36
+
37
+ DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
38
+ MODELS_DIR = os.path.join(os.path.dirname(__file__), "models")
39
+
40
+ RANDOM_STATE = 42
41
+
42
+ # Hyperparamètres Random Forest
43
+ RF_PARAMS = {
44
+ "n_estimators": 200, # Plus d'arbres = meilleure stabilité
45
+ "max_depth": None, # Profondeur illimitée (régulation via min_samples)
46
+ "min_samples_split": 5,
47
+ "min_samples_leaf": 2,
48
+ "max_features": "sqrt", # Standard pour classification
49
+ "n_jobs": -1, # Utilise tous les cœurs CPU
50
+ "random_state": RANDOM_STATE,
51
+ "verbose": 1,
52
+ }
53
+
54
+
55
+ # ─────────────────────────────────────────────────────────────
56
+ # 1. Chargement des données
57
+ # ─────────────────────────────────────────────────────────────
58
+
59
+ def load_datasets() -> tuple:
60
+ """Charge les datasets pré-traités depuis ./data/"""
61
+ print("[1/4] Chargement des datasets depuis ./data/")
62
+
63
+ # Création anticipée du dossier models (nécessaire pour les plots)
64
+ os.makedirs(MODELS_DIR, exist_ok=True)
65
+
66
+ required_files = [
67
+ "X_train_balanced.pkl",
68
+ "X_test.pkl",
69
+ "y_train_balanced.pkl",
70
+ "y_test.pkl",
71
+ ]
72
+
73
+ for f in required_files:
74
+ path = os.path.join(DATA_DIR, f)
75
+ if not os.path.exists(path):
76
+ raise FileNotFoundError(
77
+ f"Fichier manquant : {path}\n"
78
+ "→ Lancez d'abord : python data_prep.py"
79
+ )
80
+
81
+ X_train = joblib.load(os.path.join(DATA_DIR, "X_train_balanced.pkl"))
82
+ X_test = joblib.load(os.path.join(DATA_DIR, "X_test.pkl"))
83
+ y_train = joblib.load(os.path.join(DATA_DIR, "y_train_balanced.pkl"))
84
+ y_test = joblib.load(os.path.join(DATA_DIR, "y_test.pkl"))
85
+
86
+ import pandas as pd
87
+ y_train_series = pd.Series(y_train)
88
+ print(f" X_train : {X_train.shape} | Classes : {y_train_series.value_counts().to_dict()}")
89
+ print(f" X_test : {X_test.shape} | Fraudes test : {int(y_test.sum())}")
90
+
91
+ return X_train, X_test, y_train, y_test
92
+
93
+
94
+ # ─────────────────────────────────────────────────────────────
95
+ # 2. Entraînement
96
+ # ─────────────────────────────────────────────────────────────
97
+
98
+ def train_model(X_train: np.ndarray, y_train: np.ndarray) -> RandomForestClassifier:
99
+ """Entraîne le Random Forest sur les données équilibrées (post-SMOTE)."""
100
+ print(f"\n[2/4] Entraînement Random Forest ({RF_PARAMS['n_estimators']} arbres)")
101
+ print(f" Hyperparamètres : {RF_PARAMS}")
102
+
103
+ model = RandomForestClassifier(**RF_PARAMS)
104
+ model.fit(X_train, y_train)
105
+
106
+ print(" ✓ Entraînement terminé.")
107
+ return model
108
+
109
+
110
+ # ─────────────────────────────────────────────────────────────
111
+ # 3. Évaluation
112
+ # ─────────────────────────────────────────────────────────────
113
+
114
+ def evaluate_model(
115
+ model: RandomForestClassifier,
116
+ X_test: np.ndarray,
117
+ y_test: np.ndarray,
118
+ ) -> dict:
119
+ """
120
+ Évalue le modèle avec des métriques adaptées aux datasets déséquilibrés.
121
+ Note : L'Accuracy est intentionnellement exclue (trompeuse à ~0.17% fraudes).
122
+ """
123
+ print("\n[3/4] Évaluation sur le Test Set (distribution naturelle)")
124
+
125
+ y_pred = model.predict(X_test)
126
+ y_proba = model.predict_proba(X_test)[:, 1] # Proba de fraude
127
+
128
+ # ── Métriques principales ──────────────────────────────
129
+ f1 = f1_score(y_test, y_pred, pos_label=1)
130
+ recall = recall_score(y_test, y_pred, pos_label=1)
131
+ precision = precision_score(y_test, y_pred, pos_label=1)
132
+
133
+ # Precision-Recall AUC (plus pertinent que ROC-AUC sur datasets déséquilibrés)
134
+ prec_curve, rec_curve, _ = precision_recall_curve(y_test, y_proba)
135
+ pr_auc = auc(rec_curve, prec_curve)
136
+
137
+ metrics = {
138
+ "F1-Score (Fraude)": round(f1, 4),
139
+ "Recall (Fraude)": round(recall, 4),
140
+ "Precision (Fraude)": round(precision, 4),
141
+ "PR-AUC": round(pr_auc, 4),
142
+ }
143
+
144
+ # ── Affichage ─────────────────────────────────────────
145
+ print("\n ┌─ Métriques de Performance ──────────────────────────┐")
146
+ for name, val in metrics.items():
147
+ bar = "█" * int(val * 30)
148
+ print(f" │ {name:<25} : {val:.4f} {bar}")
149
+ print(" └──────────────────────────────────────────────────────┘")
150
+
151
+ print("\n ── Rapport complet ──")
152
+ print(classification_report(y_test, y_pred, target_names=["Légitime", "Fraude"]))
153
+
154
+ # ── Matrice de confusion ─────────────────────────────
155
+ cm = confusion_matrix(y_test, y_pred)
156
+ _plot_confusion_matrix(cm)
157
+
158
+ # ── Feature Importances (Top 10) ─────────────────────
159
+ _plot_feature_importances(model)
160
+
161
+ return metrics
162
+
163
+
164
+ def _plot_confusion_matrix(cm: np.ndarray) -> None:
165
+ """Affiche et sauvegarde la matrice de confusion."""
166
+ fig, ax = plt.subplots(figsize=(7, 6))
167
+
168
+ sns.heatmap(
169
+ cm,
170
+ annot=True,
171
+ fmt="d",
172
+ cmap="Blues",
173
+ xticklabels=["Prédit : Légitime", "Prédit : Fraude"],
174
+ yticklabels=["Réel : Légitime", "Réel : Fraude"],
175
+ ax=ax,
176
+ )
177
+ ax.set_title("Matrice de Confusion — Random Forest Baseline", fontsize=13, pad=15)
178
+ ax.set_ylabel("Classe Réelle", fontsize=11)
179
+ ax.set_xlabel("Classe Prédite", fontsize=11)
180
+
181
+ # Annotations FP / FN / TP / TN
182
+ tn, fp, fn, tp = cm.ravel()
183
+ print(f"\n Matrice de Confusion :")
184
+ print(f" TN (Légitimes corrects) : {tn:,}")
185
+ print(f" FP (Fausses alertes) : {fp:,}")
186
+ print(f" FN (Fraudes manquées) : {fn:,} ← Critique")
187
+ print(f" TP (Fraudes détectées) : {tp:,}")
188
+
189
+ save_path = os.path.join(MODELS_DIR, "confusion_matrix.png")
190
+ plt.tight_layout()
191
+ plt.savefig(save_path, dpi=150, bbox_inches="tight")
192
+ plt.show()
193
+ print(f"\n ✓ Matrice sauvegardée : {save_path}")
194
+
195
+
196
+ def _plot_feature_importances(model: RandomForestClassifier) -> None:
197
+ """Affiche les 15 features les plus importantes."""
198
+ import pandas as pd
199
+
200
+ importances = pd.Series(
201
+ model.feature_importances_,
202
+ index=[f"V{i}" for i in range(1, 29)] + ["Amount", "Time"]
203
+ ).sort_values(ascending=False)
204
+
205
+ top15 = importances.head(15)
206
+
207
+ fig, ax = plt.subplots(figsize=(9, 5))
208
+ top15.plot(kind="barh", ax=ax, color="steelblue", edgecolor="white")
209
+ ax.invert_yaxis()
210
+ ax.set_title("Top 15 Feature Importances — Random Forest Baseline", fontsize=12)
211
+ ax.set_xlabel("Importance (Gini)")
212
+ ax.grid(axis="x", alpha=0.4)
213
+
214
+ save_path = os.path.join(MODELS_DIR, "feature_importances.png")
215
+ plt.tight_layout()
216
+ plt.savefig(save_path, dpi=150, bbox_inches="tight")
217
+ plt.show()
218
+ print(f" ✓ Feature importances sauvegardées : {save_path}")
219
+
220
+
221
+ # ─────────────────────────────────────────────────────────────
222
+ # 4. Sauvegarde du modèle
223
+ # ─────────────────────────────────────────────────────────────
224
+
225
+ def save_model(model: RandomForestClassifier) -> str:
226
+ """Sauvegarde le modèle entraîné dans ./models/"""
227
+ os.makedirs(MODELS_DIR, exist_ok=True)
228
+
229
+ model_path = os.path.join(MODELS_DIR, "baseline_model.pkl")
230
+ joblib.dump(model, model_path)
231
+
232
+ size_mb = os.path.getsize(model_path) / 1_000_000
233
+ print(f"\n[4/4] Modèle sauvegardé : {model_path} ({size_mb:.1f} MB)")
234
+
235
+ return model_path
236
+
237
+
238
+ # ─────────────────────────────────────────────────────────────
239
+ # Main
240
+ # ─────────────────────────────────────────────────────────────
241
+
242
+ def main():
243
+ print("=" * 60)
244
+ print(" PFA — Entraînement du Modèle Baseline (Random Forest)")
245
+ print("=" * 60)
246
+
247
+ # 1. Chargement
248
+ X_train, X_test, y_train, y_test = load_datasets()
249
+
250
+ # 2. Entraînement
251
+ model = train_model(X_train, y_train)
252
+
253
+ # 3. Évaluation
254
+ metrics = evaluate_model(model, X_test, y_test)
255
+
256
+ # 4. Sauvegarde
257
+ model_path = save_model(model)
258
+
259
+ print("\n" + "=" * 60)
260
+ print(" Résumé Final")
261
+ print("=" * 60)
262
+ print(f" Modèle : Random Forest ({RF_PARAMS['n_estimators']} arbres)")
263
+ print(f" F1-Score : {metrics['F1-Score (Fraude)']}")
264
+ print(f" Recall : {metrics['Recall (Fraude)']} ← métrique prioritaire")
265
+ print(f" PR-AUC : {metrics['PR-AUC']}")
266
+ print(f" Modèle sauvegardé → {model_path}")
267
+ print("\n → Prochaine étape : python api.py (Session 1)")
268
+ print(" → Session 2 : Deep Learning + XAI avec SHAP")
269
+
270
+
271
+ if __name__ == "__main__":
272
+ main()