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