File size: 7,423 Bytes
a408d59 4681be1 a408d59 4681be1 a408d59 4681be1 a408d59 | 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 | {
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Évaluation des Modèles — Dakar Power Prediction\n",
"\n",
"Évaluation complète du pipeline LightGBM + LSTM sur `synthetic_data_v2.csv`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import sys\n",
"from pathlib import Path\n",
"\n",
"import pandas as pd\n",
"import numpy as np\n",
"import pickle\n",
"import matplotlib.pyplot as plt\n",
"import seaborn as sns\n",
"from sklearn.metrics import (\n",
" classification_report, confusion_matrix, roc_curve, auc\n",
")\n",
"from sklearn.model_selection import train_test_split\n",
"\n",
"# Assure que le repo root est dans le path\n",
"sys.path.insert(0, str(Path('..').resolve()))\n",
"from src.config import MODEL_CONFIG\n",
"\n",
"FEATURES = MODEL_CONFIG['features']\n",
"TARGET = 'coupure'\n",
"RANDOM_STATE = 42\n",
"\n",
"print('Features:', FEATURES)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df = pd.read_csv('../data/synthetic/synthetic_data_v2.csv')\n",
"print(f'Shape : {df.shape}')\n",
"df.head()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Feature engineering — encodage identique à utils_simple.py\n",
"if 'date_heure' in df.columns:\n",
" df['date_heure'] = pd.to_datetime(df['date_heure'])\n",
" df['heure'] = df['date_heure'].dt.hour\n",
" df['jour_semaine']= df['date_heure'].dt.dayofweek\n",
" df['mois'] = df['date_heure'].dt.month\n",
" df['saison'] = df['mois'].isin([6, 7, 8]).astype(int)\n",
" df['is_peak_hour']= df['heure'].between(18, 22).astype(int)\n",
"\n",
"X = df[FEATURES]\n",
"y = df[TARGET]\n",
"print(f'X shape: {X.shape}, target balance: {y.mean():.3f}')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"X_train, X_test, y_train, y_test = train_test_split(\n",
" X, y, test_size=0.2, random_state=RANDOM_STATE, stratify=y\n",
")\n",
"print(f'Train: {len(X_train):,} | Test: {len(X_test):,}')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"with open('../models/lgbm_model.pkl', 'rb') as f:\n",
" lgb_model = pickle.load(f)\n",
"with open('../models/scaler.pkl', 'rb') as f:\n",
" scaler = pickle.load(f)\n",
"\n",
"X_test_scaled = scaler.transform(X_test)\n",
"print('Modèles chargés.')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"y_prob = lgb_model.predict(X_test_scaled)\n",
"y_pred = (y_prob >= 0.5).astype(int)\n",
"\n",
"print('=== Classification Report — LightGBM ===')\n",
"print(classification_report(y_test, y_pred, target_names=['Pas de coupure', 'Coupure']))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"cm = confusion_matrix(y_test, y_pred)\n",
"fig, ax = plt.subplots(figsize=(6, 5))\n",
"sns.heatmap(\n",
" cm, annot=True, fmt='d', cmap='Blues', ax=ax,\n",
" xticklabels=['Prédit 0', 'Prédit 1'],\n",
" yticklabels=['Réel 0', 'Réel 1']\n",
")\n",
"ax.set_title('Matrice de Confusion — LightGBM')\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fpr, tpr, _ = roc_curve(y_test, y_prob)\n",
"roc_auc = auc(fpr, tpr)\n",
"\n",
"fig, ax = plt.subplots(figsize=(7, 5))\n",
"ax.plot(fpr, tpr, color='steelblue', lw=2, label=f'LightGBM (AUC = {roc_auc:.3f})')\n",
"ax.plot([0, 1], [0, 1], 'k--', lw=1)\n",
"ax.set_xlabel('Taux de Faux Positifs')\n",
"ax.set_ylabel('Taux de Vrais Positifs')\n",
"ax.set_title('Courbe ROC')\n",
"ax.legend(loc='lower right')\n",
"plt.tight_layout()\n",
"plt.show()\n",
"print(f'AUC : {roc_auc:.4f}')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"importance = lgb_model.feature_importance(importance_type='gain')\n",
"feat_imp = pd.Series(importance, index=FEATURES).sort_values()\n",
"\n",
"fig, ax = plt.subplots(figsize=(8, 5))\n",
"feat_imp.plot.barh(ax=ax, color='steelblue')\n",
"ax.set_title('Feature Importance — LightGBM (gain)')\n",
"ax.set_xlabel('Gain')\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Conclusion (métriques mesurées, pas estimées)\n",
"\n",
"> ⚠️ Données synthétiques : démonstration technique, pas des mesures du réseau SENELEC.\n",
"\n",
"Chiffres obtenus lors du diagnostic du 17/11/2026 en rechargeant les modèles déployés (`models/`) sur le jeu de test (14 000 lignes, split stratifié 80/20, `random_state=42`, encodage des features **identique au CSV**). Taux de coupure dans le test : **14,05 %**.\n",
"\n",
"| Modèle | AUC-ROC | PR-AUC | Seuil | Précision | Rappel | F1 | Matrice [[VN, FP], [FN, VP]] |\n",
"|---|---|---|---|---|---|---|---|\n",
"| LightGBM | 0,873 | 0,503 | 0,50 | 0,604 | 0,303 | 0,404 | [[11643, 390], [1371, 596]] |\n",
"| LightGBM | | | 0,25 | 0,454 | 0,597 | 0,516 | [[10618, 1415], [792, 1175]] |\n",
"| LSTM | 0,874 | 0,513 | 0,50 | 0,627 | 0,239 | 0,346 | [[11753, 280], [1497, 470]] |\n",
"| LSTM | | | 0,25 | 0,456 | 0,601 | 0,519 | [[10623, 1410], [785, 1182]] |\n",
"| Ensemble (moyenne) | 0,874 | 0,510 | 0,25 | 0,456 | 0,601 | 0,519 | [[10624, 1409], [785, 1182]] |\n",
"| Référence « jamais de coupure » | 0,500 | — | — | — | 0 | 0 | [[12033, 0], [1967, 0]] |\n",
"| Référence régression logistique | 0,842 | | | | | | |\n",
"\n",
"**Lecture honnête :**\n",
"- L'exactitude (accuracy) de LightGBM au seuil 0,5 est de 87,4 %, contre **85,95 %** pour un modèle qui répond toujours « pas de coupure » : le gain réel est faible.\n",
"- Au seuil 0,25, environ une alerte sur deux est une fausse alerte.\n",
"- Le LSTM n'apporte rien de mesurable par rapport à LightGBM.\n",
"- Variables dominantes (gain LightGBM) : `is_peak_hour` (51 %), `humidite_percent` (24 %), `conso_megawatt` (12 %), `temp_celsius` (8 %). Le modèle apprend surtout l'heure de pointe ; à l'intérieur des heures de pointe, l'AUC tombe à 0,68.\n",
"- **Biais optimiste :** le jeu de test a servi à l'arrêt anticipé de LightGBM et du LSTM, et au choix du seuil 0,25. Ces chiffres surestiment donc légèrement la performance attendue sur des données nouvelles.\n",
"- Toutes ces mesures portent sur des données synthétiques : elles ne disent rien de la performance sur le réseau réel.\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.12.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
|