diff --git a/CNN_proof_1.py b/CNN_proof_1.py new file mode 100644 index 0000000..27908bc --- /dev/null +++ b/CNN_proof_1.py @@ -0,0 +1,118 @@ +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 + +# 1. CONFIGURACIÓN +IMG_DIR = "/home/sierra/Documentos/Prueba teams/Julia_msi_GUI-main/datos_para_ai" +BATCH_SIZE = 32 +EPOCHS = 50 +LEARNING_RATE = 0.0003 # SimCLR suele preferir LRs más bajos +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([ + # El paper menciona que rotaciones leves están bien, pero Blur/Noise/Color son clave + transforms.RandomRotation(10), + transforms.GaussianBlur(kernel_size=3, sigma=(0.1, 2.0)), + transforms.ColorJitter(brightness=0.4, contrast=0.4), + transforms.ToTensor(), + # Ruido Gaussiano (Sugerido por el paper para MSI) + transforms.Lambda(lambda x: x + torch.randn_like(x) * 0.01) + ]) + + def __call__(self, x): + # SimCLR: Dos vistas aumentadas de la misma imagen + 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__() + # Usamos pesos pre-entrenados como base (Transfer Learning inicial) + self.encoder = models.efficientnet_b0(weights=models.EfficientNet_B0_Weights.DEFAULT) + num_ftrs = self.encoder.classifier[1].in_features + self.encoder.classifier = nn.Identity() # Quitamos el clasificador original + + # Projector Head (MLP) - Según SimCLR original y el paper MSI + 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 (Corregida) +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) + + # Máscara para quitar la auto-similitud (diagonal) + mask = ~torch.eye(z.shape[0], device=z.device).bool() + sim_matrix = sim_matrix.masked_select(mask).view(z.shape[0], -1) + + # Los pares positivos están en (i, i+N) + 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 --- +if __name__ == "__main__": + print(f"Iniciando entrenamiento en: {DEVICE}") + dataset = MSIDataset(IMG_DIR, transform=MSIAugmentations()) + loader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True, drop_last=True) + + model = SimCLR_MSI().to(DEVICE) + optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE) + + for epoch in range(EPOCHS): + 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) + print(f"Época [{epoch+1}/{EPOCHS}], Loss: {avg_loss:.4f}") + + # Guardar solo el encoder (la parte que sabe extraer características) + torch.save(model.encoder.state_dict(), "msi_encoder_trained.pth") + print("Entrenamiento completado. Codificador guardado en 'msi_encoder_trained.pth'.")