Subir archivos a "scripts_python"
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import os
|
||||
import sys
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torchvision import models, transforms
|
||||
@@ -11,7 +12,6 @@ from sklearn.metrics import silhouette_score, davies_bouldin_score, calinski_har
|
||||
import matplotlib.pyplot as plt
|
||||
import torch.nn.functional as F
|
||||
|
||||
# 0. REPRODUCIBILITY
|
||||
def set_seed(seed=42):
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
@@ -24,12 +24,15 @@ def set_seed(seed=42):
|
||||
|
||||
set_seed(42)
|
||||
|
||||
# CONFIGURATION
|
||||
dataset_name = sys.argv[1] if len(sys.argv) > 1 else "leaf"
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
|
||||
MODEL_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
|
||||
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images", dataset_name)
|
||||
MODEL_PATH = os.path.join(BASE_DIR, "..", "..", "outputs", "models", dataset_name, "msi_encoder_trained.pth")
|
||||
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", dataset_name)
|
||||
FIGURES_DIR = os.path.join(OUTPUT_DIR, "figures")
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
K_RANGE = range(2, 21) # Testing from 2 to 20 clusters
|
||||
K_RANGE = range(2, 21) # overridden per-dataset below to respect small corpora
|
||||
|
||||
class MSI_Structural_Encoder(nn.Module):
|
||||
def __init__(self):
|
||||
@@ -53,11 +56,10 @@ class MSI_Structural_Encoder(nn.Module):
|
||||
def forward(self, x):
|
||||
return self.features(x).squeeze(-1).squeeze(-1)
|
||||
|
||||
# 1. LOAD MODEL AND EXTRACT FEATURES
|
||||
def extract_features():
|
||||
model = MSI_Structural_Encoder()
|
||||
if not os.path.exists(MODEL_PATH):
|
||||
raise FileNotFoundError(f"No se encontró el modelo en {MODEL_PATH}")
|
||||
raise FileNotFoundError(f"Model not found at {MODEL_PATH}")
|
||||
model.features.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
|
||||
model.to(DEVICE)
|
||||
model.eval()
|
||||
@@ -69,9 +71,9 @@ def extract_features():
|
||||
|
||||
features = []
|
||||
if not os.path.exists(IMG_DIR):
|
||||
raise FileNotFoundError(f"No se encontró el directorio de imágenes en {IMG_DIR}")
|
||||
raise FileNotFoundError(f"Image directory not found at {IMG_DIR}")
|
||||
img_names = sorted([f for f in os.listdir(IMG_DIR) if f.endswith('.png')])
|
||||
|
||||
|
||||
print(f"Extracting features from {len(img_names)} images on {DEVICE}...")
|
||||
with torch.no_grad():
|
||||
for i, name in enumerate(img_names):
|
||||
@@ -80,21 +82,24 @@ def extract_features():
|
||||
img = Image.open(img_path).convert("L")
|
||||
img_t = transform(img).unsqueeze(0).to(DEVICE)
|
||||
feat = model(img_t)
|
||||
# CRITICAL FIX: Project explicitly onto the unit hypersphere
|
||||
feat_norm = F.normalize(feat, p=2, dim=1)
|
||||
features.append(feat_norm.cpu().numpy().flatten())
|
||||
|
||||
|
||||
return np.array(features)
|
||||
|
||||
# 2. EVALUATE K-MEANS
|
||||
if __name__ == "__main__":
|
||||
X = extract_features()
|
||||
|
||||
pca = PCA(n_components=min(50, X.shape[1]), random_state=42)
|
||||
|
||||
n_components = max(2, min(50, X.shape[0], X.shape[1]))
|
||||
pca = PCA(n_components=n_components, random_state=42)
|
||||
X_pca = pca.fit_transform(X)
|
||||
# CRITICAL FIX: Re-normalize after PCA to restore unit hypersphere geometry for Spherical K-Means equivalent
|
||||
X_pca = X_pca / np.linalg.norm(X_pca, axis=1, keepdims=True)
|
||||
|
||||
K_RANGE = range(2, min(21, X.shape[0])) # K must be < n_samples for silhouette
|
||||
if K_RANGE.stop - K_RANGE.start < 2:
|
||||
print("Too few ions to evaluate clustering (need at least 3).")
|
||||
K_RANGE = range(2, 3)
|
||||
|
||||
inertias = []
|
||||
silhouettes = []
|
||||
davies_bouldin = []
|
||||
@@ -105,9 +110,8 @@ if __name__ == "__main__":
|
||||
print(f"Calculating for K={k}...")
|
||||
kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
|
||||
labels = kmeans.fit_predict(X_pca)
|
||||
|
||||
|
||||
inertias.append(kmeans.inertia_)
|
||||
# CRITICAL FIX: Evaluate using cosine distance on the un-reduced features
|
||||
silhouettes.append(silhouette_score(X, labels, metric='cosine'))
|
||||
davies_bouldin.append(davies_bouldin_score(X_pca, labels))
|
||||
calinski_harabasz.append(calinski_harabasz_score(X_pca, labels))
|
||||
@@ -139,18 +143,40 @@ if __name__ == "__main__":
|
||||
ax4.grid(True)
|
||||
|
||||
plt.tight_layout()
|
||||
output_plot = os.path.join(BASE_DIR, "..", "figures", "cluster_validation_detailed_plot.png")
|
||||
os.makedirs(os.path.dirname(output_plot), exist_ok=True)
|
||||
plt.savefig(output_plot)
|
||||
print(f"Plot saved as '{output_plot}'")
|
||||
os.makedirs(FIGURES_DIR, exist_ok=True)
|
||||
output_plot = os.path.join(FIGURES_DIR, "cluster_validation_detailed_plot.png")
|
||||
plt.savefig(output_plot, dpi=300, bbox_inches="tight")
|
||||
print(f"Plot saved: {output_plot}")
|
||||
|
||||
idx_10 = list(K_RANGE).index(10)
|
||||
print(f"\n--- RESULTS FOR 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}")
|
||||
|
||||
print(f"\n--- MATHEMATICAL SUGGESTIONS ---")
|
||||
print(f"Best K (Silhouette): {K_RANGE[np.argmax(silhouettes)]}")
|
||||
print(f"Best K (Davies-Bouldin): {K_RANGE[np.argmin(davies_bouldin)]}")
|
||||
print(f"Best K (Calinski-Harabasz): {K_RANGE[np.argmax(calinski_harabasz)]}")
|
||||
best_k_sil = K_RANGE[np.argmax(silhouettes)]
|
||||
best_k_db = K_RANGE[np.argmin(davies_bouldin)]
|
||||
best_k_ch = K_RANGE[np.argmax(calinski_harabasz)]
|
||||
|
||||
print(f"\n--- RESULTS FOR {dataset_name.upper()} ---")
|
||||
print(f"Best K (Silhouette): {best_k_sil}")
|
||||
print(f"Best K (Davies-Bouldin): {best_k_db}")
|
||||
print(f"Best K (Calinski-Harabasz):{best_k_ch}")
|
||||
|
||||
# Save results CSV
|
||||
import csv
|
||||
results_path = os.path.join(OUTPUT_DIR, "best_k_results.csv")
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||
with open(results_path, 'w', newline='') as f:
|
||||
w = csv.writer(f)
|
||||
w.writerow(['metric', 'value'])
|
||||
w.writerow(['best_k_silhouette', best_k_sil])
|
||||
w.writerow(['best_k_davies_bouldin', best_k_db])
|
||||
w.writerow(['best_k_calinski_harabasz', best_k_ch])
|
||||
w.writerow(['silhouette_score_k10', silhouettes[list(K_RANGE).index(10)]])
|
||||
w.writerow(['davies_bouldin_k10', davies_bouldin[list(K_RANGE).index(10)]])
|
||||
w.writerow(['calinski_harabasz_k10', calinski_harabasz[list(K_RANGE).index(10)]])
|
||||
|
||||
# Save per-K scores as CSV
|
||||
scores_path = os.path.join(OUTPUT_DIR, "clustering_scores.csv")
|
||||
with open(scores_path, 'w', newline='') as f:
|
||||
w = csv.writer(f)
|
||||
w.writerow(['k', 'silhouette', 'davies_bouldin', 'calinski_harabasz'])
|
||||
for i, k in enumerate(K_RANGE):
|
||||
w.writerow([k, silhouettes[i], davies_bouldin[i], calinski_harabasz[i]])
|
||||
print(f"Results saved to: {results_path}")
|
||||
print(f"Scores saved to: {scores_path}")
|
||||
|
||||
Reference in New Issue
Block a user