altered CNN, encoder and loss function to achieve better stability, and fixed morphing of the images lower than the desired resolution
This commit is contained in:
@@ -9,6 +9,7 @@ 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
|
||||
|
||||
# 0. REPRODUCIBILITY
|
||||
def set_seed(seed=42):
|
||||
@@ -27,23 +28,42 @@ set_seed(42)
|
||||
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")
|
||||
# ENABLE CUDA IF AVAILABLE
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
K_RANGE = range(2, 21) # Testing from 2 to 20 clusters
|
||||
|
||||
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)
|
||||
|
||||
# 1. LOAD MODEL AND EXTRACT FEATURES
|
||||
def extract_features():
|
||||
# Load the trained encoder
|
||||
model = models.efficientnet_b0()
|
||||
model.classifier = nn.Identity()
|
||||
model = MSI_Structural_Encoder()
|
||||
if not os.path.exists(MODEL_PATH):
|
||||
raise FileNotFoundError(f"No se encontró el modelo en {MODEL_PATH}")
|
||||
model.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
|
||||
model.features.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
|
||||
model.to(DEVICE)
|
||||
model.eval()
|
||||
|
||||
transform = transforms.Compose([
|
||||
transforms.Resize((224, 224)),
|
||||
transforms.Resize((256, 256)),
|
||||
transforms.ToTensor(),
|
||||
])
|
||||
|
||||
@@ -57,10 +77,12 @@ def extract_features():
|
||||
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("RGB")
|
||||
img = Image.open(img_path).convert("L")
|
||||
img_t = transform(img).unsqueeze(0).to(DEVICE)
|
||||
feat = model(img_t).cpu().numpy().flatten()
|
||||
features.append(feat)
|
||||
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)
|
||||
|
||||
@@ -68,10 +90,7 @@ def extract_features():
|
||||
if __name__ == "__main__":
|
||||
X = extract_features()
|
||||
|
||||
# Dimensionality reduction (PCA) for stability.
|
||||
# Reducing to 50 components is a heuristic to remove noise and redundant dimensions
|
||||
# while preserving structural anatomical features (Jolliffe, 2002).
|
||||
pca = PCA(n_components=50, random_state=42)
|
||||
pca = PCA(n_components=min(50, X.shape[1]), random_state=42)
|
||||
X_pca = pca.fit_transform(X)
|
||||
|
||||
inertias = []
|
||||
@@ -82,8 +101,6 @@ if __name__ == "__main__":
|
||||
print("Evaluating different K values...")
|
||||
for k in K_RANGE:
|
||||
print(f"Calculating for K={k}...")
|
||||
# Standard scikit-learn k-means with fixed seed for reproducibility.
|
||||
# n_init=10 ensures robust initialization.
|
||||
kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
|
||||
labels = kmeans.fit_predict(X_pca)
|
||||
|
||||
@@ -92,31 +109,26 @@ if __name__ == "__main__":
|
||||
davies_bouldin.append(davies_bouldin_score(X_pca, labels))
|
||||
calinski_harabasz.append(calinski_harabasz_score(X_pca, labels))
|
||||
|
||||
# 3. PLOT RESULTS (Multiple metrics)
|
||||
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 10))
|
||||
|
||||
# Elbow (Inertia)
|
||||
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)')
|
||||
@@ -129,14 +141,12 @@ if __name__ == "__main__":
|
||||
plt.savefig(output_plot)
|
||||
print(f"Plot saved as '{output_plot}'")
|
||||
|
||||
# Results report for K=10
|
||||
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}")
|
||||
|
||||
# Suggested K by each metric
|
||||
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)]}")
|
||||
|
||||
Reference in New Issue
Block a user