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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import seaborn as sns
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import numpy as np
|
| 5 |
+
from sklearn.linear_model import LinearRegression
|
| 6 |
+
import itertools
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
|
| 9 |
+
# ------------------------------
|
| 10 |
+
# Configuration Streamlit
|
| 11 |
+
# ------------------------------
|
| 12 |
+
st.set_page_config(layout="wide")
|
| 13 |
+
|
| 14 |
+
st.sidebar.title("Exploration des corrélations partielles")
|
| 15 |
+
st.sidebar.markdown("---")
|
| 16 |
+
st.sidebar.header("Configuration")
|
| 17 |
+
|
| 18 |
+
# Sélection dataset
|
| 19 |
+
available_datasets = []
|
| 20 |
+
|
| 21 |
+
for name in sns.get_dataset_names():
|
| 22 |
+
try:
|
| 23 |
+
df_test = sns.load_dataset(name).dropna()
|
| 24 |
+
numeric_cols = df_test.select_dtypes(include=['float64', 'int64']).columns
|
| 25 |
+
if len(numeric_cols) >= 3:
|
| 26 |
+
available_datasets.append(name)
|
| 27 |
+
except:
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
dataset_name = st.sidebar.selectbox("Sélectionnez un jeu de données Seaborn :", available_datasets)
|
| 31 |
+
|
| 32 |
+
df = sns.load_dataset(dataset_name).dropna()
|
| 33 |
+
|
| 34 |
+
# Colonnes numériques uniquement
|
| 35 |
+
df_numeric = df.select_dtypes(include=['float64', 'int64'])
|
| 36 |
+
|
| 37 |
+
# Choix Pearson / Spearman
|
| 38 |
+
corr_type = st.sidebar.radio(
|
| 39 |
+
"Type de corrélation :",
|
| 40 |
+
["Pearson", "Spearman"],
|
| 41 |
+
index=0
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
# Choix variables à éliminer
|
| 45 |
+
all_vars = list(df_numeric.columns)
|
| 46 |
+
control_vars = st.sidebar.multiselect(
|
| 47 |
+
"Variables dont vous voulez éliminer l'influence :",
|
| 48 |
+
all_vars
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
# Variables restantes
|
| 52 |
+
vars_remaining = [v for v in all_vars if v not in control_vars]
|
| 53 |
+
|
| 54 |
+
if len(vars_remaining) < 2:
|
| 55 |
+
st.error("Il faut au moins deux variables restantes pour afficher une corrélation.")
|
| 56 |
+
st.stop()
|
| 57 |
+
|
| 58 |
+
# ------------------------------
|
| 59 |
+
# Prétraitement Spearman (si sélectionné)
|
| 60 |
+
# ------------------------------
|
| 61 |
+
if corr_type == "Spearman":
|
| 62 |
+
df_for_corr = df_numeric.rank()
|
| 63 |
+
else:
|
| 64 |
+
df_for_corr = df_numeric.copy()
|
| 65 |
+
|
| 66 |
+
# ------------------------------
|
| 67 |
+
# Matrice brute
|
| 68 |
+
# ------------------------------
|
| 69 |
+
corr_raw = df_for_corr[vars_remaining].corr(method=("spearman" if corr_type=="Spearman" else "pearson"))
|
| 70 |
+
|
| 71 |
+
# ------------------------------
|
| 72 |
+
# Fonction corrélation partielle
|
| 73 |
+
# ------------------------------
|
| 74 |
+
def partial_corr(df, controls):
|
| 75 |
+
vars_to_corr = [v for v in df.columns if v not in controls]
|
| 76 |
+
|
| 77 |
+
partial_corr_matrix = pd.DataFrame(
|
| 78 |
+
np.zeros((len(vars_to_corr), len(vars_to_corr))),
|
| 79 |
+
columns=vars_to_corr,
|
| 80 |
+
index=vars_to_corr
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
for x, y in itertools.product(vars_to_corr, repeat=2):
|
| 84 |
+
if x == y:
|
| 85 |
+
partial_corr_matrix.loc[x, y] = 1.0
|
| 86 |
+
continue
|
| 87 |
+
|
| 88 |
+
X = df[[x]]
|
| 89 |
+
Y = df[[y]]
|
| 90 |
+
|
| 91 |
+
if len(controls) > 0:
|
| 92 |
+
Z = df[controls]
|
| 93 |
+
|
| 94 |
+
model_x = LinearRegression().fit(Z, X)
|
| 95 |
+
X_res = X - model_x.predict(Z)
|
| 96 |
+
|
| 97 |
+
model_y = LinearRegression().fit(Z, Y)
|
| 98 |
+
Y_res = Y - model_y.predict(Z)
|
| 99 |
+
|
| 100 |
+
r = np.corrcoef(X_res.T, Y_res.T)[0, 1]
|
| 101 |
+
else:
|
| 102 |
+
r = df[[x, y]].corr(method=("spearman" if corr_type=="Spearman" else "pearson")).iloc[0, 1]
|
| 103 |
+
|
| 104 |
+
partial_corr_matrix.loc[x, y] = r
|
| 105 |
+
|
| 106 |
+
return partial_corr_matrix
|
| 107 |
+
|
| 108 |
+
# ------------------------------
|
| 109 |
+
# Matrice partielle
|
| 110 |
+
# ------------------------------
|
| 111 |
+
corr_partial = partial_corr(df_for_corr, control_vars)
|
| 112 |
+
|
| 113 |
+
# ------------------------------
|
| 114 |
+
# Calcul des différences
|
| 115 |
+
# ------------------------------
|
| 116 |
+
# Extraire uniquement les paires uniques (triangle supérieur sans diagonale)
|
| 117 |
+
diff_data = []
|
| 118 |
+
n = len(vars_remaining)
|
| 119 |
+
for i in range(n):
|
| 120 |
+
for j in range(i+1, n):
|
| 121 |
+
var1 = vars_remaining[i]
|
| 122 |
+
var2 = vars_remaining[j]
|
| 123 |
+
raw_val = corr_raw.loc[var1, var2]
|
| 124 |
+
partial_val = corr_partial.loc[var1, var2]
|
| 125 |
+
diff = partial_val - raw_val
|
| 126 |
+
diff_data.append({
|
| 127 |
+
'Paire': f"{var1} - {var2}",
|
| 128 |
+
'Différence': diff
|
| 129 |
+
})
|
| 130 |
+
|
| 131 |
+
df_diff = pd.DataFrame(diff_data).sort_values('Différence', ascending=True)
|
| 132 |
+
|
| 133 |
+
# ------------------------------
|
| 134 |
+
# ONGLET PRINCIPAL
|
| 135 |
+
# ------------------------------
|
| 136 |
+
tab1, tab2 = st.tabs(["📊 Matrices", "📄 Données"])
|
| 137 |
+
|
| 138 |
+
# ----------- TAB 1 -----------
|
| 139 |
+
with tab1:
|
| 140 |
+
col1, col2 = st.columns(2)
|
| 141 |
+
|
| 142 |
+
# Heatmap corrélation brute (triangle inférieur)
|
| 143 |
+
with col1:
|
| 144 |
+
st.write(f"**Corrélation brute ({corr_type})**")
|
| 145 |
+
mask_raw = np.triu(np.ones_like(corr_raw, dtype=bool))
|
| 146 |
+
fig, ax = plt.subplots(figsize=(5.5, 4))
|
| 147 |
+
sns.heatmap(corr_raw, annot=True, cmap="coolwarm", center=0, ax=ax,
|
| 148 |
+
mask=mask_raw, square=True, vmin=-1, vmax=1, cbar_kws={'shrink': 0.75}, annot_kws={'size': 9})
|
| 149 |
+
plt.tight_layout()
|
| 150 |
+
st.pyplot(fig)
|
| 151 |
+
|
| 152 |
+
# Heatmap corrélation partielle (triangle inférieur)
|
| 153 |
+
with col2:
|
| 154 |
+
st.write(f"**Corrélation partielle ({corr_type})**")
|
| 155 |
+
mask_partial = np.triu(np.ones_like(corr_partial, dtype=bool))
|
| 156 |
+
fig2, ax2 = plt.subplots(figsize=(5.5, 4))
|
| 157 |
+
sns.heatmap(corr_partial, annot=True, cmap="coolwarm", center=0, ax=ax2,
|
| 158 |
+
mask=mask_partial, square=True, vmin=-1, vmax=1, cbar_kws={'shrink': 0.75}, annot_kws={'size': 9})
|
| 159 |
+
plt.tight_layout()
|
| 160 |
+
st.pyplot(fig2)
|
| 161 |
+
|
| 162 |
+
# Graphique des différences (pleine largeur en dessous)
|
| 163 |
+
st.write("**Différences (Partielle - Brute)**")
|
| 164 |
+
fig3, ax3 = plt.subplots(figsize=(12, 2.2))
|
| 165 |
+
colors = ['#d7191c' if x < 0 else '#2b83ba' for x in df_diff['Différence']]
|
| 166 |
+
ax3.barh(df_diff['Paire'], df_diff['Différence'], color=colors, height=0.55)
|
| 167 |
+
ax3.axvline(0, color='black', linewidth=0.8, linestyle='--')
|
| 168 |
+
ax3.set_xlabel('Différence de corrélation', fontsize=8)
|
| 169 |
+
ax3.tick_params(axis='both', labelsize=7.5)
|
| 170 |
+
ax3.grid(axis='x', alpha=0.3, linestyle=':')
|
| 171 |
+
plt.tight_layout()
|
| 172 |
+
st.pyplot(fig3)
|
| 173 |
+
|
| 174 |
+
st.caption("🔵 Corrélation renforcée après contrôle | 🔴 Corrélation affaiblie après contrôle")
|
| 175 |
+
|
| 176 |
+
# ----------- TAB 2 -----------
|
| 177 |
+
with tab2:
|
| 178 |
+
st.write("**Aperçu des données (10 premières lignes)**")
|
| 179 |
+
st.dataframe(df_numeric.head(10))
|
requirements.txt
CHANGED
|
@@ -1,3 +1,6 @@
|
|
| 1 |
-
|
| 2 |
-
pandas
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit
|
| 2 |
+
pandas
|
| 3 |
+
numpy
|
| 4 |
+
seaborn
|
| 5 |
+
matplotlib
|
| 6 |
+
scikit-learn
|