finished CNN validations and cluster verification, cleaned repo of tests

This commit is contained in:
Pixelguy14
2026-06-04 14:31:55 -06:00
parent d98cfccb5f
commit 237bad0189
47 changed files with 991 additions and 796 deletions
-3
View File
@@ -39,9 +39,6 @@ class MSIAugmentations:
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()
])
+4 -1
View File
@@ -92,6 +92,8 @@ if __name__ == "__main__":
pca = PCA(n_components=min(50, X.shape[1]), random_state=42)
X_pca = pca.fit_transform(X)
# CRITICAL FIX: Re-normalize after PCA to restore unit hypersphere geometry for Spherical K-Means equivalent
X_pca = X_pca / np.linalg.norm(X_pca, axis=1, keepdims=True)
inertias = []
silhouettes = []
@@ -105,7 +107,8 @@ if __name__ == "__main__":
labels = kmeans.fit_predict(X_pca)
inertias.append(kmeans.inertia_)
silhouettes.append(silhouette_score(X_pca, labels))
# CRITICAL FIX: Evaluate using cosine distance on the un-reduced features
silhouettes.append(silhouette_score(X, labels, metric='cosine'))
davies_bouldin.append(davies_bouldin_score(X_pca, labels))
calinski_harabasz.append(calinski_harabasz_score(X_pca, labels))
+35 -5
View File
@@ -12,6 +12,7 @@ from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import pandas as pd
import torch.nn.functional as F
import plotly.express as px
def set_seed(seed=42):
random.seed(seed)
@@ -111,22 +112,25 @@ if __name__ == "__main__":
# 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:]
# CRITICAL FIX: Re-normalize strictly for K-Means to ensure objective Cosine geometry
features_pca_km_norm = features_pca_km / np.linalg.norm(features_pca_km, axis=1, keepdims=True)
# 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)
labels = clusterer.fit_predict(features_pca_km_norm)
# 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
perplexity=15,
early_exaggeration=24.0, # Boosted significantly to force tighter, more definitive visual clusters
learning_rate='auto',
init='pca', # Changed from 'random' to preserve global cluster seed stability
init='pca',
random_state=42
)
# Feed the unnormalized PCA vectors to t-SNE to allow intensity variance to separate the visual blobs
embeddings_2d = tsne.fit_transform(features_pca_km)
# Plotting
@@ -143,6 +147,32 @@ if __name__ == "__main__":
plt.savefig(os.path.join(BASE_DIR, "..", "msi_tsne_corregido.png"), dpi=300, bbox_inches='tight')
plt.close()
# INTERACTIVE PLOTLY EXPORT
print("Exporting Interactive Plotly t-SNE...")
mz_values = [float(n.replace("ion_", "").replace(".png", "")) for n in ion_names]
df_plot = pd.DataFrame({
't-SNE Dimension 1': embeddings_2d[:, 0],
't-SNE Dimension 2': embeddings_2d[:, 1],
'Cluster': [str(lbl) for lbl in labels],
'm/z': mz_values,
'Filename': ion_names
})
fig = px.scatter(
df_plot,
x='t-SNE Dimension 1',
y='t-SNE Dimension 2',
color='Cluster',
hover_data=['m/z', 'Filename'],
title="Interactive Segmented Leaf Manifold (Custom Encoder)",
category_orders={"Cluster": [str(i) for i in range(TARGET_K)]}
)
plotly_out = os.path.join(BASE_DIR, "..", "figures", "msi_tsne_interactive.html")
os.makedirs(os.path.dirname(plotly_out), exist_ok=True)
fig.write_html(plotly_out)
print(f"Interactive t-SNE saved to: {plotly_out}")
# Save outputs
print("Exporting synchronized cluster assignments...")
df_results = pd.DataFrame({'ion_image': ion_names, 'cluster': labels})
@@ -0,0 +1,117 @@
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.manifold import TSNE
import pandas as pd
import plotly.express as px
# 1. CONFIGURACIÓN
IMG_DIR = "/home/sierra/Documentos/Prueba teams/Julia_msi_GUI-main/datos_para_ai"
ENCODER_PATH = "Reporte/Model/msi_encoder_trained.pth"
CSV_PATH = "msi_clusters_results.csv" # Fuente de verdad
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 BASADO EN EL CSV
class MSIDatasetFromCSV(Dataset):
def __init__(self, img_dir, img_names):
self.img_dir = img_dir
self.img_names = img_names
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)
# --- PROCESO ---
if __name__ == "__main__":
# 4. CARGAR EL CSV DE RESULTADOS
print(f"Cargando datos desde {CSV_PATH}...")
df = pd.read_csv(CSV_PATH)
ion_names = df['ion_image'].tolist()
# Asegurarnos de que cluster sea categórico para Plotly
df['cluster'] = df['cluster'].astype(str)
print("Extrayendo características con el encoder...")
encoder = load_trained_encoder(ENCODER_PATH)
dataset = MSIDatasetFromCSV(IMG_DIR, ion_names)
loader = DataLoader(dataset, batch_size=1, shuffle=False)
features = []
with torch.no_grad():
for i, img in enumerate(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())
if (i+1) % 100 == 0:
print(f"Iones procesados: {i+1}/{len(ion_names)}")
features = np.array(features)
# 5. t-SNE
print("Calculando t-SNE...")
tsne = TSNE(n_components=2, perplexity=30, random_state=42)
embeddings_2d = tsne.fit_transform(features)
# Agregar coordenadas t-SNE al DataFrame original
df['tsne_1'] = embeddings_2d[:, 0]
df['tsne_2'] = embeddings_2d[:, 1]
# 6. VISUALIZACIÓN INTERACTIVA CON PLOTLY
print("Generando gráfica interactiva con Plotly...")
# Usar escala de colores similar a tab10 o cualitativa estándar
fig = px.scatter(
df,
x='tsne_1',
y='tsne_2',
color='cluster',
hover_data={'ion_image': True, 'mz': True, 'cluster': True, 'tsne_1': False, 'tsne_2': False},
title=f"t-SNE Interactivo de Iones MSI (Consistente con {CSV_PATH})",
labels={'tsne_1': 't-SNE 1', 'tsne_2': 't-SNE 2'},
category_orders={"cluster": [str(i) for i in range(N_CLUSTERS)]},
color_discrete_sequence=px.colors.qualitative.Plotly # O T10 si está disponible
)
# Mejorar el diseño
fig.update_traces(marker=dict(size=10, opacity=0.8, line=dict(width=1, color='DarkSlateGrey')))
fig.update_layout(
legend_title_text='Cluster ID',
font=dict(size=14),
hoverlabel=dict(bgcolor="white", font_size=16)
)
# Guardar como HTML
output_html = "msi_tsne_interactivo.html"
fig.write_html(output_html)
print(f"\n¡Éxito! Gráfica interactiva guardada en '{output_html}'.")
print("Puedes abrir este archivo en cualquier navegador para explorar los clusters.")
+84
View File
@@ -0,0 +1,84 @@
import os
import torch
import torch.nn.functional as F
import pandas as pd
import numpy as np
from PIL import Image
from torchvision import transforms
# Copy the exact encoder structure from your scripts
import torch.nn as nn
class MSI_Structural_Encoder(nn.Module):
def __init__(self):
super().__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)
DEVICE = torch.device("cpu")
IMG_DIR = "datos_para_ai"
MODEL_PATH = "models/msi_encoder_trained.pth"
if not os.path.exists(MODEL_PATH):
print("Model not found. Please ensure you are in the correct directory.")
exit()
model = MSI_Structural_Encoder()
model.features.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
model.eval()
transform = transforms.Compose([transforms.Resize((256, 256)), transforms.ToTensor()])
def get_vector(mz_target):
# Find the file closest to mz_target
files = [f for f in os.listdir(IMG_DIR) if f.endswith('.png')]
mzs = [float(f.replace("ion_", "").replace(".png", "")) for f in files]
idx = np.argmin(np.abs(np.array(mzs) - mz_target))
closest_mz = mzs[idx]
if abs(closest_mz - mz_target) > 0.1:
return None, closest_mz
img_path = os.path.join(IMG_DIR, files[idx])
img = Image.open(img_path).convert("L")
tensor = transform(img).unsqueeze(0)
with torch.no_grad():
feat = model(tensor)
feat_norm = F.normalize(feat, p=2, dim=1)
return feat_norm.numpy().flatten(), closest_mz
print("--- INTERNAL VALIDATION: ISOTOPIC & STRUCTURAL COHERENCE ---")
# Test 1: Isotopic Coherence (Atropine and its +1 Isotope)
v1, mz1 = get_vector(290.02)
v2, mz2 = get_vector(291.00)
if v1 is not None and v2 is not None:
sim = np.dot(v1, v2)
print(f"Isotopic Match -> m/z {mz1:.2f} (Atropine) vs m/z {mz2:.2f} (+1 Isotope): Cosine Similarity = {sim:.4f}")
# Test 2: Structural Coherence (Atropine and Scopolamine - both vascular)
v3, mz3 = get_vector(304.00)
if v1 is not None and v3 is not None:
sim = np.dot(v1, v3)
print(f"Biological Match -> m/z {mz1:.2f} (Atropine) vs m/z {mz3:.2f} (Scopolamine): Cosine Similarity = {sim:.4f}")
# Test 3: Unrelated Coherence (Atropine vs random background or non-vascular)
v4, mz4 = get_vector(142.09) # Tropine (paravascular, should be lower than scopolamine)
if v1 is not None and v4 is not None:
sim = np.dot(v1, v4)
print(f"Divergent Match -> m/z {mz1:.2f} (Atropine) vs m/z {mz4:.2f} (Tropine): Cosine Similarity = {sim:.4f}")