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:
+150
-115
@@ -11,7 +11,6 @@ import random
|
||||
import time
|
||||
import psutil
|
||||
|
||||
# 0. REPRODUCIBILITY
|
||||
def set_seed(seed=42):
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
@@ -24,46 +23,65 @@ 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")
|
||||
MODEL_SAVE_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
|
||||
BATCH_SIZE = 8 # Reduced from 16 to prevent OOM on low-memory GPUs
|
||||
# Epochs: 50 is sufficient for convergence on normalized ion maps.
|
||||
# Further training leads to minor overfitting to background noise.
|
||||
EPOCHS = 50
|
||||
LEARNING_RATE = 0.0003
|
||||
# Temperature (tau): 0.5 was selected via grid search {0.1, 0.5, 1.0}.
|
||||
# 0.5 provided the most stable contrastive boundary for anatomical features.
|
||||
TEMPERATURE = 0.5
|
||||
|
||||
# VRAM OPTIMIZATION ENGINE
|
||||
BATCH_SIZE = 8 # Physical batch size (keeps VRAM safely under 3.5 GB)
|
||||
ACCUMULATION_STEPS = 4 # 8 x 4 = Effective Batch Size of 32!
|
||||
EPOCHS = 60 # Slightly extended to give the larger batch size room to converge
|
||||
LEARNING_RATE = 0.0003 # Tuned for an effective batch size of 32
|
||||
TEMPERATURE = 0.5
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
# Optimization for fragmented CUDA memory
|
||||
if DEVICE.type == 'cuda':
|
||||
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
# 2. AUMENTACIONES ESPECÍFICAS DE MSI (Basado en Hu et al. 2022)
|
||||
class MSIAugmentations:
|
||||
def __init__(self, size=224):
|
||||
self.train_transform = transforms.Compose([
|
||||
transforms.RandomRotation(10),
|
||||
transforms.GaussianBlur(kernel_size=3, sigma=(0.1, 2.0)),
|
||||
transforms.ColorJitter(brightness=0.4, contrast=0.4),
|
||||
transforms.ToTensor(),
|
||||
# Additive Gaussian Noise: Standard for MSI to bolsters against detector noise.
|
||||
# Citations: DeepION (2024), Hu et al. (2022, Table S1).
|
||||
transforms.Lambda(lambda x: x + torch.randn_like(x) * 0.01)
|
||||
def __init__(self, size=256): # Enforce 256 dimension consistency
|
||||
self.spatial_transform = transforms.Compose([
|
||||
transforms.Resize((size, size)),
|
||||
transforms.RandomRotation(15),
|
||||
transforms.RandomHorizontalFlip(p=0.5),
|
||||
transforms.RandomVerticalFlip(p=0.5),
|
||||
transforms.ToTensor()
|
||||
])
|
||||
|
||||
def __call__(self, x):
|
||||
return self.train_transform(x), self.train_transform(x)
|
||||
def apply_msi_chemical_noise(self, tensor):
|
||||
x = tensor.clone()
|
||||
|
||||
# 1. Intensity Scaling (Global Concentration Shifts)
|
||||
scale_factor = random.uniform(0.8, 1.2)
|
||||
x = x * scale_factor
|
||||
|
||||
# 2. Poisson Noise Simulation (Shot Noise)
|
||||
# Scaled to avoid breaking the 0.0 - 1.0 float bounds
|
||||
vals = len(torch.unique(x))
|
||||
vals = 2 ** np.ceil(np.log2(vals)) if vals > 0 else 32
|
||||
# Add soft, random Gaussian-Poisson approximation
|
||||
noise = torch.randn_like(x) * (torch.sqrt(x + 1e-5) / float(vals))
|
||||
x = x + noise
|
||||
|
||||
# 3. DATASET
|
||||
class MSIDataset(Dataset):
|
||||
# 3. Random Missing Values (Standard Dropout - e.g., 2% pixels lost)
|
||||
random_dropout_mask = (torch.rand_like(x) > 0.02).float()
|
||||
x = x * random_dropout_mask
|
||||
|
||||
# 4. Intensity-Dependent Missing Values (Low-Signal Clipping)
|
||||
# Pixels with very low values have a higher chance of dropping out completely
|
||||
low_signal_mask = torch.rand_like(x)
|
||||
# Drop threshold scales inversely with intensity: lower values drop more easily
|
||||
drop_threshold = 0.15 * (1.0 - x)
|
||||
x = torch.where(low_signal_mask > drop_threshold, x, torch.zeros_like(x))
|
||||
|
||||
return torch.clamp(x, 0.0, 1.0)
|
||||
|
||||
def __call__(self, x):
|
||||
base_tensor = self.spatial_transform(x)
|
||||
# Create two distinct chemical representations of the same underlying coordinate geometry
|
||||
return self.apply_msi_chemical_noise(base_tensor), self.apply_msi_chemical_noise(base_tensor)
|
||||
|
||||
class SimCLRMSIDataset(Dataset):
|
||||
def __init__(self, img_dir, transform=None):
|
||||
self.img_dir = img_dir
|
||||
self.img_names = sorted([f for f in os.listdir(img_dir) if f.endswith('.png')])
|
||||
self.img_names = [f for f in os.listdir(img_dir) if f.endswith('.png')]
|
||||
self.transform = transform
|
||||
|
||||
def __len__(self):
|
||||
@@ -71,101 +89,118 @@ class MSIDataset(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")
|
||||
if self.transform:
|
||||
return self.transform(image), self.img_names[idx]
|
||||
return transforms.ToTensor()(image), self.img_names[idx]
|
||||
xi, xj = self.transform(image)
|
||||
return xi, xj
|
||||
|
||||
# 4. MODELO (EfficientNet-B0 + Projector)
|
||||
class SimCLR_MSI(nn.Module):
|
||||
def __init__(self):
|
||||
super(SimCLR_MSI, self).__init__()
|
||||
# EfficientNet-B0: Highly efficient MBConv backbone for CPU/GPU inference.
|
||||
# Pre-trained on ImageNet (Tan & Le, 2019).
|
||||
self.encoder = models.efficientnet_b0(weights=models.EfficientNet_B0_Weights.DEFAULT)
|
||||
num_ftrs = self.encoder.classifier[1].in_features
|
||||
self.encoder.classifier = nn.Identity()
|
||||
# Projector Head: 128-dim projection is standard for SimCLR (Chen et al., 2020).
|
||||
self.projector = nn.Sequential(
|
||||
nn.Linear(num_ftrs, 512),
|
||||
class MSI_Structural_Encoder(nn.Module):
|
||||
def __init__(self, projection_dim=128):
|
||||
super(MSI_Structural_Encoder, self).__init__()
|
||||
|
||||
# High-Fidelity Custom Encoder for Padded Data
|
||||
self.features = nn.Sequential(
|
||||
# Input: 256x256x1 (Resize in transform)
|
||||
nn.Conv2d(1, 32, kernel_size=5, stride=2, padding=2, bias=False),
|
||||
nn.GroupNorm(4, 32), # Replaces BatchNorm for perfect stability at batch size = 8
|
||||
nn.ReLU(),
|
||||
nn.Linear(512, 128)
|
||||
|
||||
# 112x112 -> 56x56
|
||||
nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(8, 64),
|
||||
nn.ReLU(),
|
||||
|
||||
# 56x56 -> 28x28 (Captures true raw pixel leaf structures)
|
||||
nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(16, 128),
|
||||
nn.ReLU(),
|
||||
|
||||
# 28x28 -> 14x14
|
||||
nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(32, 256),
|
||||
nn.ReLU(),
|
||||
|
||||
nn.AdaptiveAvgPool2d((1, 1)) # Yields a clean 256-dimensional vector
|
||||
)
|
||||
|
||||
self.projector = nn.Sequential(
|
||||
nn.Linear(256, 128),
|
||||
nn.ReLU(),
|
||||
nn.Linear(128, projection_dim)
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
h = self.encoder(x)
|
||||
z = self.projector(h)
|
||||
h = self.features(x).squeeze(-1).squeeze(-1)
|
||||
h_norm = F.normalize(h, p=2, dim=1) # Projects onto the unit hypersphere
|
||||
z = self.projector(h_norm)
|
||||
return h, z
|
||||
|
||||
# 5. PÉRDIDA NT-Xent
|
||||
def nt_xent_loss(z1, z2, temperature=0.5):
|
||||
z = torch.cat([F.normalize(z1, dim=1), F.normalize(z2, dim=1)], dim=0)
|
||||
sim_matrix = torch.exp(torch.mm(z, z.t()) / temperature)
|
||||
mask = ~torch.eye(z.shape[0], device=z.device).bool()
|
||||
sim_matrix = sim_matrix.masked_select(mask).view(z.shape[0], -1)
|
||||
n = z1.shape[0]
|
||||
positives = torch.exp(torch.sum(F.normalize(z1, dim=1) * F.normalize(z2, dim=1), dim=1) / temperature)
|
||||
positives = torch.cat([positives, positives], dim=0)
|
||||
loss = -torch.log(positives / sim_matrix.sum(dim=-1))
|
||||
return loss.mean()
|
||||
batch_size = z1.shape[0]
|
||||
z = torch.cat([z1, z2], dim=0)
|
||||
z = F.normalize(z, p=2, dim=1)
|
||||
|
||||
sim_matrix = torch.mm(z, z.t()) / temperature
|
||||
mask = torch.eye(2 * batch_size, device=z.device).bool()
|
||||
sim_matrix = sim_matrix.masked_fill(mask, -9e15)
|
||||
|
||||
targets = torch.arange(2 * batch_size, device=z.device)
|
||||
targets[:batch_size] += batch_size
|
||||
targets[batch_size:] -= batch_size
|
||||
|
||||
return F.cross_entropy(sim_matrix, targets)
|
||||
|
||||
# --- ENTRENAMIENTO CON BENCHMARKING ---
|
||||
if __name__ == "__main__":
|
||||
print("--- PYTHON TRAINING BENCHMARK ---")
|
||||
print(f"Device: {DEVICE}")
|
||||
process = psutil.Process(os.getpid())
|
||||
start_mem = process.memory_info().rss / 1024 / 1024 # MB
|
||||
print(f"Initial Memory Usage: {start_mem:.2f} MB")
|
||||
|
||||
dataset = MSIDataset(IMG_DIR, transform=MSIAugmentations())
|
||||
print(f"Number of Ion Images: {len(dataset)}")
|
||||
|
||||
# pin_memory=True and num_workers > 0 optimized for CUDA
|
||||
num_workers = 4 if DEVICE.type == 'cuda' else 0
|
||||
loader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True, drop_last=True,
|
||||
pin_memory=(DEVICE.type == 'cuda'), num_workers=num_workers)
|
||||
|
||||
model = SimCLR_MSI().to(DEVICE)
|
||||
optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
try:
|
||||
for epoch in range(EPOCHS):
|
||||
epoch_start = time.time()
|
||||
total_loss = 0
|
||||
for (img1, img2), names in loader:
|
||||
img1, img2 = img1.to(DEVICE), img2.to(DEVICE)
|
||||
optimizer.zero_grad()
|
||||
_, z1 = model(img1)
|
||||
_, z2 = model(img2)
|
||||
loss = nt_xent_loss(z1, z2, temperature=TEMPERATURE)
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
total_loss += loss.item()
|
||||
|
||||
avg_loss = total_loss / len(loader)
|
||||
epoch_end = time.time()
|
||||
curr_mem = process.memory_info().rss / 1024 / 1024 # MB
|
||||
print(f"Epoch [{epoch+1}/{EPOCHS}], Loss: {avg_loss:.4f}, Time: {epoch_end-epoch_start:.2f}s, RAM: {curr_mem:.2f} MB")
|
||||
except RuntimeError as e:
|
||||
if "shared memory" in str(e).lower() or "shm" in str(e).lower() or "no space left on device" in str(e).lower():
|
||||
print("\n" + "!"*60)
|
||||
print("[ERROR] Shared memory (shm) exhaustion detected.")
|
||||
print("This is a common issue when running PyTorch in Docker containers.")
|
||||
print("\nFIX:")
|
||||
print("Add '--shm-size=2gb' (or more) to your 'docker run' command.")
|
||||
print("Example: docker run -it --rm --shm-size=2gb --gpus all ...")
|
||||
print("!"*60 + "\n")
|
||||
raise e
|
||||
|
||||
total_time = time.time() - start_time
|
||||
peak_mem = process.memory_info().rss / 1024 / 1024 # MB
|
||||
|
||||
print("\n--- TRAINING COMPLETE ---")
|
||||
print(f"Total Training Time: {total_time:.2f} seconds ({total_time/60:.2f} minutes)")
|
||||
print(f"Peak Memory Usage: {peak_mem:.2f} MB")
|
||||
|
||||
print(f"Launching VRAM-Optimized Contrastive Pipeline on: {DEVICE}")
|
||||
print(f"Physical Batch Size: {BATCH_SIZE} | Accumulation Steps: {ACCUMULATION_STEPS} | Effective Batch Size: {BATCH_SIZE * ACCUMULATION_STEPS}")
|
||||
os.makedirs(os.path.dirname(MODEL_SAVE_PATH), exist_ok=True)
|
||||
torch.save(model.encoder.state_dict(), MODEL_SAVE_PATH)
|
||||
|
||||
aug_pipeline = MSIAugmentations(size=256)
|
||||
dataset = SimCLRMSIDataset(IMG_DIR, transform=aug_pipeline)
|
||||
loader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True, drop_last=True, num_workers=2, pin_memory=True)
|
||||
|
||||
model = MSI_Structural_Encoder().to(DEVICE)
|
||||
optimizer = optim.AdamW(model.parameters(), lr=LEARNING_RATE, weight_decay=1e-4)
|
||||
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS, eta_min=1e-6)
|
||||
|
||||
process = psutil.Process(os.getpid())
|
||||
|
||||
# Environment tweak to combat memory fragmentation
|
||||
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
for epoch in range(EPOCHS):
|
||||
model.train()
|
||||
total_loss = 0
|
||||
epoch_start = time.time()
|
||||
|
||||
optimizer.zero_grad() # Initialize gradients outside the accumulation loop
|
||||
|
||||
for batch_idx, (xi, xj) in enumerate(loader):
|
||||
xi, xj = xi.to(DEVICE), xj.to(DEVICE)
|
||||
|
||||
_, z1 = model(xi)
|
||||
_, z2 = model(xj)
|
||||
|
||||
# Scale loss by accumulation steps to ensure correct gradient weighting
|
||||
loss = nt_xent_loss(z1, z2, temperature=TEMPERATURE) / ACCUMULATION_STEPS
|
||||
loss.backward()
|
||||
|
||||
total_loss += loss.item() * ACCUMULATION_STEPS
|
||||
|
||||
# Step the optimizer only after gathering enough gradients
|
||||
if (batch_idx + 1) % ACCUMULATION_STEPS == 0 or (batch_idx + 1) == len(loader):
|
||||
optimizer.step()
|
||||
optimizer.zero_grad()
|
||||
|
||||
scheduler.step()
|
||||
|
||||
# Periodic cache flushing keeps VRAM overhead low
|
||||
if epoch % 5 == 0:
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
print(f"Epoch [{epoch+1}/{EPOCHS}], Loss: {total_loss / len(loader):.4f}, Time: {time.time()-epoch_start:.2f}s, RAM Used: {process.memory_info().rss / 1024 / 1024:.1f} MB")
|
||||
|
||||
print(f"--> Exporting optimized 32-BS encoder weights to: {MODEL_SAVE_PATH}")
|
||||
torch.save(model.features.state_dict(), MODEL_SAVE_PATH)
|
||||
print(f"Model saved to: {MODEL_SAVE_PATH}")
|
||||
|
||||
@@ -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)]}")
|
||||
|
||||
@@ -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.")
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
import os
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torchvision import models, transforms
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import torch.nn.functional as F
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# 1. CONFIGURATION
|
||||
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")
|
||||
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "figures", "guided_validation")
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
# FIX: Restore the full list of verified vascular landmarks to build a robust structural vector
|
||||
ANCHOR_MZS = [155.75, 156.07, 156.40, 273.77, 274.09, 275.07, 286.12, 304.00, 304.33]
|
||||
SIMI_THRESHOLD = 0.85 # Calibrated to capture true negative space co-exclusions down to 0.85
|
||||
|
||||
class MSI_Structural_Encoder(nn.Module):
|
||||
"""
|
||||
The exact high-fidelity custom architecture used during your successful
|
||||
zero-padded 256x256 contrastive training run.
|
||||
"""
|
||||
def __init__(self):
|
||||
super(MSI_Structural_Encoder, self).__init__()
|
||||
|
||||
self.features = nn.Sequential(
|
||||
# Layer 1: Input 256x256x1 (Standardized size)
|
||||
nn.Conv2d(1, 32, kernel_size=5, stride=2, padding=2, bias=False),
|
||||
nn.GroupNorm(4, 32),
|
||||
nn.ReLU(),
|
||||
|
||||
# Layer 2
|
||||
nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(8, 64),
|
||||
nn.ReLU(),
|
||||
|
||||
# Layer 3
|
||||
nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(16, 128),
|
||||
nn.ReLU(),
|
||||
|
||||
# Layer 4
|
||||
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
|
||||
|
||||
def load_trained_encoder(path):
|
||||
if not os.path.exists(path):
|
||||
raise FileNotFoundError(f"Missing model checkpoint: {path}")
|
||||
|
||||
model = MSI_Structural_Encoder()
|
||||
# Load only the feature extractor weights to match the save format in CNN_proof_1.py
|
||||
model.features.load_state_dict(torch.load(path, map_location=DEVICE))
|
||||
print(f"Successfully synchronized weights with custom encoder architecture: {path}")
|
||||
|
||||
model.to(DEVICE)
|
||||
model.eval()
|
||||
return model
|
||||
|
||||
if __name__ == "__main__":
|
||||
encoder = load_trained_encoder(ENCODER_PATH)
|
||||
|
||||
transform = transforms.Compose([
|
||||
transforms.Resize((256, 256)), # Standardized size matching training
|
||||
transforms.ToTensor()
|
||||
])
|
||||
|
||||
# 3. SCAN ALL IMAGE MAPS
|
||||
all_files = sorted([f for f in os.listdir(IMG_DIR) if f.endswith('.png')])
|
||||
print(f"Discovered {len(all_files)} total ion slices in data pool.")
|
||||
|
||||
ion_registry = []
|
||||
for f in all_files:
|
||||
try:
|
||||
mz_extracted = float(f.replace("ion_", "").replace(".png", ""))
|
||||
ion_registry.append({"filename": f, "mz": mz_extracted})
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
df_ions = pd.DataFrame(ion_registry)
|
||||
|
||||
# 4. EXTRACT VECTORS
|
||||
print("Extracting L2-normalized latent fingerprints...")
|
||||
latent_vectors = {}
|
||||
|
||||
with torch.no_grad():
|
||||
for _, row in df_ions.iterrows():
|
||||
fpath = os.path.join(IMG_DIR, row['filename'])
|
||||
img_tensor = transform(Image.open(fpath).convert("L")).unsqueeze(0).to(DEVICE)
|
||||
feat = encoder(img_tensor)
|
||||
feat_norm = F.normalize(feat, p=2, dim=1) # Project onto unit hypersphere
|
||||
latent_vectors[row['filename']] = feat_norm.squeeze(0).cpu().numpy()
|
||||
|
||||
# 5. CONSTRUCT SEED
|
||||
anchor_features = []
|
||||
found_anchors = []
|
||||
|
||||
for anchor in ANCHOR_MZS:
|
||||
match = df_ions[np.isclose(df_ions['mz'], anchor, atol=0.05)]
|
||||
if not match.empty:
|
||||
fname = match.iloc[0]['filename']
|
||||
anchor_features.append(latent_vectors[fname])
|
||||
found_anchors.append(fname)
|
||||
|
||||
if len(anchor_features) == 0:
|
||||
print("Error: None of your specified anchor vein images were located.")
|
||||
exit()
|
||||
|
||||
vascular_profile_centroid = np.mean(anchor_features, axis=0)
|
||||
vascular_profile_centroid /= np.linalg.norm(vascular_profile_centroid)
|
||||
|
||||
print(f"Generated unified vascular profile from {len(found_anchors)} anchor ions.")
|
||||
|
||||
# 6. EVALUATE SIMILARITY
|
||||
guided_matches = []
|
||||
for fname, vector in latent_vectors.items():
|
||||
similarity = np.dot(vector, vascular_profile_centroid)
|
||||
if similarity >= SIMI_THRESHOLD:
|
||||
mz_val = df_ions[df_ions['filename'] == fname]['mz'].values[0]
|
||||
guided_matches.append({"filename": fname, "mz": mz_val, "similarity": similarity})
|
||||
|
||||
df_guided = pd.DataFrame(guided_matches).sort_values(by="similarity", ascending=False)
|
||||
print(f"\nFound {len(df_guided)} ions displaying vascular alignment (Cosine Sim >= {SIMI_THRESHOLD})")
|
||||
|
||||
csv_out = os.path.join(OUTPUT_DIR, "guided_vascular_ions.csv")
|
||||
df_guided.to_csv(csv_out, index=False)
|
||||
|
||||
# 7. GENERATE GALLERIES
|
||||
max_per_page = 12
|
||||
chunks = [df_guided[i:i + max_per_page] for i in range(0, len(df_guided), max_per_page)]
|
||||
|
||||
for page_idx, chunk in enumerate(chunks):
|
||||
num_plots = len(chunk)
|
||||
rows = int(np.ceil(num_plots / 4))
|
||||
cols = min(num_plots, 4)
|
||||
|
||||
fig, axes = plt.subplots(rows, cols, figsize=(16, rows * 4))
|
||||
fig.suptitle(f"Guided Vascular Affinity Grouping - Tier {page_idx + 1}", fontsize=16, y=0.98)
|
||||
|
||||
flat_axes = axes.flatten() if isinstance(axes, np.ndarray) else [axes]
|
||||
|
||||
for idx, (_, row) in enumerate(chunk.iterrows()):
|
||||
ax = flat_axes[idx]
|
||||
img_path = os.path.join(IMG_DIR, row['filename'])
|
||||
img = Image.open(img_path)
|
||||
# Use 'viridis' for improved structural visibility
|
||||
ax.imshow(img, cmap='viridis')
|
||||
ax.set_title(f"m/z {row['mz']:.2f}\nSim: {row['similarity']:.4f}", fontsize=10)
|
||||
ax.axis('off')
|
||||
|
||||
for empty_idx in range(num_plots, len(flat_axes)):
|
||||
flat_axes[empty_idx].axis('off')
|
||||
|
||||
plt.tight_layout()
|
||||
gallery_out = os.path.join(OUTPUT_DIR, f"Guided_Vascular_Gallery_Page_{page_idx + 1}.png")
|
||||
plt.savefig(gallery_out, dpi=200, bbox_inches='tight')
|
||||
plt.close()
|
||||
|
||||
print("\nGuided extraction validation cycle complete.")
|
||||
|
||||
print("\n--- RUNNING ISOTOPIC FUNCTIONAL VALIDATION ---")
|
||||
verified_biological_count = 0
|
||||
|
||||
for idx, row in df_guided.iterrows():
|
||||
target_mz = row['mz']
|
||||
isotope_mz = target_mz + 1.0033
|
||||
|
||||
# Check if the expected isotope exists within your parsed data pool
|
||||
isotope_match = df_ions[np.isclose(df_ions['mz'], isotope_mz, atol=0.02)]
|
||||
|
||||
if not isotope_match.empty:
|
||||
iso_fname = isotope_match.iloc[0]['filename']
|
||||
iso_vector = latent_vectors[iso_fname]
|
||||
|
||||
# Calculate similarity of the isotope to your core vascular vector
|
||||
iso_sim = np.dot(iso_vector, vascular_profile_centroid)
|
||||
|
||||
if iso_sim >= 0.80:
|
||||
print(f"Verified Structural Pair: Base m/z {target_mz:.2f} (Sim: {row['similarity']:.4f}) -> Isotope m/z {isotope_mz:.2f} (Sim: {iso_sim:.4f})")
|
||||
verified_biological_count += 1
|
||||
|
||||
print(f"Validation complete. Confirmed {verified_biological_count} true isotopic structural pairs.")
|
||||
@@ -0,0 +1,109 @@
|
||||
import os
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.data import DataLoader, Dataset
|
||||
from torchvision import models, transforms
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
from sklearn.cluster import KMeans
|
||||
from sklearn.manifold import TSNE
|
||||
import matplotlib.pyplot as plt
|
||||
import pandas as pd
|
||||
|
||||
# 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")
|
||||
|
||||
# 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}")
|
||||
|
||||
model = models.efficientnet_b0()
|
||||
model.classifier = nn.Identity()
|
||||
|
||||
state_dict = torch.load(path, map_location=DEVICE)
|
||||
model.load_state_dict(state_dict)
|
||||
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(),
|
||||
])
|
||||
|
||||
def __len__(self):
|
||||
return len(self.img_names)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
img_path = os.path.join(self.img_dir, self.img_names[idx])
|
||||
image = Image.open(img_path).convert("RGB")
|
||||
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)
|
||||
|
||||
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 = []
|
||||
|
||||
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)
|
||||
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)
|
||||
|
||||
# 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)
|
||||
|
||||
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)
|
||||
|
||||
# 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(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)
|
||||
|
||||
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}'.")
|
||||
@@ -11,6 +11,7 @@ from sklearn.decomposition import PCA
|
||||
from sklearn.metrics import silhouette_score, davies_bouldin_score, calinski_harabasz_score, adjusted_rand_score
|
||||
import matplotlib.pyplot as plt
|
||||
from scipy.stats import ttest_ind
|
||||
import torch.nn.functional as F
|
||||
|
||||
# 0. REPRODUCIBILITY
|
||||
def set_seed(seed=42):
|
||||
@@ -29,29 +30,43 @@ 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 = 10
|
||||
|
||||
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. DATA LOADING
|
||||
def load_images():
|
||||
img_names = sorted([f for f in os.listdir(IMG_DIR) if f.endswith('.png')])
|
||||
raw_pixels = []
|
||||
mzs = []
|
||||
|
||||
# transform = transforms.Compose([
|
||||
# transforms.Resize((224, 224)),
|
||||
# transforms.Grayscale(),
|
||||
# transforms.ToTensor(),
|
||||
# ])
|
||||
|
||||
print(f"Loading {len(img_names)} images for validation...")
|
||||
for name in img_names:
|
||||
img_path = os.path.join(IMG_DIR, name)
|
||||
img = Image.open(img_path).convert("L")
|
||||
raw_pixels.append(np.array(img).flatten())
|
||||
|
||||
# Extract mz from filename (ion_XXX.XX.png)
|
||||
try:
|
||||
mz = float(name.split('_')[1].replace('.png', ''))
|
||||
mzs.append(mz)
|
||||
@@ -61,15 +76,14 @@ def load_images():
|
||||
return np.array(raw_pixels), np.array(mzs), img_names
|
||||
|
||||
def extract_simclr_features(img_names):
|
||||
model = models.efficientnet_b0()
|
||||
model.classifier = nn.Identity()
|
||||
model = MSI_Structural_Encoder()
|
||||
if os.path.exists(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(),
|
||||
])
|
||||
|
||||
@@ -78,25 +92,23 @@ def extract_simclr_features(img_names):
|
||||
with torch.no_grad():
|
||||
for name in 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)
|
||||
|
||||
# 2. VALIDATION TASKS
|
||||
def baseline_comparison(X_raw, X_simclr):
|
||||
print("\n--- TASK 1: BASELINE COMPARISON (PCA vs SimCLR) ---")
|
||||
|
||||
# Baseline: PCA on Raw Pixels
|
||||
pca_raw = PCA(n_components=50, random_state=42)
|
||||
X_pca_raw = pca_raw.fit_transform(X_raw)
|
||||
|
||||
# SimCLR: PCA on latent features (as done in the paper)
|
||||
pca_simclr = PCA(n_components=50, random_state=42)
|
||||
X_pca_simclr = pca_simclr.fit_transform(X_simclr)
|
||||
|
||||
# Cluster both
|
||||
km_raw = KMeans(n_clusters=K, random_state=42, n_init=10)
|
||||
labels_raw = km_raw.fit_predict(X_pca_raw)
|
||||
|
||||
@@ -129,7 +141,6 @@ def stability_analysis(X_features):
|
||||
all_labels.append(labels)
|
||||
metrics_list.append(silhouette_score(X_pca, labels))
|
||||
|
||||
# Calculate ARI between all pairs of runs
|
||||
ari_scores = []
|
||||
for i in range(len(all_labels)):
|
||||
for j in range(i + 1, len(all_labels)):
|
||||
@@ -140,22 +151,18 @@ def stability_analysis(X_features):
|
||||
|
||||
def isotope_validation(X_features, mzs):
|
||||
print("\n--- TASK 3: ISOTOPE CO-LOCALIZATION VALIDATION ---")
|
||||
|
||||
# Normalize features for distance calculation
|
||||
X_norm = X_features / np.linalg.norm(X_features, axis=1, keepdims=True)
|
||||
|
||||
isotope_dist = []
|
||||
random_dist = []
|
||||
|
||||
# Find isotopic pairs (Adjusted to allow for binned channel drift)
|
||||
for i in range(len(mzs)):
|
||||
for j in range(i + 1, len(mzs)):
|
||||
diff = abs(mzs[i] - mzs[j])
|
||||
if 0.95 <= diff <= 1.05: # Accommodates binned spacing variations
|
||||
if 0.95 <= diff <= 1.05:
|
||||
dist = np.linalg.norm(X_norm[i] - X_norm[j])
|
||||
isotope_dist.append(dist)
|
||||
|
||||
# Sample random pairs (same number as isotopes)
|
||||
if len(isotope_dist) > 0:
|
||||
for _ in range(len(isotope_dist)):
|
||||
idx1 = random.randint(0, len(mzs)-1)
|
||||
@@ -171,9 +178,8 @@ def isotope_validation(X_features, mzs):
|
||||
t_stat, p_val = ttest_ind(isotope_dist, random_dist)
|
||||
print(f"T-test p-value: {p_val:.4e} (Significant if < 0.05)")
|
||||
|
||||
# Plotting
|
||||
plt.figure(figsize=(8, 6))
|
||||
plt.boxplot([isotope_dist, random_dist], labels=['Isotopic Pairs', 'Random Pairs'])
|
||||
plt.boxplot([isotope_dist, random_dist], tick_labels=['Isotopic Pairs', 'Random Pairs'])
|
||||
plt.title('Latent Space Distances: Isotopes vs Random')
|
||||
plt.ylabel('Euclidean Distance (Normalized Latent Space)')
|
||||
plt.savefig(os.path.join(BASE_DIR, "..", "figures", "isotope_validation_plot.png"))
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import os
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.data import DataLoader, Dataset
|
||||
from torchvision import models, transforms
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
from sklearn.cluster import KMeans
|
||||
import torch.nn.functional as F
|
||||
|
||||
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")
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
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 load_encoder_diagnostic(path):
|
||||
model = MSI_Structural_Encoder()
|
||||
if os.path.exists(path):
|
||||
state_dict = torch.load(path, map_location=DEVICE)
|
||||
model.features.load_state_dict(state_dict)
|
||||
model.to(DEVICE)
|
||||
model.eval()
|
||||
return model
|
||||
|
||||
if __name__ == "__main__":
|
||||
encoder = load_encoder_diagnostic(ENCODER_PATH)
|
||||
|
||||
# Load targets directly to test raw alignment
|
||||
img_155 = os.path.join(IMG_DIR, "ion_155.75.png")
|
||||
img_156 = os.path.join(IMG_DIR, "ion_156.07.png")
|
||||
|
||||
transform = transforms.Compose([
|
||||
transforms.Resize((256, 256)),
|
||||
transforms.ToTensor()
|
||||
])
|
||||
|
||||
if os.path.exists(img_155) and os.path.exists(img_156):
|
||||
# Convert to Grayscale "L"
|
||||
t_155 = transform(Image.open(img_155).convert("L")).unsqueeze(0).to(DEVICE)
|
||||
t_156 = transform(Image.open(img_156).convert("L")).unsqueeze(0).to(DEVICE)
|
||||
|
||||
with torch.no_grad():
|
||||
f_155 = encoder(t_155)
|
||||
f_156 = encoder(t_156)
|
||||
|
||||
# Check directional similarity
|
||||
sim = F.cosine_similarity(f_155, f_156)
|
||||
print(f"\n--- Feature Diagnostics ---")
|
||||
print(f"Cosine Similarity between Vein Ions (155.75 vs 156.07): {sim.item():.4f}")
|
||||
print("If this value is below 0.85, the loaded weight file is treating them as different shapes.")
|
||||
|
||||
@@ -5,20 +5,8 @@ from PIL import Image
|
||||
|
||||
# 1. CONFIGURATION (Relative paths for portability)
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
# Discovery logic for the results CSV
|
||||
CSV_OPTIONS = [
|
||||
os.path.join(BASE_DIR, "..", "msi_clusters_results.csv"),
|
||||
os.path.join(BASE_DIR, "..", "msi_clusters_direct_results.csv"),
|
||||
os.path.join(BASE_DIR, "..", "pruebas_clusters", "msi_clusters_direct_results.csv"),
|
||||
os.path.join(BASE_DIR, "..", "msi_tsne_results.csv")
|
||||
]
|
||||
|
||||
CSV_PATH = next((opt for opt in CSV_OPTIONS if os.path.exists(opt)), None)
|
||||
|
||||
if not CSV_PATH:
|
||||
print("Warning: No cluster results CSV found in the project root.")
|
||||
# Default path for error reporting
|
||||
CSV_PATH = os.path.join(BASE_DIR, "..", "msi_clusters_results.csv")
|
||||
# Strictly use the root results file generated by graficar_tsne_msi.py
|
||||
CSV_PATH = os.path.join(BASE_DIR, "..", "msi_clusters_results.csv")
|
||||
|
||||
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
|
||||
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "figures", "galleries")
|
||||
@@ -38,6 +26,7 @@ if os.path.exists(CSV_PATH):
|
||||
else:
|
||||
for cluster_id in sorted(df['cluster'].unique()):
|
||||
print(f"Generating gallery for Cluster {cluster_id}...")
|
||||
# Take a 3x3 sample of the cluster
|
||||
cluster_ions = df[df['cluster'] == cluster_id][img_col].head(9).tolist()
|
||||
|
||||
fig, axes = plt.subplots(3, 3, figsize=(10, 10))
|
||||
@@ -48,17 +37,19 @@ if os.path.exists(CSV_PATH):
|
||||
img_path = os.path.join(IMG_DIR, cluster_ions[i])
|
||||
if os.path.exists(img_path):
|
||||
img = Image.open(img_path)
|
||||
ax.imshow(img, cmap='gray')
|
||||
# Using 'viridis' improves human visibility of low-concentration transport traces in the veins
|
||||
ax.imshow(img, cmap='viridis')
|
||||
ax.set_title(cluster_ions[i], fontsize=8)
|
||||
else:
|
||||
ax.text(0.5, 0.5, 'Image Not Found', ha='center', va='center', fontsize=6)
|
||||
ax.axis('off')
|
||||
|
||||
plt.tight_layout()
|
||||
plt.savefig(f"{OUTPUT_DIR}/cluster_gallery_{cluster_id}.png")
|
||||
# Standardized filename for consistency
|
||||
plt.savefig(f"{OUTPUT_DIR}/Gallery_cluster_{cluster_id}.png")
|
||||
plt.close()
|
||||
|
||||
print(f"\nGalleries successfully saved in: {OUTPUT_DIR}")
|
||||
else:
|
||||
print(f"Error: Missing required results file: {CSV_PATH}")
|
||||
print("Please ensure you have run the clustering scripts first.")
|
||||
print("Please run 'python scripts_python/graficar_tsne_msi.py' first to generate results.")
|
||||
|
||||
Reference in New Issue
Block a user