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:
@@ -6,12 +6,13 @@ 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.manifold import TSNE
|
||||
from sklearn.cluster import KMeans
|
||||
import matplotlib.pyplot as plt
|
||||
import pandas as pd
|
||||
import torch.nn.functional as F
|
||||
|
||||
# 0. REPRODUCIBILITY
|
||||
def set_seed(seed=42):
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
@@ -24,35 +25,54 @@ def set_seed(seed=42):
|
||||
|
||||
set_seed(42)
|
||||
|
||||
# 1. CONFIGURACIÓN
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
|
||||
ENCODER_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
|
||||
N_CLUSTERS = 10
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
TARGET_K = 10 # Enforce your target 10 metabolic domains
|
||||
|
||||
class MSI_Structural_Encoder(nn.Module):
|
||||
def __init__(self):
|
||||
super(MSI_Structural_Encoder, self).__init__()
|
||||
# Matches the high-fidelity GroupNorm architecture
|
||||
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):
|
||||
h = self.features(x).squeeze(-1).squeeze(-1)
|
||||
return h
|
||||
|
||||
# 2. CARGAR EL MODELO ENTRENADO
|
||||
def load_trained_encoder(path):
|
||||
if not os.path.exists(path):
|
||||
raise FileNotFoundError(f"No se encontró el modelo en {path}")
|
||||
raise FileNotFoundError(f"Missing model checkpoint: {path}")
|
||||
|
||||
model = models.efficientnet_b0()
|
||||
model.classifier = nn.Identity()
|
||||
|
||||
state_dict = torch.load(path, map_location=DEVICE)
|
||||
model.load_state_dict(state_dict)
|
||||
model = MSI_Structural_Encoder()
|
||||
# Loading only the feature extractor weights
|
||||
model.features.load_state_dict(torch.load(path, map_location=DEVICE))
|
||||
model.to(DEVICE)
|
||||
model.eval()
|
||||
return model
|
||||
|
||||
# 3. DATASET PARA INFERENCIA
|
||||
class MSIDatasetInference(Dataset):
|
||||
def __init__(self, img_dir):
|
||||
self.img_dir = img_dir
|
||||
self.img_names = sorted([f for f in os.listdir(img_dir) if f.endswith('.png')])
|
||||
self.transform = transforms.Compose([
|
||||
transforms.Resize((224, 224)),
|
||||
transforms.ToTensor(),
|
||||
transforms.Resize((256, 256)),
|
||||
transforms.ToTensor()
|
||||
])
|
||||
|
||||
def __len__(self):
|
||||
@@ -60,64 +80,73 @@ class MSIDatasetInference(Dataset):
|
||||
|
||||
def __getitem__(self, idx):
|
||||
img_path = os.path.join(self.img_dir, self.img_names[idx])
|
||||
image = Image.open(img_path).convert("RGB")
|
||||
image = Image.open(img_path).convert("L")
|
||||
return self.transform(image), self.img_names[idx]
|
||||
|
||||
# --- PROCESO ---
|
||||
if __name__ == "__main__":
|
||||
print("Extrayendo características con el encoder...")
|
||||
try:
|
||||
encoder = load_trained_encoder(ENCODER_PATH)
|
||||
except Exception as e:
|
||||
print(f"Error al cargar el modelo: {e}")
|
||||
exit(1)
|
||||
|
||||
print("Loading specialized custom MSI Structural Encoder...")
|
||||
encoder = load_trained_encoder(ENCODER_PATH)
|
||||
dataset = MSIDatasetInference(IMG_DIR)
|
||||
if len(dataset) == 0:
|
||||
print(f"No se encontraron imágenes en {IMG_DIR}")
|
||||
exit(1)
|
||||
|
||||
loader = DataLoader(dataset, batch_size=1, shuffle=False)
|
||||
|
||||
features = []
|
||||
ion_names = []
|
||||
|
||||
print("Extracting and L2-normalizing features from custom manifold...")
|
||||
with torch.no_grad():
|
||||
for img, name in loader:
|
||||
img = img.to(DEVICE)
|
||||
feat = encoder(img)
|
||||
# Normalización L2
|
||||
feat = feat / feat.norm(p=2, dim=1, keepdim=True)
|
||||
# Re-enforce unit hypersphere mapping
|
||||
feat = F.normalize(feat, p=2, dim=1)
|
||||
features.append(feat.cpu().numpy().flatten())
|
||||
ion_names.append(name[0])
|
||||
|
||||
features = np.array(features)
|
||||
|
||||
# 4. CLUSTERING K-MEANS
|
||||
print(f"Realizando KMeans con {N_CLUSTERS} clusters...")
|
||||
km = KMeans(n_clusters=N_CLUSTERS, n_init=20, random_state=42)
|
||||
labels = km.fit_predict(features)
|
||||
# Dimensionality Reduction Optimization
|
||||
pca_km = PCA(n_components=min(50, len(features)), random_state=42)
|
||||
features_pca_all = pca_km.fit_transform(features)
|
||||
|
||||
# 5. VISUALIZACIÓN t-SNE CORREGIDA
|
||||
print("Generando visualización t-SNE con escala corregida...")
|
||||
tsne = TSNE(n_components=2, perplexity=30, random_state=42)
|
||||
embeddings_2d = tsne.fit_transform(features)
|
||||
# FIX: Slice out the first principal component (index 0)
|
||||
# if it continues to hold the global brightness/intensity bias
|
||||
features_pca_km = features_pca_all[:, 1:]
|
||||
|
||||
# ENFORCE EXACTLY 10 METABOLIC DOMAINS
|
||||
print(f"Executing K-Means clustering strictly constrained to K={TARGET_K}...")
|
||||
clusterer = KMeans(n_clusters=TARGET_K, init='k-means++', n_init=20, random_state=42)
|
||||
labels = clusterer.fit_predict(features_pca_km)
|
||||
|
||||
# MANIFOLD PROJECTION ADJUSTMENT
|
||||
print("Projecting t-SNE map...")
|
||||
tsne = TSNE(
|
||||
n_components=2,
|
||||
perplexity=15, # Reduced from 25 to force local structural groupings
|
||||
early_exaggeration=12.0, # Adjusted to optimize structural separation distance
|
||||
learning_rate='auto',
|
||||
init='pca', # Changed from 'random' to preserve global cluster seed stability
|
||||
random_state=42
|
||||
)
|
||||
embeddings_2d = tsne.fit_transform(features_pca_km)
|
||||
|
||||
# Plotting
|
||||
plt.figure(figsize=(10, 8))
|
||||
# Aplicando tu corrección específica:
|
||||
scatter = plt.scatter(embeddings_2d[:, 0], embeddings_2d[:, 1], c=labels, cmap='tab10', alpha=0.8, edgecolors='w', s=50)
|
||||
scatter = plt.scatter(embeddings_2d[:, 0], embeddings_2d[:, 1], c=labels, cmap='tab10', alpha=0.9, edgecolors='none', s=45)
|
||||
cbar = plt.colorbar(scatter, ticks=range(TARGET_K))
|
||||
cbar.set_label('Metabolic Domain ID (K=10)')
|
||||
|
||||
# Configuración de la barra de colores con los ticks exactos para 10 clusters
|
||||
cbar = plt.colorbar(scatter, ticks=range(N_CLUSTERS))
|
||||
cbar.set_label('Cluster ID')
|
||||
plt.title("Objectively Segmented Leaf Manifold (Custom Encoder)")
|
||||
plt.xlabel("t-SNE Dimension 1")
|
||||
plt.ylabel("t-SNE Dimension 2")
|
||||
plt.grid(True, linestyle='--', alpha=0.3)
|
||||
|
||||
plt.title(f"t-SNE Visualization of MSI Ions (K={N_CLUSTERS})")
|
||||
plt.xlabel("t-SNE dimension 1")
|
||||
plt.ylabel("t-SNE dimension 2")
|
||||
plt.grid(True, linestyle='--', alpha=0.5)
|
||||
plt.savefig(os.path.join(BASE_DIR, "..", "msi_tsne_corregido.png"), dpi=300, bbox_inches='tight')
|
||||
plt.close()
|
||||
|
||||
# Save outputs
|
||||
print("Exporting synchronized cluster assignments...")
|
||||
df_results = pd.DataFrame({'ion_image': ion_names, 'cluster': labels})
|
||||
df_results['mz'] = df_results['ion_image'].str.extract(r'(\d+\.\d+)').astype(float)
|
||||
df_results.to_csv(os.path.join(BASE_DIR, "..", "msi_clusters_results.csv"), index=False)
|
||||
|
||||
output_file = "msi_tsne_corregido.png"
|
||||
plt.savefig(output_file, dpi=300, bbox_inches='tight')
|
||||
# plt.show()
|
||||
|
||||
print(f"Visualización guardada exitosamente en '{output_file}'.")
|
||||
print("Process complete.")
|
||||
|
||||
Reference in New Issue
Block a user