{ "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 }