Last active
April 7, 2025 14:45
-
-
Save hdary85/a3ec41fb1f171ba272512c5cb05f31a1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sklearn.ensemble import IsolationForest | |
from sklearn.cluster import DBSCAN | |
from sklearn.neighbors import LocalOutlierFactor | |
from sklearn.covariance import EllipticEnvelope | |
from sklearn.svm import OneClassSVM | |
from sklearn.decomposition import PCA | |
from sklearn.preprocessing import StandardScaler | |
import matplotlib.pyplot as plt | |
import seaborn as sns | |
# --- Préparation des données --- | |
X = df_merged[features_cols].copy() | |
scaler = StandardScaler() | |
X_scaled = scaler.fit_transform(X) | |
# --- PCA pour visualisation --- | |
pca = PCA(n_components=2) | |
X_pca = pca.fit_transform(X_scaled) | |
df_vis = pd.DataFrame(X_pca, columns=['pca1', 'pca2']) | |
# --- Dictionnaire des méthodes à tester --- | |
models = { | |
"Isolation Forest": IsolationForest(contamination=0.05, random_state=42), | |
"One-Class SVM": OneClassSVM(nu=0.05, kernel="rbf", gamma='scale'), | |
"Local Outlier Factor": LocalOutlierFactor(n_neighbors=20, contamination=0.05), | |
"Elliptic Envelope": EllipticEnvelope(contamination=0.05, random_state=42), | |
"DBSCAN": DBSCAN(eps=0.5, min_samples=5) | |
} | |
# --- Boucle sur les modèles --- | |
for name, model in models.items(): | |
try: | |
# --- Prédiction --- | |
if name == "Local Outlier Factor": | |
y_pred = model.fit_predict(X_scaled) | |
elif name == "DBSCAN": | |
y_pred = model.fit_predict(X_scaled) | |
else: | |
model.fit(X_scaled) | |
y_pred = model.predict(X_scaled) | |
# --- Marquage des anomalies --- | |
anomalies = (y_pred == -1).astype(int) | |
df_vis[f"{name}_anomaly"] = anomalies | |
# --- Visualisation --- | |
plt.figure(figsize=(9, 6)) | |
sns.scatterplot( | |
x='pca1', | |
y='pca2', | |
hue=df_vis[f"{name}_anomaly"], | |
palette={0: 'blue', 1: 'red'}, | |
data=df_vis, | |
alpha=0.6 | |
) | |
plt.title(f"📊 {name} - Détection d'anomalies (projection PCA)") | |
plt.xlabel("Composante principale 1") | |
plt.ylabel("Composante principale 2") | |
plt.legend(title='Anomalie', labels=['Normal', 'Suspect']) | |
plt.grid(True) | |
plt.show() | |
except Exception as e: | |
print(f"⚠️ Erreur avec le modèle {name} : {e}") | |
# --- Résumé du nombre d'anomalies par méthode --- | |
anomaly_summary = {} | |
for name in models.keys(): | |
col_name = f"{name}_anomaly" | |
if col_name in df_vis.columns: | |
anomaly_count = df_vis[col_name].sum() | |
anomaly_summary[name] = anomaly_count | |
# Affichage du résumé | |
print("\n📊 Nombre d'anomalies détectées par méthode :") | |
for method, count in anomaly_summary.items(): | |
print(f"- {method}: {count} anomalies") | |
# --- Sélection de la méthode la plus conservatrice (moins d'anomalies) --- | |
best_method = min(anomaly_summary, key=anomaly_summary.get) | |
print(f"\n✅ La méthode la plus conservatrice est : **{best_method}** avec {anomaly_summary[best_method]} anomalies détectées.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment