Spaces:
Runtime error
Runtime error
File size: 13,063 Bytes
002b8b7 98ff77a 002b8b7 98ff77a 002b8b7 98ff77a 002b8b7 98ff77a 002b8b7 98ff77a | 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 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 | import streamlit as st
import pandas as pd
import pickle
import matplotlib.pyplot as plt
from dotenv import load_dotenv
import os
import numpy as np
import shap
from sklearn.linear_model import LinearRegression
from langchain_mistralai import ChatMistralAI
from langchain_core.output_parsers import StrOutputParser
# === Chargement des données
df = pd.read_csv("https://geodechet.s3.eu-west-3.amazonaws.com/v1/dataset/df_dummies.csv").drop(columns=["Unnamed: 0"], errors="ignore")
observed_df = pd.read_excel("https://geodechet.s3.eu-west-3.amazonaws.com/v1/dataset/data_wip_v5.xlsx")
# === Liste des départements
departements = [col.replace("Département_", "") for col in df.columns if col.startswith("Département_")]
# === Mise en page
st.set_page_config(layout="wide")
st.markdown("<h1 style='text-align: center;'>♻️ Simulateur de production de déchets par département</h1>", unsafe_allow_html=True)
# === Titre + Choix département alignés
top_col1, top_col2 = st.columns([1, 2])
with top_col1:
st.markdown("<h3 style='text-align: center;'>📍 Choix du département</h3>", unsafe_allow_html=True)
with top_col2:
st.markdown("<h3 style='text-align: center;'>📈 Comparaison entre valeurs observées et prédites</h3>", unsafe_allow_html=True)
# === Séparation en colonnes
top_input_col, chart_col = st.columns([1, 2])
with top_input_col:
selected_dept = st.selectbox("Sélectionner un département", sorted(departements), index=sorted(departements).index("Ain") if "Ain" in departements else 0)
row_default = df[df[f"Département_{selected_dept}"] == 1].iloc[0]
default_dict = row_default.to_dict()
st.subheader("⚙️ Paramètres modifiables")
form_input = {}
categories = {
"📊 Population": [
"densité_n-2", "densité", "pop_globale_n-2", "pop_globale",
"tranche_age_0-24", "tranche_age_25-59", "tranche_age_60+",
"csp1_agriculteurs", "csp2_artisans_commerçant_chef_entreprises",
"csp3_cadres_professions_intellectuelles", "csp4_professions_intermédiaires",
"csp5_employés", "csp6_ouvriers", "csp7_retraités", "csp8_sans_activité"
],
"🏭 Activité économique": [
"nb_salaries_secteur_agricole", "nb_salaries_secteur_industrie", "nb_salaries_secteur_service",
"nbre_entreprises", "nbre_entreprises_agricole", "nbre_entreprises_industrie", "nbre_entreprises_service"
],
"🗑️ Déchets": [
"tonnage_dechet_produit_n-2", "tonnage_dechet_produit",
"Total_autres_dechets_n-2", "Total_autres_dechets",
"Déblais_gravats_n-2", "Déblais_gravats",
"Déchets_verts_n-2", "Déchets_verts",
"Encombrants_n-2", "Encombrants",
"Matériaux_recyclables_n-2", "Matériaux_recyclables"
]
}
for category_name, variables in categories.items():
with st.expander(category_name, expanded=True):
for var in variables:
if var in default_dict:
col_slider, col_input = st.columns([2, 1])
with col_slider:
slider_value = st.slider(
f"🔧 {var}",
min_value=float(default_dict[var]) * 0,
max_value=float(default_dict[var]) * 1.5,
value=float(default_dict[var]),
step=1.0,
key=f"slider_{var}"
)
with col_input:
text_val = st.text_input(f"{var} (manuel)", value=str(slider_value), key=f"text_{var}")
try:
form_input[var] = float(text_val)
except ValueError:
form_input[var] = slider_value
input_df = pd.DataFrame([form_input])
input_df_complete = row_default.to_frame().T.copy()
for col in input_df.columns:
if col in input_df_complete.columns:
input_df_complete.at[input_df_complete.index[0], col] = input_df.at[0, col]
with chart_col:
st.markdown("<div style='margin-top: 30px;'></div>", unsafe_allow_html=True)
btn_col = st.columns([3, 2, 3])[1]
with btn_col:
run_eval = st.button("🔍 Lancer l'évaluation")
st.markdown("<div style='margin-top: 40px;'></div>", unsafe_allow_html=True)
model_paths = {
"Déblais et Gravats": "src/model_paths/Déblais_gravats.pkl",
"Déchets verts": "src/model_paths/Déchets_verts.pkl",
"Encombrants": "src/model_paths/Encombrants.pkl",
"Matériaux recyclables": "src/model_paths/Matériaux_recyclables.pkl",
"Total autres déchets": "src/model_paths/Total_autres_dechets.pkl"
}
col_mapping = {
"Déblais et Gravats": "Déblais_gravats",
"Déchets verts": "Déchets_verts",
"Encombrants": "Encombrants",
"Matériaux recyclables": "Matériaux_recyclables",
"Total autres déchets": "Total_autres_dechets"
}
valeurs_observees = []
valeurs_predites = []
labels = []
if run_eval:
for typologie, path in model_paths.items():
try:
with open(path, "rb") as f:
model = pickle.load(f)
expected_cols = model.model.exog_names
if "const" in expected_cols and "const" not in input_df_complete.columns:
input_df_complete["const"] = 1.0
prediction = max(0, model.predict(input_df_complete[expected_cols]).iloc[0])
valeurs_predites.append(prediction)
labels.append(typologie)
filtered = observed_df[
(observed_df["Département"] == selected_dept) & (observed_df["année"] == 2019)
]
excel_col = col_mapping.get(typologie)
if not filtered.empty and excel_col in filtered.columns:
valeurs_observees.append(filtered[excel_col].values[0])
else:
valeurs_observees.append(0.0)
except Exception as e:
st.error(f"Erreur avec le modèle {typologie}")
st.exception(e)
if valeurs_observees and valeurs_predites:
x = np.arange(len(labels))
width = 0.4
fig, ax = plt.subplots(figsize=(10, 6))
bars1 = ax.bar(x - width / 2, valeurs_observees, width, label='Observé (2019)', color='steelblue')
bar_colors = [(1, 0, 0, 0.6) if pred > obs else (0, 0.6, 0, 0.6)
for pred, obs in zip(valeurs_predites, valeurs_observees)]
bars2 = ax.bar(x + width / 2, valeurs_predites, width, label='Prévision', color=bar_colors)
for i in range(len(labels)):
ax.text(x[i] - width / 2, valeurs_observees[i] + max(valeurs_observees) * 0.01, f"{valeurs_observees[i]:,.0f}",
ha='center', va='bottom', fontsize=9)
ax.text(x[i] + width / 2, valeurs_predites[i] + max(valeurs_predites) * 0.01, f"{valeurs_predites[i]:,.0f}",
ha='center', va='bottom', fontsize=9)
ax.set_ylabel("Tonnes")
ax.set_title("Comparaison Observé vs Prédit")
ax.set_xticks(x)
ax.set_xticklabels(labels, rotation=45, ha='right')
ax.legend()
st.pyplot(fig)
# === Graphiques SHAP ===
st.markdown("---")
st.subheader(f"📉 SHAP - Analyse des contributions pour le département : {selected_dept}")
# Menu déroulant
selected_typologie = st.selectbox("Choisissez une typologie de déchets à analyser avec SHAP :", list(model_paths.keys()))
# SHAP pour la typologie sélectionnée
typologie = selected_typologie
path = model_paths[typologie]
st.markdown(f"### 🔍 {typologie}")
try:
with open(path, "rb") as f:
model_sm = pickle.load(f)
used_features = model_sm.model.exog_names
used_features_no_const = [f for f in used_features if f != "const"]
X_used = df[used_features_no_const].copy()
if "const" in used_features:
X_used["const"] = 1.0
intercept = model_sm.params['const'] if 'const' in model_sm.params else 0
coefs = model_sm.params[used_features_no_const].values
lr = LinearRegression()
lr.intercept_ = intercept
lr.coef_ = coefs
lr.feature_names_in_ = np.array(used_features_no_const)
X_used_corrected = X_used.reindex(columns=lr.feature_names_in_, fill_value=0)
explainer = shap.Explainer(lr, X_used_corrected)
shap_values = explainer(X_used_corrected)
selected_index = df[df[f"Département_{selected_dept}"] == 1].index[0]
# === Première ligne : Waterfall + Beeswarm + Moyenne des contributions
exclude_vars = [
"tonnage_dechet_produit_n-2", "tonnage_dechet_produit",
"Total_autres_dechets_n-2", "Total_autres_dechets",
"Déblais_gravats_n-2", "Déblais_gravats",
"Déchets_verts_n-2", "Déchets_verts",
"Encombrants_n-2", "Encombrants",
"Matériaux_recyclables_n-2", "Matériaux_recyclables"
]
# Création d’un masque pour filtrer les SHAP plots sans toucher à la prédiction
mask = np.array([name not in exclude_vars for name in shap_values.feature_names])
filtered_shap = shap.Explanation(
values=shap_values.values[:, mask],
base_values=shap_values.base_values,
data=shap_values.data[:, mask],
feature_names=[name for name in shap_values.feature_names if name not in exclude_vars]
)
col1 = st.columns(1)[0]
with col1:
st.markdown("<h6 style='text-align: center;'> Waterfall</h6>", unsafe_allow_html=True)
fig = plt.figure(figsize=(3, 2))
shap.plots.waterfall(filtered_shap[selected_index], max_display=10, show=False)
st.pyplot(fig, bbox_inches='tight', dpi=200, clear_figure=True)
except Exception as e:
st.error(f"Erreur dans le SHAP pour {typologie}")
st.exception(e)
# === 🧠 Explication automatique avec Mistral ===
# 1. Récupération des moyennes absolues des SHAP values
mean_shap_values = shap_values.abs.mean(0).values
feature_names = lr.feature_names_in_
# 2. Création d’un résumé lisible des coefficients (triés par impact)
sorted_indices = mean_shap_values.argsort()[::-1]
top_n = 10 # on peut ajuster ce nombre
list_coef = "\n".join([
f"{feature_names[i]}: {mean_shap_values[i]:.4f}"
for i in sorted_indices[:top_n]
])
# 3. Prompt + contexte
prompt_template = f"""
Tu es un expert en data science et en statistique, spécialisé dans l'interprétation des résultats de modèles explicatifs à l'aide des coefficients de Shapley.
Je vais te fournir les valeurs des coefficients de Shapley pour un modèle linéaire de régression, associés à chaque variable explicative.
Ta mission :
Rédige un paragraphe clair et synthétique interprétant le rôle des variables dans le modèle pour répondre au besoin de notre client qui sont les présidents des conseils départementaux. Tu dois identifier :
- Les variables qui ont le plus d’impact positif ou négatif sur la variable cible.
- Les grandes tendances démographiques ou économiques qui expliquent la production de déchets.
- Une interprétation compréhensible par un public non-expert, mais avec une rigueur statistique.
Voici les coefficients :
{list_coef}
Contexte :
- Objectif : Comprendre comment les caractéristiques démographiques et économiques influencent la production des différents types de déchets en France.
- Variable cible : {typologie}
- Modèle utilisé : OLS de Statsmodel avec coefficients de Shapley.
- Variables explicatives :
- Secteurs d’activités : Nombre de salariés par secteur : Agricole, Service, Industrie.
- Profils socioprofessionnels (CSP) :
csp1_agriculteurs, csp2_artisans_commerçant_chef_entreprises, csp3_cadres_professions_intellectuelles, csp4_professions_intermédiaires, csp5_employés, csp6_ouvriers, csp7_retraités, csp8_sans_activité.
- Tranches d’âge : tranche_age_0-24, tranche_age_25-59, tranche_age_60+.
- Autres variables :
Nombre entreprise globale, Densité de population, Population globale, Typologie d'entreprises
Valeurs historiques à n-2 pour chaque variable cible
- tu ne dois pas prendre en compte les {exclude_vars} dans ton analyse
"""
# 4. Appel à l’API Mistral
# Charge les variables d'environnement à partir du fichier .env
load_dotenv()
api_key = os.getenv("MISTRAL_API_KEY")
try:
with st.spinner("🧠 Génération de l'interprétation avec Mistral..."):
model_llm = ChatMistralAI(model="mistral-large-latest", mistral_api_key=api_key)
parser = StrOutputParser()
response = model_llm.invoke(prompt_template)
explanation_text = parser.invoke(response)
# 5. Affichage dans l’interface Streamlit
st.markdown("#### 🤖 Interprétation automatique (LLM)")
st.success(explanation_text)
except Exception as e:
st.error("Erreur lors de l'appel au LLM Mistral.")
st.exception(e)
|