diff --git a/evaluate_clustering.py b/evaluate_clustering.py new file mode 100644 index 0000000..158c0e9 --- /dev/null +++ b/evaluate_clustering.py @@ -0,0 +1,116 @@ +import os +import torch +import torch.nn as nn +from torchvision import models, transforms +from PIL import Image +import numpy as np +from sklearn.cluster import KMeans +from sklearn.decomposition import PCA +from sklearn.metrics import silhouette_score, davies_bouldin_score, calinski_harabasz_score +import matplotlib.pyplot as plt + +# CONFIGURACIÓN +IMG_DIR = "datos_para_ai" +MODEL_PATH = "Model/msi_encoder_trained.pth" +DEVICE = torch.device("cpu") # Forzado a CPU +K_RANGE = range(2, 21) # Probaremos de 2 a 20 clusters + +# 1. CARGAR MODELO Y EXTRAER CARACTERÍSTICAS +def extract_features(): + # Cargar el encoder entrenado + model = models.efficientnet_b0() + model.classifier = nn.Identity() + model.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE)) + model.eval() + + transform = transforms.Compose([ + transforms.Resize((224, 224)), + transforms.ToTensor(), + ]) + + features = [] + img_names = sorted([f for f in os.listdir(IMG_DIR) if f.endswith('.png')]) + + print(f"Extrayendo características de {len(img_names)} imágenes...") + with torch.no_grad(): + for i, name in enumerate(img_names): + if i % 100 == 0: print(f"Procesando imagen {i}/{len(img_names)}...") + img_path = os.path.join(IMG_DIR, name) + img = Image.open(img_path).convert("RGB") + img_t = transform(img).unsqueeze(0).to(DEVICE) + feat = model(img_t).cpu().numpy().flatten() + features.append(feat) + + return np.array(features) + +# 2. EVALUAR K-MEANS +if __name__ == "__main__": + X = extract_features() + + # Reducción de dimensionalidad (PCA) para estabilizar + pca = PCA(n_components=50) + X_pca = pca.fit_transform(X) + + inertias = [] + silhouettes = [] + davies_bouldin = [] + calinski_harabasz = [] + + print("Evaluando diferentes valores de K...") + for k in K_RANGE: + print(f"Calculando para K={k}...") + kmeans = KMeans(n_clusters=k, random_state=42, n_init=10) + labels = kmeans.fit_predict(X_pca) + + inertias.append(kmeans.inertia_) + silhouettes.append(silhouette_score(X_pca, labels)) + davies_bouldin.append(davies_bouldin_score(X_pca, labels)) + calinski_harabasz.append(calinski_harabasz_score(X_pca, labels)) + + # 3. GRAFICAR RESULTADOS (Múltiples métricas en Inglés) + fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 10)) + + # Elbow (Inercia) + ax1.plot(K_RANGE, inertias, 'o-', color='tab:red') + ax1.set_title('Elbow Method (Inertia)') + ax1.set_xlabel('Number of Clusters (k)') + ax1.set_ylabel('Sum of Squared Errors') + ax1.grid(True) + + # Silhouette + ax2.plot(K_RANGE, silhouettes, 's-', color='tab:blue') + ax2.set_title('Silhouette Score (Higher is better)') + ax2.set_xlabel('Number of Clusters (k)') + ax2.set_ylabel('Score') + ax2.grid(True) + + # Davies-Bouldin + ax3.plot(K_RANGE, davies_bouldin, '^-', color='tab:green') + ax3.set_title('Davies-Bouldin Index (Lower is better)') + ax3.set_xlabel('Number of Clusters (k)') + ax3.set_ylabel('Score') + ax3.grid(True) + + # Calinski-Harabasz + ax4.plot(K_RANGE, calinski_harabasz, 'd-', color='tab:orange') + ax4.set_title('Calinski-Harabasz Index (Higher is better)') + ax4.set_xlabel('Number of Clusters (k)') + ax4.set_ylabel('Score') + ax4.grid(True) + + plt.tight_layout() + plt.savefig('cluster_validation_detailed_plot.png') + print("Plot saved as 'cluster_validation_detailed_plot.png'") + + # Reporte de resultados para K=10 + idx_10 = list(K_RANGE).index(10) + print(f"\n--- RESULTADOS PARA K=10 ---") + print(f"Silhouette Score: {silhouettes[idx_10]:.4f}") + print(f"Davies-Bouldin Index: {davies_bouldin[idx_10]:.4f}") + print(f"Calinski-Harabasz Index: {calinski_harabasz[idx_10]:.4f}") + + # K sugerido por cada métrica + print(f"\n--- SUGERENCIAS MATEMÁTICAS ---") + print(f"Mejor K (Silhouette): {K_RANGE[np.argmax(silhouettes)]}") + print(f"Mejor K (Davies-Bouldin): {K_RANGE[np.argmin(davies_bouldin)]}") + print(f"Mejor K (Calinski-Harabasz): {K_RANGE[np.argmax(calinski_harabasz)]}")