cheikhaidev-ui Claude Sonnet 4.6 commited on
Commit
3e4b260
·
1 Parent(s): fd9b3d1

fix: correct critical feature encoding bugs + retrain models

Browse files

BREAKING FIX: silent wrong predictions in production resolved

- fix(inference): align saison encoding with training CSV (binary 0/1, pluies=Jun-Aug)
- fix(inference): align is_peak_hour with training CSV (18-22h, evening only)
- fix(inference): remove invalid predict_proba fallback on lgb.Booster
- fix(config): harmonize quartier names with accents (Sicap-Liberté, Mermoz-Sacré-Cœur)
- fix(config): remove module-level print() causing UnicodeEncodeError on Windows
- chore(deps): upgrade tensorflow-cpu 2.15.0 → 2.17.1 (Python 3.12 support)
- chore(models): retrain LightGBM (87.42%) and LSTM (87.31%) with corrected encodings

Audit performed by Claude Code — 22 issues found, 4 critical bugs fixed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

CLAUDE.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## Project Overview
6
+
7
+ Dakar Power Prediction is a Streamlit web app that predicts electricity outage risk (0–100%) for 8 Dakar neighborhoods using a hybrid ML ensemble (LightGBM + LSTM). Models are pre-trained on 70,001 synthetic records and stored as binary artifacts in `models/`.
8
+
9
+ ## Commands
10
+
11
+ ```bash
12
+ # Install dependencies
13
+ pip install -r requirements.txt
14
+
15
+ # Run the Streamlit app (default port 8501)
16
+ streamlit run streamlit_app/app.py
17
+
18
+ # Retrain models from the local CSV (takes 10–15 min due to LSTM)
19
+ python scripts/2_train_models.py
20
+
21
+ # Load synthetic data to Supabase
22
+ python scripts/3_load_to_supabase.py
23
+
24
+ # Generate fresh synthetic data (outputs to data/raw/raw_data.csv)
25
+ python src/data_generator.py
26
+ ```
27
+
28
+ ### Docker
29
+
30
+ ```bash
31
+ docker build -t dakar-power .
32
+ docker run -p 8501:8501 dakar-power
33
+ ```
34
+
35
+ The Dockerfile installs `libgomp1` (required by LightGBM on Linux) before installing Python deps.
36
+
37
+ ## Architecture
38
+
39
+ ```
40
+ streamlit_app/app.py # Entry point; sidebar controls, 4 tabs (Prédiction, Carte, Stats, Historique)
41
+ streamlit_app/utils_simple.py # All ML inference, chart creation, and model loading (@st.cache_resource)
42
+ src/config.py # Central config: quartier names, GPS coords, risk adjustments, model feature list
43
+ src/database.py # Supabase REST API client (bulk insert, prediction save, stats queries)
44
+ src/data_generator.py # Synthetic data generation with per-quartier risk profiles
45
+ scripts/2_train_models.py # Train LightGBM + LSTM, saves to models/
46
+ scripts/3_load_to_supabase.py # Upload CSV to Supabase enregistrements table
47
+ models/ # lgbm_model.pkl, lstm_model.keras, scaler.pkl (tracked via Git LFS)
48
+ data/synthetic/synthetic_data_v2.csv # Training dataset (Git LFS)
49
+ ```
50
+
51
+ ### Prediction Pipeline
52
+
53
+ 1. User sets weather/consumption inputs in sidebar → clicks "Lancer la Prédiction"
54
+ 2. `create_time_features()` extracts hour, weekday, month, season, is_peak_hour from `datetime.now()`
55
+ 3. `make_prediction_single()` builds a 9-feature vector, scales it with the stored `scaler.pkl`, runs LightGBM and LSTM independently, averages their outputs, then multiplies by a per-quartier `QUARTIER_ADJUSTMENT` factor (defined in `src/config.py`)
56
+ 4. Risk is clamped to 0–100%; classified as FAIBLE (<40%), MOYEN (40–69%), ÉLEVÉ (≥70%)
57
+
58
+ ### Model Feature Order (must match scaler fit order)
59
+
60
+ ```python
61
+ ['temp_celsius', 'humidite_percent', 'vitesse_vent', 'conso_megawatt',
62
+ 'heure', 'jour_semaine', 'mois', 'saison', 'is_peak_hour']
63
+ ```
64
+
65
+ This order is defined in `src/config.py:MODEL_CONFIG['features']` and must stay consistent across `scripts/2_train_models.py` and `streamlit_app/utils_simple.py`.
66
+
67
+ ### LSTM Input Shape
68
+
69
+ The LSTM expects shape `(1, 1, 9)` — single sample, single timestep, 9 features. This is a deliberate simplification; the model captures feature interactions rather than true time series.
70
+
71
+ ### Supabase
72
+
73
+ Credentials are hardcoded in `src/config.py:SUPABASE_CONFIG`. The anon key is public by design (PostgREST RLS). Two tables: `enregistrements` (historical data) and `predictions` (logged inference results). `src/database.py` uses raw `requests` against the REST API, not the Supabase Python client.
74
+
75
+ ## Key Constraints
76
+
77
+ - Models must be loaded from the project root (paths like `'models/lgbm_model.pkl'`). Always run the app from the repo root.
78
+ - LSTM is loaded with `compile=False` then recompiled manually to avoid Keras serialization compatibility issues.
79
+ - The app degrades gracefully: if LSTM fails to load, LightGBM prediction is used for both model slots.
80
+ - `saison` encoding differs between `data_generator.py` (0/1/2 for Dakar's three seasons) and `utils_simple.py` (1/2/3/4 for four calendar seasons). Training data uses the 3-season encoding.
models/lgbm_model.pkl CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:d63cec2383f642bddf62e96eedb3a6bfa37b7fbce73f321ff6dbe5fbf1dd5b14
3
- size 265975
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c765a73ae1bed4107869f22513c92f7032fd8d983f696768fac9e29c914a7c9e
3
+ size 312364
models/lstm_model.keras CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:39e5c6bb7e8678d4a218f9c1f9629c42c62a1b756b1fa15664f1013e8461cbf5
3
- size 424958
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f09054a7ee7fa3447990f7cf95fa36154a2ee75ca3764945febe8cd9580148b
3
+ size 424673
models/scaler.pkl CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:0d60ee6e46fc958f49fa4bcfeae4b54e6b2357607de765f588cedeb309c426c8
3
- size 872
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:115e62559da03e118795c6bd4d2fa134e70a1d7228714177b1dfbe123891db83
3
+ size 665
requirements.txt CHANGED
@@ -4,4 +4,4 @@ numpy==1.26.3
4
  plotly==5.18.0
5
  lightgbm==4.1.0
6
  scikit-learn==1.3.2
7
- tensorflow-cpu==2.15.0
 
4
  plotly==5.18.0
5
  lightgbm==4.1.0
6
  scikit-learn==1.3.2
7
+ tensorflow-cpu==2.17.1
src/config.py CHANGED
@@ -26,12 +26,12 @@ SUPABASE_CONFIG = {
26
  QUARTIERS_DAKAR = [
27
  'Guediawaye',
28
  'Parcelles Assainies',
29
- 'Pikine',
30
- 'Sicap-Liberte',
31
  'Yoff',
32
- 'Mermoz-Sacre-Coeur',
33
  'Dakar-Plateau',
34
- 'Fann'
35
  ]
36
 
37
  # ============================================================================
@@ -42,9 +42,9 @@ COORDONNEES_QUARTIERS = {
42
  'Guediawaye': {'lat': 14.7692, 'lon': -17.4008},
43
  'Parcelles Assainies': {'lat': 14.7586, 'lon': -17.4147},
44
  'Pikine': {'lat': 14.7564, 'lon': -17.3924},
45
- 'Sicap-Liberte': {'lat': 14.7167, 'lon': -17.4677},
46
  'Yoff': {'lat': 14.7539, 'lon': -17.4894},
47
- 'Mermoz-Sacre-Coeur': {'lat': 14.7206, 'lon': -17.4706},
48
  'Dakar-Plateau': {'lat': 14.6928, 'lon': -17.4467},
49
  'Fann': {'lat': 14.6937, 'lon': -17.4531}
50
  }
@@ -56,12 +56,12 @@ COORDONNEES_QUARTIERS = {
56
  QUARTIER_ADJUSTMENT = {
57
  'Guediawaye': 1.15,
58
  'Parcelles Assainies': 1.10,
59
- 'Pikine': 1.20,
60
- 'Sicap-Liberte': 1.05,
61
  'Yoff': 1.00,
62
- 'Mermoz-Sacre-Coeur': 0.90,
63
  'Dakar-Plateau': 0.85,
64
- 'Fann': 0.95
65
  }
66
 
67
  # ============================================================================
@@ -116,4 +116,3 @@ MODEL_CONFIG = {
116
  'random_state': 42
117
  }
118
 
119
- print("✅ Config chargée : 8 quartiers")
 
26
  QUARTIERS_DAKAR = [
27
  'Guediawaye',
28
  'Parcelles Assainies',
29
+ 'Pikine', # ATTENTION : absent des données d'entraînement (data_generator.py)
30
+ 'Sicap-Liberté',
31
  'Yoff',
32
+ 'Mermoz-Sacré-Cœur',
33
  'Dakar-Plateau',
34
+ 'Fann' # ATTENTION : absent des données d'entraînement (data_generator.py)
35
  ]
36
 
37
  # ============================================================================
 
42
  'Guediawaye': {'lat': 14.7692, 'lon': -17.4008},
43
  'Parcelles Assainies': {'lat': 14.7586, 'lon': -17.4147},
44
  'Pikine': {'lat': 14.7564, 'lon': -17.3924},
45
+ 'Sicap-Liberté': {'lat': 14.7167, 'lon': -17.4677},
46
  'Yoff': {'lat': 14.7539, 'lon': -17.4894},
47
+ 'Mermoz-Sacré-Cœur': {'lat': 14.7206, 'lon': -17.4706},
48
  'Dakar-Plateau': {'lat': 14.6928, 'lon': -17.4467},
49
  'Fann': {'lat': 14.6937, 'lon': -17.4531}
50
  }
 
56
  QUARTIER_ADJUSTMENT = {
57
  'Guediawaye': 1.15,
58
  'Parcelles Assainies': 1.10,
59
+ 'Pikine': 1.20, # ATTENTION : absent des données d'entraînement
60
+ 'Sicap-Liberté': 1.05,
61
  'Yoff': 1.00,
62
+ 'Mermoz-Sacré-Cœur': 0.90,
63
  'Dakar-Plateau': 0.85,
64
+ 'Fann': 0.95 # ATTENTION : absent des données d'entraînement
65
  }
66
 
67
  # ============================================================================
 
116
  'random_state': 42
117
  }
118
 
 
streamlit_app/utils_simple.py CHANGED
@@ -1,17 +1,23 @@
1
  """
2
  Fonctions utilitaires - THÈME PAR DÉFAUT STREAMLIT/PLOTLY
3
  """
4
- import streamlit as st
5
  import warnings
6
- warnings.filterwarnings('ignore')
 
 
 
7
  import pandas as pd
8
  import numpy as np
9
- from datetime import datetime
10
- import pickle
11
  import plotly.graph_objects as go
12
  from tensorflow import keras
 
 
 
13
  from src.config import QUARTIERS_DAKAR, COORDONNEES_QUARTIERS, QUARTIER_ADJUSTMENT
14
 
 
 
15
  @st.cache_resource
16
  def load_models_cached():
17
  models = {'lgb': None, 'lstm': None, 'scaler': None}
@@ -37,14 +43,9 @@ def load_models_cached():
37
 
38
  def create_time_features(date_time):
39
  month = date_time.month
40
- if month in [12, 1, 2]:
41
- saison = 1
42
- elif month in [3, 4, 5]:
43
- saison = 2
44
- elif month in [6, 7, 8]:
45
- saison = 3
46
- else:
47
- saison = 4
48
  is_peak_hour = 1 if 18 <= date_time.hour <= 22 else 0
49
  return {'hour': date_time.hour, 'day_of_week': date_time.weekday(), 'month': date_time.month, 'saison': saison, 'is_peak_hour': is_peak_hour}
50
 
@@ -60,11 +61,9 @@ def make_prediction_single(models, quartier, temp, humidite, vent, conso, time_f
60
  features_scaled = scaler.transform(features_array)
61
  try:
62
  pred_lgb = float(lgb_model.predict(features_scaled)[0]) * 100
63
- except:
64
- try:
65
- pred_lgb = lgb_model.predict_proba(features_scaled)[0][1] * 100
66
- except:
67
- pred_lgb = 50.0
68
  if lstm_model is not None:
69
  try:
70
  features_lstm = features_scaled.reshape(1, 1, -1)
 
1
  """
2
  Fonctions utilitaires - THÈME PAR DÉFAUT STREAMLIT/PLOTLY
3
  """
4
+ import logging
5
  import warnings
6
+ import pickle
7
+ from datetime import datetime
8
+
9
+ import streamlit as st
10
  import pandas as pd
11
  import numpy as np
 
 
12
  import plotly.graph_objects as go
13
  from tensorflow import keras
14
+
15
+ warnings.filterwarnings('ignore')
16
+
17
  from src.config import QUARTIERS_DAKAR, COORDONNEES_QUARTIERS, QUARTIER_ADJUSTMENT
18
 
19
+ logger = logging.getLogger(__name__)
20
+
21
  @st.cache_resource
22
  def load_models_cached():
23
  models = {'lgb': None, 'lstm': None, 'scaler': None}
 
43
 
44
  def create_time_features(date_time):
45
  month = date_time.month
46
+ # Encodage binaire calé sur synthetic_data_v2.csv : saison pluies (Jun-Août) = 1, reste = 0
47
+ saison = 1 if month in [6, 7, 8] else 0
48
+ # is_peak_hour calé sur le CSV : heures 18-22 = 1 (soir uniquement)
 
 
 
 
 
49
  is_peak_hour = 1 if 18 <= date_time.hour <= 22 else 0
50
  return {'hour': date_time.hour, 'day_of_week': date_time.weekday(), 'month': date_time.month, 'saison': saison, 'is_peak_hour': is_peak_hour}
51
 
 
61
  features_scaled = scaler.transform(features_array)
62
  try:
63
  pred_lgb = float(lgb_model.predict(features_scaled)[0]) * 100
64
+ except Exception as e:
65
+ logger.error(f"LightGBM prediction failed: {e}")
66
+ pred_lgb = 50.0
 
 
67
  if lstm_model is not None:
68
  try:
69
  features_lstm = features_scaled.reshape(1, 1, -1)