suppression des apps qui marchent pas
Browse files- src/app_cache.py +0 -285
src/app_cache.py
DELETED
|
@@ -1,285 +0,0 @@
|
|
| 1 |
-
|
| 2 |
-
import streamlit as st
|
| 3 |
-
import pandas as pd
|
| 4 |
-
import pickle
|
| 5 |
-
import matplotlib.pyplot as plt
|
| 6 |
-
from dotenv import load_dotenv
|
| 7 |
-
import os
|
| 8 |
-
|
| 9 |
-
import numpy as np
|
| 10 |
-
import shap
|
| 11 |
-
from sklearn.linear_model import LinearRegression
|
| 12 |
-
from langchain_mistralai import ChatMistralAI
|
| 13 |
-
from langchain_core.output_parsers import StrOutputParser
|
| 14 |
-
|
| 15 |
-
@st.cache_data(show_spinner="📥 Chargement des datasets...")
|
| 16 |
-
def load_data():
|
| 17 |
-
df_csv = pd.read_csv("https://geodechet.s3.eu-west-3.amazonaws.com/v1/dataset/df_dummies.csv").drop(columns=["Unnamed: 0"], errors="ignore")
|
| 18 |
-
df_excel = pd.read_excel("https://geodechet.s3.eu-west-3.amazonaws.com/v1/dataset/data_wip_v5.xlsx")
|
| 19 |
-
return df_csv, df_excel
|
| 20 |
-
|
| 21 |
-
@st.cache_resource(show_spinner="🧠 Chargement du modèle...")
|
| 22 |
-
def load_model(path):
|
| 23 |
-
with open(path, "rb") as f:
|
| 24 |
-
return pickle.load(f)
|
| 25 |
-
|
| 26 |
-
df, observed_df = load_data()
|
| 27 |
-
|
| 28 |
-
departements = [col.replace("Département_", "") for col in df.columns if col.startswith("Département_")]
|
| 29 |
-
|
| 30 |
-
st.set_page_config(layout="wide")
|
| 31 |
-
st.markdown("<h1 style='text-align: center;'>♻️ Simulateur de production de déchets par département</h1>", unsafe_allow_html=True)
|
| 32 |
-
|
| 33 |
-
top_col1, top_col2 = st.columns([1, 2])
|
| 34 |
-
with top_col1:
|
| 35 |
-
st.markdown("<h3 style='text-align: center;'>📍 Choix du département</h3>", unsafe_allow_html=True)
|
| 36 |
-
with top_col2:
|
| 37 |
-
st.markdown("<h3 style='text-align: center;'>📈 Comparaison entre valeurs observées et prédites</h3>", unsafe_allow_html=True)
|
| 38 |
-
|
| 39 |
-
top_input_col, chart_col = st.columns([1, 2])
|
| 40 |
-
|
| 41 |
-
with top_input_col:
|
| 42 |
-
selected_dept = st.selectbox("Sélectionner un département", sorted(departements), index=sorted(departements).index("Ain") if "Ain" in departements else 0)
|
| 43 |
-
row_default = df[df[f"Département_{selected_dept}"] == 1].iloc[0]
|
| 44 |
-
default_dict = row_default.to_dict()
|
| 45 |
-
|
| 46 |
-
st.subheader("⚙️ Paramètres modifiables")
|
| 47 |
-
form_input = {}
|
| 48 |
-
|
| 49 |
-
categories = {
|
| 50 |
-
"📊 Population": [
|
| 51 |
-
"densité_n-2", "densité", "pop_globale_n-2", "pop_globale",
|
| 52 |
-
"tranche_age_0-24", "tranche_age_25-59", "tranche_age_60+",
|
| 53 |
-
"csp1_agriculteurs", "csp2_artisans_commerçant_chef_entreprises",
|
| 54 |
-
"csp3_cadres_professions_intellectuelles", "csp4_professions_intermédiaires",
|
| 55 |
-
"csp5_employés", "csp6_ouvriers", "csp7_retraités", "csp8_sans_activité"
|
| 56 |
-
],
|
| 57 |
-
"🏭 Activité économique": [
|
| 58 |
-
"nb_salaries_secteur_agricole", "nb_salaries_secteur_industrie", "nb_salaries_secteur_service",
|
| 59 |
-
"nbre_entreprises", "nbre_entreprises_agricole", "nbre_entreprises_industrie", "nbre_entreprises_service"
|
| 60 |
-
],
|
| 61 |
-
"🗑️ Déchets": [
|
| 62 |
-
"tonnage_dechet_produit_n-2", "tonnage_dechet_produit",
|
| 63 |
-
"Total_autres_dechets_n-2", "Total_autres_dechets",
|
| 64 |
-
"Déblais_gravats_n-2", "Déblais_gravats",
|
| 65 |
-
"Déchets_verts_n-2", "Déchets_verts",
|
| 66 |
-
"Encombrants_n-2", "Encombrants",
|
| 67 |
-
"Matériaux_recyclables_n-2", "Matériaux_recyclables"
|
| 68 |
-
]
|
| 69 |
-
}
|
| 70 |
-
|
| 71 |
-
for category_name, variables in categories.items():
|
| 72 |
-
with st.expander(category_name, expanded=True):
|
| 73 |
-
for var in variables:
|
| 74 |
-
if var in default_dict:
|
| 75 |
-
col_slider, col_input = st.columns([2, 1])
|
| 76 |
-
with col_slider:
|
| 77 |
-
slider_value = st.slider(
|
| 78 |
-
f"🔧 {var}",
|
| 79 |
-
min_value=float(default_dict[var]) * 0,
|
| 80 |
-
max_value=float(default_dict[var]) * 1.5,
|
| 81 |
-
value=float(default_dict[var]),
|
| 82 |
-
step=1.0,
|
| 83 |
-
key=f"slider_{var}"
|
| 84 |
-
)
|
| 85 |
-
with col_input:
|
| 86 |
-
text_val = st.text_input(f"{var}", value=str(slider_value), key=f"text_{var}")
|
| 87 |
-
try:
|
| 88 |
-
form_input[var] = float(text_val)
|
| 89 |
-
except ValueError:
|
| 90 |
-
form_input[var] = slider_value
|
| 91 |
-
|
| 92 |
-
input_df = pd.DataFrame([form_input])
|
| 93 |
-
input_df_complete = row_default.to_frame().T.copy()
|
| 94 |
-
for col in input_df.columns:
|
| 95 |
-
if col in input_df_complete.columns:
|
| 96 |
-
input_df_complete.at[input_df_complete.index[0], col] = input_df.at[0, col]
|
| 97 |
-
|
| 98 |
-
with chart_col:
|
| 99 |
-
st.markdown("<div style='margin-top: 30px;'></div>", unsafe_allow_html=True)
|
| 100 |
-
|
| 101 |
-
btn_col = st.columns([3, 2, 3])[1]
|
| 102 |
-
with btn_col:
|
| 103 |
-
run_eval = st.button("🔍 Lancer l'évaluation")
|
| 104 |
-
|
| 105 |
-
st.markdown("<div style='margin-top: 40px;'></div>", unsafe_allow_html=True)
|
| 106 |
-
|
| 107 |
-
model_paths = {
|
| 108 |
-
"Déblais et Gravats": "src/model_paths/Déblais_gravats.pkl",
|
| 109 |
-
"Déchets verts": "src/model_paths/Déchets_verts.pkl",
|
| 110 |
-
"Encombrants": "src/model_paths/Encombrants.pkl",
|
| 111 |
-
"Matériaux recyclables": "src/model_paths/Matériaux_recyclables.pkl",
|
| 112 |
-
"Total autres déchets": "src/model_paths/Total_autres_dechets.pkl"
|
| 113 |
-
}
|
| 114 |
-
|
| 115 |
-
col_mapping = {
|
| 116 |
-
"Déblais et Gravats": "Déblais_gravats",
|
| 117 |
-
"Déchets verts": "Déchets_verts",
|
| 118 |
-
"Encombrants": "Encombrants",
|
| 119 |
-
"Matériaux recyclables": "Matériaux_recyclables",
|
| 120 |
-
"Total autres déchets": "Total_autres_dechets"
|
| 121 |
-
}
|
| 122 |
-
|
| 123 |
-
valeurs_observees = []
|
| 124 |
-
valeurs_predites = []
|
| 125 |
-
labels = []
|
| 126 |
-
|
| 127 |
-
if run_eval:
|
| 128 |
-
for typologie, path in model_paths.items():
|
| 129 |
-
try:
|
| 130 |
-
model = load_model(path)
|
| 131 |
-
|
| 132 |
-
expected_cols = model.model.exog_names
|
| 133 |
-
if "const" in expected_cols and "const" not in input_df_complete.columns:
|
| 134 |
-
input_df_complete["const"] = 1.0
|
| 135 |
-
|
| 136 |
-
prediction = max(0, model.predict(input_df_complete[expected_cols]).iloc[0])
|
| 137 |
-
valeurs_predites.append(prediction)
|
| 138 |
-
labels.append(typologie)
|
| 139 |
-
|
| 140 |
-
filtered = observed_df[
|
| 141 |
-
(observed_df["Département"] == selected_dept) & (observed_df["année"] == 2019)
|
| 142 |
-
]
|
| 143 |
-
|
| 144 |
-
excel_col = col_mapping.get(typologie)
|
| 145 |
-
if not filtered.empty and excel_col in filtered.columns:
|
| 146 |
-
valeurs_observees.append(filtered[excel_col].values[0])
|
| 147 |
-
else:
|
| 148 |
-
valeurs_observees.append(0.0)
|
| 149 |
-
except Exception as e:
|
| 150 |
-
st.error(f"Erreur avec le modèle {typologie}")
|
| 151 |
-
st.exception(e)
|
| 152 |
-
|
| 153 |
-
if valeurs_observees and valeurs_predites:
|
| 154 |
-
x = np.arange(len(labels))
|
| 155 |
-
width = 0.4
|
| 156 |
-
fig, ax = plt.subplots(figsize=(10, 6))
|
| 157 |
-
|
| 158 |
-
bars1 = ax.bar(x - width / 2, valeurs_observees, width, label='Observé (2019)', color='steelblue')
|
| 159 |
-
bar_colors = [(1, 0, 0, 0.6) if pred > obs else (0, 0.6, 0, 0.6)
|
| 160 |
-
for pred, obs in zip(valeurs_predites, valeurs_observees)]
|
| 161 |
-
bars2 = ax.bar(x + width / 2, valeurs_predites, width, label='Prévision', color=bar_colors)
|
| 162 |
-
|
| 163 |
-
for i in range(len(labels)):
|
| 164 |
-
ax.text(x[i] - width / 2, valeurs_observees[i] + max(valeurs_observees) * 0.01, f"{valeurs_observees[i]:,.0f}",
|
| 165 |
-
ha='center', va='bottom', fontsize=9)
|
| 166 |
-
ax.text(x[i] + width / 2, valeurs_predites[i] + max(valeurs_predites) * 0.01, f"{valeurs_predites[i]:,.0f}",
|
| 167 |
-
ha='center', va='bottom', fontsize=9)
|
| 168 |
-
|
| 169 |
-
ax.set_ylabel("Tonnes")
|
| 170 |
-
ax.set_title("Comparaison Observé vs Prédit")
|
| 171 |
-
ax.set_xticks(x)
|
| 172 |
-
ax.set_xticklabels(labels, rotation=45, ha='right')
|
| 173 |
-
ax.legend()
|
| 174 |
-
st.pyplot(fig)
|
| 175 |
-
|
| 176 |
-
# === Graphiques SHAP ===
|
| 177 |
-
st.markdown("---")
|
| 178 |
-
st.subheader(f"📉 SHAP - Analyse des contributions pour le département : {selected_dept}")
|
| 179 |
-
|
| 180 |
-
selected_typologie = st.selectbox("Choisissez une typologie de déchets à analyser avec SHAP :", list(model_paths.keys()))
|
| 181 |
-
typologie = selected_typologie
|
| 182 |
-
path = model_paths[typologie]
|
| 183 |
-
|
| 184 |
-
st.markdown(f"### 🔍 {typologie}")
|
| 185 |
-
|
| 186 |
-
try:
|
| 187 |
-
model_sm = load_model(path)
|
| 188 |
-
used_features = model_sm.model.exog_names
|
| 189 |
-
used_features_no_const = [f for f in used_features if f != "const"]
|
| 190 |
-
X_used = df[used_features_no_const].copy()
|
| 191 |
-
|
| 192 |
-
if "const" in used_features:
|
| 193 |
-
X_used["const"] = 1.0
|
| 194 |
-
|
| 195 |
-
intercept = model_sm.params['const'] if 'const' in model_sm.params else 0
|
| 196 |
-
coefs = model_sm.params[used_features_no_const].values
|
| 197 |
-
|
| 198 |
-
lr = LinearRegression()
|
| 199 |
-
lr.intercept_ = intercept
|
| 200 |
-
lr.coef_ = coefs
|
| 201 |
-
lr.feature_names_in_ = np.array(used_features_no_const)
|
| 202 |
-
|
| 203 |
-
X_used_corrected = X_used.reindex(columns=lr.feature_names_in_, fill_value=0)
|
| 204 |
-
explainer = shap.Explainer(lr, X_used_corrected)
|
| 205 |
-
shap_values = explainer(X_used_corrected)
|
| 206 |
-
selected_index = df[df[f"Département_{selected_dept}"] == 1].index[0]
|
| 207 |
-
|
| 208 |
-
col1, col2, col3 = st.columns(3)
|
| 209 |
-
with col1:
|
| 210 |
-
st.markdown("<h6 style='text-align: center;'> Waterfall</h6>", unsafe_allow_html=True)
|
| 211 |
-
fig = plt.figure(figsize=(3, 2))
|
| 212 |
-
shap.plots.waterfall(shap_values[selected_index], max_display=10, show=False)
|
| 213 |
-
st.pyplot(fig, bbox_inches='tight', dpi=200, clear_figure=True)
|
| 214 |
-
with col2:
|
| 215 |
-
st.markdown("<h6 style='text-align: center;'>🐝 Beeswarm</h6>", unsafe_allow_html=True)
|
| 216 |
-
fig = plt.figure(figsize=(3, 2))
|
| 217 |
-
shap.plots.beeswarm(shap_values, max_display=15, show=False)
|
| 218 |
-
st.pyplot(fig, bbox_inches='tight', dpi=200, clear_figure=True)
|
| 219 |
-
with col3:
|
| 220 |
-
st.markdown("<h6 style='text-align: center;'>📊 Moyenne des contributions</h6>", unsafe_allow_html=True)
|
| 221 |
-
fig = plt.figure(figsize=(3, 2))
|
| 222 |
-
shap.plots.bar(shap_values, max_display=15, show=False)
|
| 223 |
-
st.pyplot(fig, bbox_inches='tight', dpi=200, clear_figure=True)
|
| 224 |
-
|
| 225 |
-
except Exception as e:
|
| 226 |
-
st.error(f"Erreur dans le SHAP pour {typologie}")
|
| 227 |
-
st.exception(e)
|
| 228 |
-
|
| 229 |
-
# === 🧠 Explication automatique avec Mistral ===
|
| 230 |
-
|
| 231 |
-
mean_shap_values = shap_values.abs.mean(0).values
|
| 232 |
-
feature_names = lr.feature_names_in_
|
| 233 |
-
|
| 234 |
-
sorted_indices = mean_shap_values.argsort()[::-1]
|
| 235 |
-
top_n = 10
|
| 236 |
-
list_coef = "\n".join([
|
| 237 |
-
f"{feature_names[i]}: {mean_shap_values[i]:.4f}"
|
| 238 |
-
for i in sorted_indices[:top_n]
|
| 239 |
-
])
|
| 240 |
-
|
| 241 |
-
prompt_template = f"""
|
| 242 |
-
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.
|
| 243 |
-
|
| 244 |
-
Je vais te fournir les valeurs des coefficients de Shapley pour un modèle linéaire de régression, associés à chaque variable explicative.
|
| 245 |
-
|
| 246 |
-
Ta mission :
|
| 247 |
-
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 :
|
| 248 |
-
|
| 249 |
-
- Les variables qui ont le plus d’impact positif ou négatif sur la variable cible.
|
| 250 |
-
- Les grandes tendances démographiques ou économiques qui expliquent la production de déchets.
|
| 251 |
-
- Une interprétation compréhensible par un public non-expert, mais avec une rigueur statistique.
|
| 252 |
-
|
| 253 |
-
Voici les coefficients :
|
| 254 |
-
{list_coef}
|
| 255 |
-
|
| 256 |
-
Contexte :
|
| 257 |
-
- Objectif : Comprendre comment les caractéristiques démographiques et économiques influencent la production des différents types de déchets en France.
|
| 258 |
-
- Variable cible : {typologie}
|
| 259 |
-
- Modèle utilisé : OLS de Statsmodel avec coefficients de Shapley.
|
| 260 |
-
- Variables explicatives :
|
| 261 |
-
- Secteurs d’activités : Nombre de salariés par secteur : Agricole, Service, Industrie.
|
| 262 |
-
- Profils socioprofessionnels (CSP) :
|
| 263 |
-
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é.
|
| 264 |
-
- Tranches d’âge : tranche_age_0-24, tranche_age_25-59, tranche_age_60+.
|
| 265 |
-
- Autres variables :
|
| 266 |
-
Nombre entreprise globale, Densité de population, Population globale, Typologie d'entreprises
|
| 267 |
-
Valeurs historiques à n-2 pour chaque variable cible
|
| 268 |
-
"""
|
| 269 |
-
|
| 270 |
-
load_dotenv()
|
| 271 |
-
api_key = os.getenv("MISTRAL_API_KEY")
|
| 272 |
-
|
| 273 |
-
try:
|
| 274 |
-
with st.spinner("🧠 Génération de l'interprétation avec Mistral..."):
|
| 275 |
-
model_llm = ChatMistralAI(model="mistral-large-latest", mistral_api_key=api_key)
|
| 276 |
-
parser = StrOutputParser()
|
| 277 |
-
response = model_llm.invoke(prompt_template)
|
| 278 |
-
explanation_text = parser.invoke(response)
|
| 279 |
-
|
| 280 |
-
st.markdown("#### 🤖 Interprétation automatique (LLM)")
|
| 281 |
-
st.success(explanation_text)
|
| 282 |
-
|
| 283 |
-
except Exception as e:
|
| 284 |
-
st.error("Erreur lors de l'appel au LLM Mistral.")
|
| 285 |
-
st.exception(e)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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