Spaces:
Runtime error
Runtime error
add functions
Browse files
utils.py
CHANGED
|
@@ -61,4 +61,40 @@ def extract_features(image_paths):
|
|
| 61 |
# Dans ce cas, nous utilisons les logits comme vecteur de caractéristiques.
|
| 62 |
feature_vector = outputs.logits.cpu().numpy()
|
| 63 |
features.append(feature_vector)
|
| 64 |
-
return np.vstack(features)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
# Dans ce cas, nous utilisons les logits comme vecteur de caractéristiques.
|
| 62 |
feature_vector = outputs.logits.cpu().numpy()
|
| 63 |
features.append(feature_vector)
|
| 64 |
+
return np.vstack(features)
|
| 65 |
+
|
| 66 |
+
def adaptive_threshold(anomaly_scores):
|
| 67 |
+
"""
|
| 68 |
+
Calcule un seuil adaptatif en utilisant la méthode IQR.
|
| 69 |
+
"""
|
| 70 |
+
Q1 = np.percentile(anomaly_scores, 25)
|
| 71 |
+
Q3 = np.percentile(anomaly_scores, 75)
|
| 72 |
+
IQR = Q3 - Q1
|
| 73 |
+
threshold = Q3 + 1.5 * IQR # Ajuster le facteur 1.5 si besoin
|
| 74 |
+
return threshold
|
| 75 |
+
|
| 76 |
+
def analyze_image(image_path, all_features_for_threshold):
|
| 77 |
+
"""
|
| 78 |
+
Analyse une image et détermine si elle est une anomalie.
|
| 79 |
+
"""
|
| 80 |
+
# Extraire les caractéristiques de l'image
|
| 81 |
+
features = extract_features([image_path])
|
| 82 |
+
|
| 83 |
+
# Appliquer la transformation PCA
|
| 84 |
+
pca = joblib.load("pca_transformer.pkl")
|
| 85 |
+
features_reduced = pca.transform(features)
|
| 86 |
+
|
| 87 |
+
# Prédire le score d'anomalie
|
| 88 |
+
anomaly_detector = joblib.load("anomaly_detector.pkl")
|
| 89 |
+
anomaly_score = anomaly_detector.decision_function(features_reduced)[0]
|
| 90 |
+
|
| 91 |
+
# Calculer le seuil adaptatif pour l'ensemble d'entraînement
|
| 92 |
+
threshold = adaptive_threshold(all_features_for_threshold)
|
| 93 |
+
|
| 94 |
+
# Déterminer si l'image est une anomalie
|
| 95 |
+
if anomaly_score < threshold:
|
| 96 |
+
result = "Anomalie"
|
| 97 |
+
else:
|
| 98 |
+
result = "Normale"
|
| 99 |
+
|
| 100 |
+
return result, anomaly_score
|