Files
MSI_Julia_CNN_Release/scripts_python/CNN_proof_1.py
T

156 lines
5.9 KiB
Python

import os
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
from torchvision import models, transforms
from PIL import Image
import torch.nn.functional as F
import numpy as np
import random
import time
import psutil
# 0. REPRODUCIBILITY
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)
# 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 = 32
# 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
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 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 __call__(self, x):
return self.train_transform(x), self.train_transform(x)
# 3. DATASET
class MSIDataset(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.transform = transform
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")
if self.transform:
return self.transform(image), self.img_names[idx]
return transforms.ToTensor()(image), self.img_names[idx]
# 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),
nn.ReLU(),
nn.Linear(512, 128)
)
def forward(self, x):
h = self.encoder(x)
z = self.projector(h)
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()
# --- 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()
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")
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")
os.makedirs(os.path.dirname(MODEL_SAVE_PATH), exist_ok=True)
torch.save(model.encoder.state_dict(), MODEL_SAVE_PATH)
print(f"Model saved to: {MODEL_SAVE_PATH}")