Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import pandas as pd | |
| from pycaret.classification import * | |
| import plotly.express as px | |
| import seaborn as sns | |
| import matplotlib.pyplot as plt | |
| import os | |
| st.set_page_config(page_title="Analyse de Risque", layout="wide") | |
| # Chargement automatique des données | |
| def load_data(): | |
| return pd.read_csv("high.csv") | |
| data = load_data() | |
| # Style CSS personnalisé conservant la couleur par défaut de Streamlit | |
| st.markdown(""" | |
| <style> | |
| .main {background-color: #f5f5f5;} | |
| .block-container {padding-top: 2rem; padding-bottom: 2rem;} | |
| h1, h2, h3 {color: #2c3e50;} | |
| .stButton>button { | |
| width: 100%; | |
| margin-bottom: 0.5rem; | |
| text-align: left !important; | |
| justify-content: flex-start; | |
| } | |
| .stDownloadButton>button { | |
| width: 100%; | |
| margin-top: 0.5rem; | |
| } | |
| </style> | |
| """, unsafe_allow_html=True) | |
| st.title("CC MACHINE LEARNING DANS LE CLOUD") | |
| st.subheader("\U0001F4CA Application d'Analyse de Risque de mortalité: Utilisant PyCaret") | |
| # Sidebar avec navigation | |
| st.sidebar.image("keyce_logo.jpeg", width=200, caption="Keyce informatique et IA") | |
| if "page" not in st.session_state: | |
| st.session_state.page = "\U0001F3E0 Accueil" | |
| if st.sidebar.button("\U0001F3E0 Accueil"): | |
| st.session_state.page = "\U0001F3E0 Accueil" | |
| if st.sidebar.button("\U0001F4CA Analyse exploratoire"): | |
| st.session_state.page = "\U0001F4CA Analyse exploratoire" | |
| if st.sidebar.button("\U0001F6E0️ Prétraitement"): | |
| st.session_state.page = "\U0001F6E0️ Prétraitement" | |
| if st.sidebar.button("⚖️ Comparaison des modèles"): | |
| st.session_state.page = "⚖️ Comparaison des modèles" | |
| if st.sidebar.button("\U0001F4C8 Évaluation du modèle"): | |
| st.session_state.page = "\U0001F4C8 Évaluation du modèle" | |
| if st.sidebar.button("\U0001F4BE Export du modèle"): | |
| st.session_state.page = "\U0001F4BE Export du modèle" | |
| page = st.session_state.page | |
| # Vérification de la colonne cible | |
| if "Risk" not in data.columns: | |
| st.error("La colonne cible 'Risk' est absente du fichier.") | |
| else: | |
| if page == "\U0001F3E0 Accueil": | |
| st.header("Objectif de l'analyse") | |
| st.markdown(""" | |
| Cette application vise à analyser et classifier les données en fonction du **niveau de risque (`Risk`) de mortalite**. | |
| Elle est conçue pour aider à identifier rapidement les facteurs influents et évaluer les performances | |
| de différents modèles de Machine Learning sur un jeu de données. | |
| """) | |
| st.header("Aperçu des données") | |
| st.write(data.head()) | |
| tab_l, tab_c = st.tabs(["Nombre de lignes", "Nombre de colonnes(features)"]) | |
| with tab_l: | |
| st.metric("Nombre de lignes",data.shape[0]) | |
| with tab_c: | |
| st.metric("Nombre de colonnes(features)",data.shape[1]) | |
| if page == "\U0001F4CA Analyse exploratoire": | |
| st.header("Analyse exploratoire") | |
| tab_desc, tab_dist, tab_hist, tab_box, tab_corr = st.tabs([ | |
| "Statistiques descriptives", "Distribution de la cible", | |
| "Histogrammes", "Boxplots par classe de risque", "Corrélations"]) | |
| with tab_desc: | |
| st.subheader("Statistiques descriptives") | |
| st.write(data.describe(include='all')) | |
| with tab_dist: | |
| st.subheader("Distribution de la variable cible") | |
| fig = px.histogram(data, x='Risk', title="Distribution de la variable cible", color='Risk', color_discrete_sequence=px.colors.qualitative.Set1) | |
| st.plotly_chart(fig, use_container_width=True) | |
| with tab_hist: | |
| st.subheader("Histogrammes des variables numériques") | |
| num_cols = data.select_dtypes(include='number').columns.tolist() | |
| hist_col = st.selectbox("Choisir une colonne:", num_cols, key="hist_col") | |
| if hist_col: | |
| fig = px.histogram(data, x=hist_col, title=f"Distribution de {hist_col}", color='Risk', barmode='overlay', color_discrete_sequence=px.colors.qualitative.Set2) | |
| st.plotly_chart(fig, use_container_width=True) | |
| with tab_box: | |
| st.subheader("Boxplots par classe de risque") | |
| box_col = st.selectbox("Choisir une colonne:", num_cols, key="box_col") | |
| if box_col: | |
| fig = px.box(data, x="Risk", y=box_col, title=f"Répartition de {box_col} selon le risque", color="Risk", color_discrete_sequence=px.colors.qualitative.Set3) | |
| st.plotly_chart(fig, use_container_width=True) | |
| with tab_corr: | |
| st.subheader("Carte de corrélation des variables numériques") | |
| corr = data[num_cols].corr() | |
| fig, ax = plt.subplots(figsize=(10, 6)) | |
| sns.heatmap(corr, annot=True, fmt=".2f", cmap='coolwarm', ax=ax) | |
| st.pyplot(fig) | |
| if page == "\U0001F6E0️ Prétraitement": | |
| st.header("Prétraitement automatique avec PyCaret") | |
| with st.spinner("Initialisation en cours..."): | |
| clf_setup = setup(data=data, target='Risk', session_id=123, verbose=False) | |
| setup_df = pull() | |
| st.write("Configuration PyCaret :") | |
| st.dataframe(setup_df) | |
| if page == "⚖️ Comparaison des modèles": | |
| st.header("Comparaison des modèles") | |
| with st.spinner("Comparaison en cours..."): | |
| best_model = compare_models() | |
| compare_df = pull() | |
| st.write("Résultats de la comparaison :") | |
| st.dataframe(compare_df) | |
| st.session_state["best_model"] = best_model | |
| if page == "\U0001F4C8 Évaluation du modèle": | |
| st.header("4. Évaluation du modèle") | |
| if "best_model" in st.session_state: | |
| final_model = finalize_model(st.session_state["best_model"]) | |
| st.session_state["final_model"] = final_model | |
| tab_feat, tab_conf, tab_roc, tab_pred = st.tabs([ | |
| "Importances des variables", "Matrice de confusion", "Courbe ROC", "Prédictions"]) | |
| with tab_feat: | |
| st.subheader("Importances des variables") | |
| try: | |
| plot_model(final_model, plot='feature', save=True) | |
| st.image("Feature Importance.png", width=600) | |
| os.remove("Feature Importance.png") | |
| except Exception as e: | |
| st.error(f"Erreur lors de l'affichage : {e}") | |
| with tab_conf: | |
| st.subheader("Matrice de confusion") | |
| try: | |
| plot_model(final_model, plot='confusion_matrix', save=True) | |
| st.image("Confusion Matrix.png", width=500) | |
| os.remove("Confusion Matrix.png") | |
| except Exception as e: | |
| st.error(f"Erreur lors de l'affichage : {e}") | |
| with tab_roc: | |
| st.subheader("Courbe ROC") | |
| try: | |
| plot_model(final_model, plot='auc', save=True) | |
| st.image("AUC.png", width=500) | |
| os.remove("AUC.png") | |
| except Exception as e: | |
| st.error(f"Erreur lors de l'affichage : {e}") | |
| with tab_pred: | |
| st.subheader("Prédictions sur les données") | |
| predictions = predict_model(final_model, data=data) | |
| st.write(predictions[['Risk', 'prediction_label', 'prediction_score']]) | |
| else: | |
| st.warning("Veuillez d'abord comparer les modèles.") | |
| if page == "\U0001F4BE Export du modèle": | |
| st.header("5. Export du modèle") | |
| if "final_model" in st.session_state: | |
| save_model(st.session_state["final_model"], 'best_risk_model') | |
| with open('best_risk_model.pkl', 'rb') as f: | |
| st.download_button("🔹 Télécharger le modèle PyCaret", f, file_name="best_risk_model.pkl") | |
| else: | |
| st.warning("Veuillez d'abord évaluer un modèle.") | |