import os import sys import torch import torch.nn as nn from torchvision import models, transforms from PIL import Image import numpy as np import random 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 import torch.nn.functional as F def set_seed(seed=42): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False set_seed(42) 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, "..", "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) # overridden per-dataset below to respect small corpora class MSI_Structural_Encoder(nn.Module): def __init__(self): super(MSI_Structural_Encoder, self).__init__() self.features = nn.Sequential( nn.Conv2d(1, 32, kernel_size=5, stride=2, padding=2, bias=False), nn.GroupNorm(4, 32), nn.ReLU(), nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False), nn.GroupNorm(8, 64), nn.ReLU(), nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False), nn.GroupNorm(16, 128), nn.ReLU(), nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1, bias=False), nn.GroupNorm(32, 256), nn.ReLU(), nn.AdaptiveAvgPool2d((1, 1)) ) def forward(self, x): return self.features(x).squeeze(-1).squeeze(-1) def extract_features(): model = MSI_Structural_Encoder() if not os.path.exists(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() transform = transforms.Compose([ transforms.Resize((256, 256)), transforms.ToTensor(), ]) features = [] if not os.path.exists(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): if i % 100 == 0: print(f"Processing image {i}/{len(img_names)}...") img_path = os.path.join(IMG_DIR, name) img = Image.open(img_path).convert("L") img_t = transform(img).unsqueeze(0).to(DEVICE) feat = model(img_t) feat_norm = F.normalize(feat, p=2, dim=1) features.append(feat_norm.cpu().numpy().flatten()) return np.array(features) if __name__ == "__main__": X = extract_features() 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) 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 = [] calinski_harabasz = [] print("Evaluating different K values...") for k in K_RANGE: 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_) 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)) fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 10)) 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) 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) 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) 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() 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}") 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}")