fix(risque): afficher la vraie probabilité et redéfinir les seuils
Browse files- Suppression du « ×2 » (PREDICTION_THRESHOLD) : le risque affiché est
la moyenne des probabilités brutes LightGBM/LSTM, déjà bien calibrée
(14,1 % prédit en moyenne pour 14,05 % observé)
- Coefficient de quartier appliqué AVANT le plafonnement à 100 %
- Suppression du plancher artificiel de 5 % (RISK_FLOOR)
- Seuils 40/70 % → 15/35 %, fixés sur la distribution du test :
FAIBLE 61,4 % des cas (2,5 % de coupures réelles), MOYEN 24,9 %
(22,0 %), ÉLEVÉ 13,7 % (51,5 %)
- Jauge, lignes de seuil et messages pilotés par RISK_THRESHOLDS ;
affichage à 0,1 % près ; légende expliquant le score
- Un échec de LightGBM affiche une erreur au lieu d'un 50 % fictif
- Prédiction unique et carte partagent le même code
(_predict_probas_pct, apply_quartier_adjustment)
- Tests : seuils, absence de rescaling et de plancher, ordre
coefficient/plafond, cohérence carte/prédiction ; la CI lance tests/
- Docs : README, PERFORMANCE, CLAUDE.md, CHANGELOG
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- .github/workflows/ci.yml +1 -1
- CHANGELOG.md +1 -0
- CLAUDE.md +2 -2
- PERFORMANCE.md +12 -6
- README.md +2 -2
- src/config.py +7 -2
- streamlit_app/app.py +10 -5
- streamlit_app/utils_simple.py +46 -64
- tests/test_config.py +11 -3
- tests/test_prediction.py +90 -0
|
@@ -26,4 +26,4 @@ jobs:
|
|
| 26 |
pip install pytest pandas numpy scikit-learn lightgbm streamlit plotly
|
| 27 |
|
| 28 |
- name: Run tests
|
| 29 |
-
run: python -m pytest tests/
|
|
|
|
| 26 |
pip install pytest pandas numpy scikit-learn lightgbm streamlit plotly
|
| 27 |
|
| 28 |
- name: Run tests
|
| 29 |
+
run: python -m pytest tests/ -v
|
|
@@ -11,6 +11,7 @@ Tous les changements notables de ce projet seront documentés dans ce fichier.
|
|
| 11 |
- PERFORMANCE.md et conclusion du notebook 02 : chiffres inventés (AUC ~0,93, F1 ~0,55, classe ~8 %) et configuration erronée remplacés par les métriques mesurées, avec la référence « jamais de coupure » et le biais lié à l'usage du test pour l'arrêt anticipé
|
| 12 |
- Port unifié sur 7860 (Dockerfile, .streamlit/config.toml, CLAUDE.md) ; `.env.example` débarrassé des variables Supabase ; accent cassé du Dockerfile
|
| 13 |
- **Inférence réalignée sur le CSV d'entraînement** : `saison` binaire (juin-août) et `is_peak_hour` 18h-22h. La « correction » 1.1.0 ci-dessous avait aligné l'app sur `data_generator.py` sans réentraîner, ce qui faussait les prédictions (ex. 22h ≈ 0 % au lieu d'environ 43 %). Tests réécrits pour comparer l'encodage aux valeurs du CSV
|
|
|
|
| 14 |
|
| 15 |
## [1.1.0] - 2026-06-17
|
| 16 |
|
|
|
|
| 11 |
- PERFORMANCE.md et conclusion du notebook 02 : chiffres inventés (AUC ~0,93, F1 ~0,55, classe ~8 %) et configuration erronée remplacés par les métriques mesurées, avec la référence « jamais de coupure » et le biais lié à l'usage du test pour l'arrêt anticipé
|
| 12 |
- Port unifié sur 7860 (Dockerfile, .streamlit/config.toml, CLAUDE.md) ; `.env.example` débarrassé des variables Supabase ; accent cassé du Dockerfile
|
| 13 |
- **Inférence réalignée sur le CSV d'entraînement** : `saison` binaire (juin-août) et `is_peak_hour` 18h-22h. La « correction » 1.1.0 ci-dessous avait aligné l'app sur `data_generator.py` sans réentraîner, ce qui faussait les prédictions (ex. 22h ≈ 0 % au lieu d'environ 43 %). Tests réécrits pour comparer l'encodage aux valeurs du CSV
|
| 14 |
+
- **Risque affiché = vraie probabilité** : suppression du « ×2 » et du plancher de 5 % ; coefficient de quartier appliqué avant le plafonnement ; seuils redéfinis à 15 % / 35 % sur la distribution du jeu de test (au lieu de 40 % / 70 %) ; un échec de LightGBM n'affiche plus un 50 % fictif
|
| 15 |
|
| 16 |
## [1.1.0] - 2026-06-17
|
| 17 |
|
|
@@ -47,8 +47,8 @@ data/synthetic/synthetic_data_v2.csv # Training dataset (Git LFS)
|
|
| 47 |
|
| 48 |
1. User sets weather/consumption inputs in sidebar → clicks "Lancer la Prédiction"
|
| 49 |
2. `create_time_features()` extracts hour, weekday, month, season, is_peak_hour from `datetime.now()`
|
| 50 |
-
3. `make_prediction_single()` builds a 9-feature vector, scales it with the stored `scaler.pkl`, runs LightGBM and LSTM independently, averages their
|
| 51 |
-
4. Risk is clamped to 0–100%; classified as FAIBLE (<
|
| 52 |
|
| 53 |
### Model Feature Order (must match scaler fit order)
|
| 54 |
|
|
|
|
| 47 |
|
| 48 |
1. User sets weather/consumption inputs in sidebar → clicks "Lancer la Prédiction"
|
| 49 |
2. `create_time_features()` extracts hour, weekday, month, season, is_peak_hour from `datetime.now()`
|
| 50 |
+
3. `make_prediction_single()` builds a 9-feature vector, scales it with the stored `scaler.pkl`, runs LightGBM and LSTM independently, averages their raw probabilities (no rescaling), then multiplies by a per-quartier `QUARTIER_ADJUSTMENT` factor (defined in `src/config.py`) BEFORE clamping
|
| 51 |
+
4. Risk is clamped to 0–100% (no floor); classified as FAIBLE (<15%), MOYEN (15–35%), ÉLEVÉ (≥35%) — `RISK_THRESHOLDS` in `src/config.py`, chosen on the test-set distribution (real outage rate 2.5% / 22% / 51.5% per level)
|
| 52 |
|
| 53 |
### Model Feature Order (must match scaler fit order)
|
| 54 |
|
|
@@ -76,13 +76,19 @@ Les chiffres ci-dessus surestiment donc légèrement la performance attendue sur
|
|
| 76 |
|
| 77 |
## 🎯 Niveaux de Risque
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|--------|-------|
|
| 81 |
-
| **FAIBLE** | 0-39 % |
|
| 82 |
-
| **MOYEN** | 40-69 % |
|
| 83 |
-
| **ÉLEVÉ** | 70-100 % |
|
| 84 |
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
## 📊 Ajustements par Quartier
|
| 88 |
|
|
|
|
| 76 |
|
| 77 |
## 🎯 Niveaux de Risque
|
| 78 |
|
| 79 |
+
Le risque affiché est la **probabilité brute** de l'ensemble (moyenne LightGBM/LSTM), multipliée par le coefficient du quartier, puis bornée à 100 %. Aucun rééchelonnement ni plancher. Cette probabilité est bien calibrée sur le test : moyenne prédite 14,1 %, taux réel 14,05 %, écart ≤ 1,6 point par décile.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
+
Seuils fixés sur la distribution du jeu de test (14 000 lignes, coefficient de quartier appliqué) :
|
| 82 |
+
|
| 83 |
+
| Niveau | Plage | Part des cas | Taux de coupure réel | Part des coupures captées |
|
| 84 |
+
|--------|-------|---|---|---|
|
| 85 |
+
| **FAIBLE** | < 15 % | 61,4 % | 2,5 % | 10,9 % |
|
| 86 |
+
| **MOYEN** | 15-35 % | 24,9 % | 22,0 % | 38,8 % |
|
| 87 |
+
| **ÉLEVÉ** | ≥ 35 % | 13,7 % | 51,5 % | 50,2 % |
|
| 88 |
+
|
| 89 |
+
FAIBLE correspond à un risque inférieur au taux moyen (14 %) ; ÉLEVÉ à une coupure plus probable qu'improbable. Probabilité maximale observée : 0,72 avant coefficient, 0,84 après. Ces seuils ont été choisis sur le jeu de test, déjà utilisé pour l'arrêt anticipé : même réserve d'optimisme que pour les métriques.
|
| 90 |
+
|
| 91 |
+
*Historique : jusqu'à cette correction, l'app multipliait la probabilité par 2 (« seuil 0,25 → 50 % »), plafonnait avant d'appliquer le coefficient, imposait un plancher de 5 % et classait à 40 / 70 %.*
|
| 92 |
|
| 93 |
## 📊 Ajustements par Quartier
|
| 94 |
|
|
@@ -54,8 +54,8 @@ J'ai développé un **système d'ensemble combinant 2 algorithmes** pour maximis
|
|
| 54 |
- Apprentissage de patterns complexes
|
| 55 |
|
| 56 |
3. **Prédiction finale** : Moyenne simple des 2 modèles
|
| 57 |
-
- Risque
|
| 58 |
-
- Classification : FAIBLE (
|
| 59 |
|
| 60 |
### Dataset
|
| 61 |
|
|
|
|
| 54 |
- Apprentissage de patterns complexes
|
| 55 |
|
| 56 |
3. **Prédiction finale** : Moyenne simple des 2 modèles
|
| 57 |
+
- Risque = probabilité moyenne des 2 modèles × coefficient du quartier (en %, sans rééchelonnement)
|
| 58 |
+
- Classification : FAIBLE (< 15 %), MOYEN (15-35 %), ÉLEVÉ (≥ 35 %) — sur le test synthétique, taux réel de coupure 2,5 % / 22 % / 51,5 %
|
| 59 |
|
| 60 |
### Dataset
|
| 61 |
|
|
@@ -59,8 +59,13 @@ QUARTIER_ADJUSTMENT = {
|
|
| 59 |
'Fann': 0.95
|
| 60 |
}
|
| 61 |
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
def classify_risk(score: float) -> str:
|
| 66 |
if score < RISK_THRESHOLDS['faible']: return "FAIBLE"
|
|
|
|
| 59 |
'Fann': 0.95
|
| 60 |
}
|
| 61 |
|
| 62 |
+
# Seuils en % de probabilité (ensemble LightGBM + LSTM × coefficient de quartier).
|
| 63 |
+
# Fixés sur la distribution réelle du jeu de test (14 000 lignes) :
|
| 64 |
+
# FAIBLE < 15 % : 61,4 % des cas, taux de coupure réel 2,5 % (sous le taux moyen de 14 %)
|
| 65 |
+
# MOYEN 15-35 % : 24,9 % des cas, taux de coupure réel 22,0 %
|
| 66 |
+
# ÉLEVÉ ≥ 35 % : 13,7 % des cas, taux de coupure réel 51,5 % (coupure plus probable qu'improbable)
|
| 67 |
+
# Le jeu de test ayant déjà servi à l'arrêt anticipé, ces chiffres sont légèrement optimistes.
|
| 68 |
+
RISK_THRESHOLDS = {'faible': 15, 'eleve': 35}
|
| 69 |
|
| 70 |
def classify_risk(score: float) -> str:
|
| 71 |
if score < RISK_THRESHOLDS['faible']: return "FAIBLE"
|
|
@@ -142,18 +142,23 @@ with tab1:
|
|
| 142 |
|
| 143 |
col1, col2, col3 = st.columns(3)
|
| 144 |
with col1:
|
| 145 |
-
st.metric("🌳 LightGBM", f"{pred_lgb:.1f}%")
|
| 146 |
with col2:
|
| 147 |
-
st.metric("🧠 LSTM", f"{pred_lstm:.1f}%")
|
| 148 |
with col3:
|
| 149 |
st.metric("⚠️ NIVEAU", niveau)
|
| 150 |
|
| 151 |
if risque < RISK_THRESHOLDS['faible']:
|
| 152 |
-
st.success(f"✅ Risque {niveau} ({risque:.
|
| 153 |
elif risque < RISK_THRESHOLDS['eleve']:
|
| 154 |
-
st.warning(f"⚠️ Risque {niveau} ({risque:.
|
| 155 |
else:
|
| 156 |
-
st.error(f"🚨 Risque {niveau} ({risque:.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
if st.session_state.get('predictions_history'):
|
| 159 |
df_export = pd.DataFrame(st.session_state['predictions_history'])
|
|
|
|
| 142 |
|
| 143 |
col1, col2, col3 = st.columns(3)
|
| 144 |
with col1:
|
| 145 |
+
st.metric("🌳 LightGBM (hors quartier)", f"{pred_lgb:.1f}%")
|
| 146 |
with col2:
|
| 147 |
+
st.metric("🧠 LSTM (hors quartier)", f"{pred_lstm:.1f}%")
|
| 148 |
with col3:
|
| 149 |
st.metric("⚠️ NIVEAU", niveau)
|
| 150 |
|
| 151 |
if risque < RISK_THRESHOLDS['faible']:
|
| 152 |
+
st.success(f"✅ Risque {niveau} ({risque:.1f}%)")
|
| 153 |
elif risque < RISK_THRESHOLDS['eleve']:
|
| 154 |
+
st.warning(f"⚠️ Risque {niveau} ({risque:.1f}%)")
|
| 155 |
else:
|
| 156 |
+
st.error(f"🚨 Risque {niveau} ({risque:.1f}%)")
|
| 157 |
+
st.caption(
|
| 158 |
+
f"Probabilité de coupure estimée par le modèle (moyenne LightGBM/LSTM × coefficient du quartier). "
|
| 159 |
+
f"Niveaux : FAIBLE < {RISK_THRESHOLDS['faible']} %, MOYEN < {RISK_THRESHOLDS['eleve']} %, ÉLEVÉ au-delà. "
|
| 160 |
+
f"Sur le jeu de test synthétique, le taux réel de coupure est de 2,5 % / 22 % / 51,5 % dans ces trois niveaux."
|
| 161 |
+
)
|
| 162 |
|
| 163 |
if st.session_state.get('predictions_history'):
|
| 164 |
df_export = pd.DataFrame(st.session_state['predictions_history'])
|
|
@@ -22,10 +22,7 @@ warnings.filterwarnings('ignore', category=UserWarning, module='keras')
|
|
| 22 |
warnings.filterwarnings('ignore', category=UserWarning, module='lightgbm')
|
| 23 |
|
| 24 |
from src.config import (QUARTIERS_DAKAR, COORDONNEES_QUARTIERS, QUARTIER_ADJUSTMENT,
|
| 25 |
-
classify_risk, RISK_THRESHOLDS
|
| 26 |
-
|
| 27 |
-
# Seuil de décision optimal (déterminé sur set de test : recall 60%, F1 0.52)
|
| 28 |
-
PREDICTION_THRESHOLD = 0.25
|
| 29 |
|
| 30 |
logger = logging.getLogger(__name__)
|
| 31 |
|
|
@@ -76,51 +73,47 @@ def create_time_features(date_time: datetime, hour_override: int = None) -> dict
|
|
| 76 |
'is_peak_hour': is_peak_hour,
|
| 77 |
}
|
| 78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
def make_prediction_single(models, quartier, temp, humidite, vent, conso, time_features):
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
|
|
|
| 84 |
return None
|
| 85 |
try:
|
| 86 |
features = [temp, humidite, vent, conso, time_features['hour'], time_features['day_of_week'], time_features['month'], time_features['saison'], time_features['is_peak_hour']]
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
logger.error(f"LightGBM prediction failed: {e}")
|
| 93 |
-
pred_lgb = 50.0
|
| 94 |
-
if lstm_model is not None:
|
| 95 |
-
try:
|
| 96 |
-
features_lstm = features_scaled.reshape(1, 1, -1)
|
| 97 |
-
pred_lstm = float(lstm_model.predict(features_lstm, verbose=0)[0][0]) * 100
|
| 98 |
-
except Exception as e:
|
| 99 |
-
logger.warning(f"LSTM prediction failed, falling back to LightGBM: {e}")
|
| 100 |
-
pred_lstm = pred_lgb
|
| 101 |
-
else:
|
| 102 |
-
pred_lstm = pred_lgb
|
| 103 |
-
risque_base = (pred_lgb + pred_lstm) / 2
|
| 104 |
-
# Recalibration : prob=THRESHOLD → 50 % affiché
|
| 105 |
-
scale = 0.5 / PREDICTION_THRESHOLD
|
| 106 |
-
risque_base = min(100.0, risque_base * scale)
|
| 107 |
-
pred_lgb = min(100.0, pred_lgb * scale)
|
| 108 |
-
pred_lstm = min(100.0, pred_lstm * scale)
|
| 109 |
-
adjustment = QUARTIER_ADJUSTMENT.get(quartier, 1.0)
|
| 110 |
-
risque_ajuste = max(RISK_FLOOR, risque_base * adjustment)
|
| 111 |
-
pred_lgb = np.clip(pred_lgb, 0, 100)
|
| 112 |
-
pred_lstm = np.clip(pred_lstm, 0, 100)
|
| 113 |
-
risque_ajuste = np.clip(risque_ajuste, 0, 100)
|
| 114 |
-
return pred_lgb, pred_lstm, risque_ajuste
|
| 115 |
except Exception as e:
|
| 116 |
-
|
|
|
|
| 117 |
return None
|
| 118 |
|
| 119 |
def compute_map_risks(models, temperature, humidite, vitesse_vent, consommation, time_features):
|
| 120 |
-
|
| 121 |
-
lstm_model = models['lstm']
|
| 122 |
-
scaler = models['scaler']
|
| 123 |
-
if lgb_model is None or scaler is None:
|
| 124 |
return None
|
| 125 |
feature_row = [
|
| 126 |
temperature, humidite, vitesse_vent, consommation,
|
|
@@ -128,24 +121,13 @@ def compute_map_risks(models, temperature, humidite, vitesse_vent, consommation,
|
|
| 128 |
time_features['month'], time_features['saison'],
|
| 129 |
time_features['is_peak_hour'],
|
| 130 |
]
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
if lstm_model is not None:
|
| 136 |
-
preds_lstm = np.clip(
|
| 137 |
-
lstm_model.predict(X_scaled.reshape(len(QUARTIERS_DAKAR), 1, -1), verbose=0).flatten() * 100 * scale,
|
| 138 |
-
0, 100
|
| 139 |
-
)
|
| 140 |
-
else:
|
| 141 |
-
preds_lstm = preds_lgb.copy()
|
| 142 |
-
risque_base = (preds_lgb + preds_lstm) / 2
|
| 143 |
return [
|
| 144 |
-
{
|
| 145 |
-
|
| 146 |
-
'Risque': float(np.clip(max(RISK_FLOOR, risque_base[i] * QUARTIER_ADJUSTMENT.get(q, 1.0)), 0, 100)),
|
| 147 |
-
}
|
| 148 |
-
for i, q in enumerate(QUARTIERS_DAKAR)
|
| 149 |
]
|
| 150 |
|
| 151 |
def get_risk_color(risque_pct):
|
|
@@ -165,14 +147,14 @@ def create_gauge_chart(risque, quartier):
|
|
| 165 |
value=risque,
|
| 166 |
domain={'x': [0, 1], 'y': [0, 1]},
|
| 167 |
title={'text': f"{quartier}", 'font': {'size': 20}},
|
| 168 |
-
number={'suffix': "%", 'font': {'size': 50}},
|
| 169 |
gauge={
|
| 170 |
'axis': {'range': [None, 100], 'tickwidth': 2},
|
| 171 |
'bar': {'color': color, 'thickness': 0.75},
|
| 172 |
'steps': [
|
| 173 |
-
{'range': [0,
|
| 174 |
-
{'range': [
|
| 175 |
-
{'range': [
|
| 176 |
]
|
| 177 |
}
|
| 178 |
))
|
|
@@ -325,8 +307,8 @@ def create_risk_trend_chart(df_hist, quartier_filter):
|
|
| 325 |
customdata=df_daily[['niveau', 'coupures']],
|
| 326 |
hovertemplate='<b>%{x}</b><br>Taux: %{y:.1f}%<br>Niveau: %{customdata[0]}<extra></extra>'
|
| 327 |
))
|
| 328 |
-
fig.add_hline(y=
|
| 329 |
-
fig.add_hline(y=
|
| 330 |
title = f"Tendance - {quartier_filter}" if quartier_filter != "Tous" else "Tendance"
|
| 331 |
fig.update_layout(title=title, xaxis_title="Date", yaxis_title="Taux (%)", height=500)
|
| 332 |
return fig
|
|
|
|
| 22 |
warnings.filterwarnings('ignore', category=UserWarning, module='lightgbm')
|
| 23 |
|
| 24 |
from src.config import (QUARTIERS_DAKAR, COORDONNEES_QUARTIERS, QUARTIER_ADJUSTMENT,
|
| 25 |
+
classify_risk, RISK_THRESHOLDS)
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
logger = logging.getLogger(__name__)
|
| 28 |
|
|
|
|
| 73 |
'is_peak_hour': is_peak_hour,
|
| 74 |
}
|
| 75 |
|
| 76 |
+
def _predict_probas_pct(models, X_scaled):
|
| 77 |
+
"""Probabilités brutes (en %) de LightGBM et du LSTM pour chaque ligne de X_scaled.
|
| 78 |
+
Si le LSTM est indisponible, LightGBM est utilisé pour les deux colonnes."""
|
| 79 |
+
preds_lgb = np.asarray(models['lgb'].predict(X_scaled), dtype=float) * 100
|
| 80 |
+
preds_lstm = preds_lgb.copy()
|
| 81 |
+
if models['lstm'] is not None:
|
| 82 |
+
try:
|
| 83 |
+
preds_lstm = models['lstm'].predict(
|
| 84 |
+
X_scaled.reshape(len(X_scaled), 1, -1), verbose=0
|
| 85 |
+
).flatten().astype(float) * 100
|
| 86 |
+
except Exception as e:
|
| 87 |
+
logger.warning(f"LSTM prediction failed, falling back to LightGBM: {e}")
|
| 88 |
+
return preds_lgb, preds_lstm
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def apply_quartier_adjustment(proba_pct, quartier):
|
| 92 |
+
"""Applique le coefficient de quartier à la probabilité (en %), PUIS borne à [0, 100]."""
|
| 93 |
+
return float(np.clip(proba_pct * QUARTIER_ADJUSTMENT.get(quartier, 1.0), 0, 100))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
def make_prediction_single(models, quartier, temp, humidite, vent, conso, time_features):
|
| 97 |
+
"""Retourne (proba LightGBM %, proba LSTM %, risque du quartier %).
|
| 98 |
+
|
| 99 |
+
Le risque est la moyenne des deux probabilités brutes (aucun rééchelonnement),
|
| 100 |
+
multipliée par le coefficient du quartier puis bornée à 100 %."""
|
| 101 |
+
if models['lgb'] is None or models['scaler'] is None:
|
| 102 |
return None
|
| 103 |
try:
|
| 104 |
features = [temp, humidite, vent, conso, time_features['hour'], time_features['day_of_week'], time_features['month'], time_features['saison'], time_features['is_peak_hour']]
|
| 105 |
+
features_scaled = models['scaler'].transform(np.array([features]))
|
| 106 |
+
preds_lgb, preds_lstm = _predict_probas_pct(models, features_scaled)
|
| 107 |
+
pred_lgb, pred_lstm = float(preds_lgb[0]), float(preds_lstm[0])
|
| 108 |
+
risque = apply_quartier_adjustment((pred_lgb + pred_lstm) / 2, quartier)
|
| 109 |
+
return pred_lgb, pred_lstm, risque
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
except Exception as e:
|
| 111 |
+
logger.error(f"Prediction failed: {e}")
|
| 112 |
+
st.error(f"❌ Erreur de prédiction : {e}")
|
| 113 |
return None
|
| 114 |
|
| 115 |
def compute_map_risks(models, temperature, humidite, vitesse_vent, consommation, time_features):
|
| 116 |
+
if models['lgb'] is None or models['scaler'] is None:
|
|
|
|
|
|
|
|
|
|
| 117 |
return None
|
| 118 |
feature_row = [
|
| 119 |
temperature, humidite, vitesse_vent, consommation,
|
|
|
|
| 121 |
time_features['month'], time_features['saison'],
|
| 122 |
time_features['is_peak_hour'],
|
| 123 |
]
|
| 124 |
+
X_scaled = models['scaler'].transform(np.array([feature_row]))
|
| 125 |
+
preds_lgb, preds_lstm = _predict_probas_pct(models, X_scaled)
|
| 126 |
+
# Le quartier n'est pas une feature : même probabilité de base pour tous
|
| 127 |
+
risque_base = float((preds_lgb[0] + preds_lstm[0]) / 2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
return [
|
| 129 |
+
{'Quartier': q, 'Risque': apply_quartier_adjustment(risque_base, q)}
|
| 130 |
+
for q in QUARTIERS_DAKAR
|
|
|
|
|
|
|
|
|
|
| 131 |
]
|
| 132 |
|
| 133 |
def get_risk_color(risque_pct):
|
|
|
|
| 147 |
value=risque,
|
| 148 |
domain={'x': [0, 1], 'y': [0, 1]},
|
| 149 |
title={'text': f"{quartier}", 'font': {'size': 20}},
|
| 150 |
+
number={'suffix': "%", 'valueformat': '.1f', 'font': {'size': 50}},
|
| 151 |
gauge={
|
| 152 |
'axis': {'range': [None, 100], 'tickwidth': 2},
|
| 153 |
'bar': {'color': color, 'thickness': 0.75},
|
| 154 |
'steps': [
|
| 155 |
+
{'range': [0, RISK_THRESHOLDS['faible']], 'color': '#d4edda'},
|
| 156 |
+
{'range': [RISK_THRESHOLDS['faible'], RISK_THRESHOLDS['eleve']], 'color': '#fff3cd'},
|
| 157 |
+
{'range': [RISK_THRESHOLDS['eleve'], 100], 'color': '#f8d7da'}
|
| 158 |
]
|
| 159 |
}
|
| 160 |
))
|
|
|
|
| 307 |
customdata=df_daily[['niveau', 'coupures']],
|
| 308 |
hovertemplate='<b>%{x}</b><br>Taux: %{y:.1f}%<br>Niveau: %{customdata[0]}<extra></extra>'
|
| 309 |
))
|
| 310 |
+
fig.add_hline(y=RISK_THRESHOLDS['faible'], line_dash="dash", line_color="#ffc107", annotation_text="Seuil MOYEN")
|
| 311 |
+
fig.add_hline(y=RISK_THRESHOLDS['eleve'], line_dash="dash", line_color="#dc3545", annotation_text="Seuil ÉLEVÉ")
|
| 312 |
title = f"Tendance - {quartier_filter}" if quartier_filter != "Tous" else "Tendance"
|
| 313 |
fig.update_layout(title=title, xaxis_title="Date", yaxis_title="Taux (%)", height=500)
|
| 314 |
return fig
|
|
@@ -3,18 +3,26 @@ from pathlib import Path
|
|
| 3 |
|
| 4 |
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 5 |
|
| 6 |
-
from src.config import classify_risk, QUARTIERS_DAKAR, QUARTIER_ADJUSTMENT
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
|
| 9 |
def test_classify_risk_faible():
|
| 10 |
-
assert classify_risk(
|
|
|
|
| 11 |
|
| 12 |
|
| 13 |
def test_classify_risk_moyen():
|
| 14 |
-
assert classify_risk(
|
|
|
|
| 15 |
|
| 16 |
|
| 17 |
def test_classify_risk_eleve():
|
|
|
|
| 18 |
assert classify_risk(80) == "ÉLEVÉ"
|
| 19 |
|
| 20 |
|
|
|
|
| 3 |
|
| 4 |
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 5 |
|
| 6 |
+
from src.config import classify_risk, QUARTIERS_DAKAR, QUARTIER_ADJUSTMENT, RISK_THRESHOLDS
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_seuils_valeurs_figees():
|
| 10 |
+
# Seuils fixés sur la distribution réelle du jeu de test (voir src/config.py)
|
| 11 |
+
assert RISK_THRESHOLDS == {'faible': 15, 'eleve': 35}
|
| 12 |
|
| 13 |
|
| 14 |
def test_classify_risk_faible():
|
| 15 |
+
assert classify_risk(0.1) == "FAIBLE"
|
| 16 |
+
assert classify_risk(14.9) == "FAIBLE"
|
| 17 |
|
| 18 |
|
| 19 |
def test_classify_risk_moyen():
|
| 20 |
+
assert classify_risk(15) == "MOYEN"
|
| 21 |
+
assert classify_risk(34.9) == "MOYEN"
|
| 22 |
|
| 23 |
|
| 24 |
def test_classify_risk_eleve():
|
| 25 |
+
assert classify_risk(35) == "ÉLEVÉ"
|
| 26 |
assert classify_risk(80) == "ÉLEVÉ"
|
| 27 |
|
| 28 |
|
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pipeline de prédiction avec des modèles factices : vérifie que le risque affiché
|
| 3 |
+
est la vraie probabilité (pas de rééchelonnement ×2) et que le coefficient de
|
| 4 |
+
quartier est appliqué AVANT le plafonnement à 100 %.
|
| 5 |
+
"""
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from unittest.mock import MagicMock
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pytest
|
| 13 |
+
|
| 14 |
+
sys.modules['streamlit'] = MagicMock()
|
| 15 |
+
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 16 |
+
|
| 17 |
+
from src.config import QUARTIER_ADJUSTMENT, QUARTIERS_DAKAR
|
| 18 |
+
from streamlit_app.utils_simple import (
|
| 19 |
+
make_prediction_single, compute_map_risks, create_time_features,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class _Identity:
|
| 24 |
+
def transform(self, X):
|
| 25 |
+
return np.asarray(X, dtype=float)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class _ConstLGB:
|
| 29 |
+
def __init__(self, p):
|
| 30 |
+
self.p = p
|
| 31 |
+
|
| 32 |
+
def predict(self, X):
|
| 33 |
+
return np.full(len(X), self.p)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class _ConstLSTM:
|
| 37 |
+
def __init__(self, p):
|
| 38 |
+
self.p = p
|
| 39 |
+
|
| 40 |
+
def predict(self, X, verbose=0):
|
| 41 |
+
return np.full((len(X), 1), self.p)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _models(p_lgb, p_lstm=None):
|
| 45 |
+
return {
|
| 46 |
+
'lgb': _ConstLGB(p_lgb),
|
| 47 |
+
'lstm': _ConstLSTM(p_lstm) if p_lstm is not None else None,
|
| 48 |
+
'scaler': _Identity(),
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
TF = create_time_features(datetime(2024, 1, 15, 19, 0))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _predict(models, quartier):
|
| 56 |
+
return make_prediction_single(models, quartier, 25, 80, 10, 1000, TF)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_probabilite_brute_sans_rescaling():
|
| 60 |
+
pred_lgb, pred_lstm, risque = _predict(_models(0.20, 0.30), 'Yoff')
|
| 61 |
+
assert pred_lgb == pytest.approx(20.0)
|
| 62 |
+
assert pred_lstm == pytest.approx(30.0)
|
| 63 |
+
assert risque == pytest.approx(25.0) # moyenne, coefficient Yoff = 1,00, pas de ×2
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_pas_de_plancher_artificiel():
|
| 67 |
+
_, _, risque = _predict(_models(0.001, 0.001), 'Dakar-Plateau')
|
| 68 |
+
assert risque == pytest.approx(0.1 * QUARTIER_ADJUSTMENT['Dakar-Plateau'])
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_coefficient_applique_avant_plafonnement():
|
| 72 |
+
# 0,90 × 0,85 = 76,5 % pour Dakar-Plateau ; 0,90 × 1,20 = 108 % → plafonné à 100 % pour Pikine
|
| 73 |
+
_, _, plateau = _predict(_models(0.90, 0.90), 'Dakar-Plateau')
|
| 74 |
+
_, _, pikine = _predict(_models(0.90, 0.90), 'Pikine')
|
| 75 |
+
assert plateau == pytest.approx(76.5)
|
| 76 |
+
assert pikine == pytest.approx(100.0)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_lstm_absent_utilise_lightgbm():
|
| 80 |
+
pred_lgb, pred_lstm, risque = _predict(_models(0.40), 'Yoff')
|
| 81 |
+
assert pred_lgb == pred_lstm == pytest.approx(40.0)
|
| 82 |
+
assert risque == pytest.approx(40.0)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def test_carte_coherente_avec_prediction_unique():
|
| 86 |
+
models = _models(0.20, 0.30)
|
| 87 |
+
carte = {r['Quartier']: r['Risque'] for r in compute_map_risks(models, 25, 80, 10, 1000, TF)}
|
| 88 |
+
assert set(carte) == set(QUARTIERS_DAKAR)
|
| 89 |
+
for q in QUARTIERS_DAKAR:
|
| 90 |
+
assert carte[q] == pytest.approx(_predict(models, q)[2])
|