first commit, migrated repository to contain the scripts only
This commit is contained in:
@@ -12,24 +12,24 @@ from sklearn.manifold import TSNE
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# 1. CONFIGURACIÓN
|
||||
IMG_DIR = "datos_para_ai"
|
||||
OUTPUT_DIR = "pruebas_clusters"
|
||||
# 1. CONFIGURATION
|
||||
IMG_DIR = "ai_data"
|
||||
OUTPUT_DIR = "cluster_tests"
|
||||
N_CLUSTERS = 10
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||
|
||||
# 2. CARGAR MODELO PRE-ENTRENADO (Directo de PyTorch)
|
||||
# 2. LOAD PRETRAINED MODEL (Directly from PyTorch)
|
||||
def get_pretrained_extractor():
|
||||
# Usamos los pesos por defecto de ImageNet
|
||||
# We use the default ImageNet weights
|
||||
model = models.efficientnet_b0(weights=models.EfficientNet_B0_Weights.DEFAULT)
|
||||
model.classifier = nn.Identity() # Quitamos la capa de clasificación
|
||||
model.classifier = nn.Identity() # Remove the classification layer
|
||||
model.to(DEVICE)
|
||||
model.eval()
|
||||
return model
|
||||
|
||||
# 3. DATASET CON NORMALIZACIÓN ESTÁNDAR
|
||||
# 3. DATASET WITH STANDARD NORMALIZATION
|
||||
class MSIDatasetDirect(Dataset):
|
||||
def __init__(self, img_dir):
|
||||
self.img_dir = img_dir
|
||||
@@ -37,7 +37,7 @@ class MSIDatasetDirect(Dataset):
|
||||
self.transform = transforms.Compose([
|
||||
transforms.Resize((224, 224)),
|
||||
transforms.ToTensor(),
|
||||
# Normalización obligatoria para modelos pre-entrenados
|
||||
# Normalization required for pretrained models
|
||||
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
||||
])
|
||||
|
||||
@@ -50,7 +50,7 @@ class MSIDatasetDirect(Dataset):
|
||||
return self.transform(image), self.img_names[idx]
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(f"Extrayendo características con red pre-entrenada en {DEVICE}...")
|
||||
print(f"Extracting features with the pretrained network on {DEVICE}...")
|
||||
model = get_pretrained_extractor()
|
||||
dataset = MSIDatasetDirect(IMG_DIR)
|
||||
loader = DataLoader(dataset, batch_size=1, shuffle=False)
|
||||
@@ -62,55 +62,55 @@ if __name__ == "__main__":
|
||||
for img, name in loader:
|
||||
img = img.to(DEVICE)
|
||||
feat = model(img)
|
||||
# Aplanar el vector de características (1280 dimensiones para EffNet-B0)
|
||||
# Flatten the feature vector (1280 dimensions for EffNet-B0)
|
||||
features.append(feat.cpu().numpy().flatten())
|
||||
ion_names.append(name[0])
|
||||
|
||||
features = np.array(features)
|
||||
print(f"Características extraídas: {features.shape}")
|
||||
print(f"Extracted features: {features.shape}")
|
||||
|
||||
# 4. REDUCCIÓN DE DIMENSIONALIDAD (PCA)
|
||||
# Esto ayuda a que el clustering no se pierda en dimensiones irrelevantes
|
||||
print("Reduciendo ruido con PCA...")
|
||||
# 4. DIMENSIONALITY REDUCTION (PCA)
|
||||
# This helps clustering from getting lost in irrelevant dimensions
|
||||
print("Reducing noise with PCA...")
|
||||
features_scaled = StandardScaler().fit_transform(features)
|
||||
pca = PCA(n_components=0.95) # Mantenemos el 95% de la varianza
|
||||
pca = PCA(n_components=0.95) # We keep 95% of the variance
|
||||
features_pca = pca.fit_transform(features_scaled)
|
||||
print(f"Dimensiones tras PCA: {features_pca.shape[1]}")
|
||||
print(f"Dimensions after PCA: {features_pca.shape[1]}")
|
||||
|
||||
# 5. CLUSTERING K-MEANS
|
||||
print(f"Agrupando en {N_CLUSTERS} clusters...")
|
||||
# 5. K-MEANS CLUSTERING
|
||||
print(f"Grouping into {N_CLUSTERS} clusters...")
|
||||
km = KMeans(n_clusters=N_CLUSTERS, n_init=20, random_state=42)
|
||||
labels = km.fit_predict(features_pca)
|
||||
|
||||
# 6. VISUALIZACIÓN (t-SNE)
|
||||
print("Generando visualización t-SNE para verificar consistencia...")
|
||||
# 6. VISUALIZATION (t-SNE)
|
||||
print("Generating t-SNE visualization to verify consistency...")
|
||||
tsne = TSNE(n_components=2, random_state=42)
|
||||
features_tsne = tsne.fit_transform(features_pca)
|
||||
|
||||
plt.figure(figsize=(10, 8))
|
||||
scatter = plt.scatter(features_tsne[:, 0], features_tsne[:, 1], c=labels, cmap='tab10', alpha=0.7)
|
||||
plt.colorbar(scatter, ticks=range(N_CLUSTERS), label='Cluster ID')
|
||||
plt.title(f"Visualización de Clusters (K={N_CLUSTERS}) - Directo")
|
||||
plt.title(f"Cluster Visualization (K={N_CLUSTERS}) - Direct")
|
||||
plt.xlabel("t-SNE 1")
|
||||
plt.ylabel("t-SNE 2")
|
||||
plt.grid(True, linestyle='--', alpha=0.5)
|
||||
plt.savefig(os.path.join(OUTPUT_DIR, "msi_clusters_direct_plot.png"))
|
||||
print(f"Gráfico de consistencia guardado en '{OUTPUT_DIR}/msi_clusters_direct_plot.png'.")
|
||||
print(f"Consistency plot saved to '{OUTPUT_DIR}/msi_clusters_direct_plot.png'.")
|
||||
|
||||
# 7. GUARDAR Y REPORTAR
|
||||
# 7. SAVE AND REPORT
|
||||
df = pd.DataFrame({'ion_image': ion_names, 'cluster': labels})
|
||||
df['mz'] = df['ion_image'].str.extract(r'(\d+\.\d+)').astype(float)
|
||||
df.to_csv(os.path.join(OUTPUT_DIR, "msi_clusters_direct_results.csv"), index=False)
|
||||
|
||||
# Crear un resumen de cuántos iones hay por cluster
|
||||
print("\nResumen de Clusters (Consistente con el CSV y el Gráfico):")
|
||||
# Create a summary of how many ions there are per cluster
|
||||
print("\nCluster Summary (Consistent with the CSV and the Plot):")
|
||||
counts = df['cluster'].value_counts().sort_index()
|
||||
print(counts)
|
||||
|
||||
# Guardar también el resumen para evitar confusiones con otros archivos
|
||||
# Also save the summary to avoid confusion with other files
|
||||
summary_df = counts.reset_index()
|
||||
summary_df.columns = ['Cluster_ID', 'Ion_Count']
|
||||
summary_df.to_csv(os.path.join(OUTPUT_DIR, "msi_clusters_direct_summary.csv"), index=False)
|
||||
|
||||
print(f"\nResultados guardados en '{OUTPUT_DIR}/msi_clusters_direct_results.csv' y '{OUTPUT_DIR}/msi_clusters_direct_summary.csv'.")
|
||||
print(f"Usa '{OUTPUT_DIR}/msi_clusters_direct_plot.png' para validar visualmente los puntos.")
|
||||
print(f"\nResults saved to '{OUTPUT_DIR}/msi_clusters_direct_results.csv' and '{OUTPUT_DIR}/msi_clusters_direct_summary.csv'.")
|
||||
print(f"Use '{OUTPUT_DIR}/msi_clusters_direct_plot.png' to visually validate the points.")
|
||||
|
||||
+18
-18
@@ -10,17 +10,17 @@ from sklearn.manifold import TSNE
|
||||
import matplotlib.pyplot as plt
|
||||
import pandas as pd
|
||||
|
||||
# 1. CONFIGURACIÓN
|
||||
# 1. CONFIGURATION
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
IMG_DIR = os.path.join(BASE_DIR, "../..", "datos_para_ai")
|
||||
IMG_DIR = os.path.join(BASE_DIR, "../..", "ai_data")
|
||||
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
|
||||
# 2. LOAD THE TRAINED MODEL
|
||||
def load_trained_encoder(path):
|
||||
if not os.path.exists(path):
|
||||
raise FileNotFoundError(f"No se encontró el modelo en {path}")
|
||||
raise FileNotFoundError(f"Model not found at {path}")
|
||||
|
||||
model = models.efficientnet_b0()
|
||||
model.classifier = nn.Identity()
|
||||
@@ -31,7 +31,7 @@ def load_trained_encoder(path):
|
||||
model.eval()
|
||||
return model
|
||||
|
||||
# 3. DATASET PARA INFERENCIA
|
||||
# 3. DATASET FOR INFERENCE
|
||||
class MSIDatasetInference(Dataset):
|
||||
def __init__(self, img_dir):
|
||||
self.img_dir = img_dir
|
||||
@@ -49,18 +49,18 @@ class MSIDatasetInference(Dataset):
|
||||
image = Image.open(img_path).convert("RGB")
|
||||
return self.transform(image), self.img_names[idx]
|
||||
|
||||
# --- PROCESO ---
|
||||
# --- PROCESS ---
|
||||
if __name__ == "__main__":
|
||||
print("Extrayendo características con el encoder...")
|
||||
print("Extracting features with the encoder...")
|
||||
try:
|
||||
encoder = load_trained_encoder(ENCODER_PATH)
|
||||
except Exception as e:
|
||||
print(f"Error al cargar el modelo: {e}")
|
||||
print(f"Error loading the model: {e}")
|
||||
exit(1)
|
||||
|
||||
dataset = MSIDatasetInference(IMG_DIR)
|
||||
if len(dataset) == 0:
|
||||
print(f"No se encontraron imágenes en {IMG_DIR}")
|
||||
print(f"No images found in {IMG_DIR}")
|
||||
exit(1)
|
||||
|
||||
loader = DataLoader(dataset, batch_size=1, shuffle=False)
|
||||
@@ -72,28 +72,28 @@ if __name__ == "__main__":
|
||||
for img, name in loader:
|
||||
img = img.to(DEVICE)
|
||||
feat = encoder(img)
|
||||
# Normalización L2
|
||||
# L2 normalization
|
||||
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...")
|
||||
# 4. K-MEANS CLUSTERING
|
||||
print(f"Running KMeans with {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...")
|
||||
# 5. CORRECTED t-SNE VISUALIZATION
|
||||
print("Generating t-SNE visualization with corrected scale...")
|
||||
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:
|
||||
# Applying your specific correction:
|
||||
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
|
||||
# Configure the colorbar with exact ticks for 10 clusters
|
||||
cbar = plt.colorbar(scatter, ticks=range(N_CLUSTERS))
|
||||
cbar.set_label('Cluster ID')
|
||||
|
||||
@@ -102,8 +102,8 @@ if __name__ == "__main__":
|
||||
plt.ylabel("t-SNE dimension 2")
|
||||
plt.grid(True, linestyle='--', alpha=0.5)
|
||||
|
||||
output_file = "msi_tsne_corregido.png"
|
||||
output_file = "msi_tsne_corrected.png"
|
||||
plt.savefig(output_file, dpi=300, bbox_inches='tight')
|
||||
# plt.show()
|
||||
|
||||
print(f"Visualización guardada exitosamente en '{output_file}'.")
|
||||
print(f"Visualization successfully saved to '{output_file}'.")
|
||||
+26
-26
@@ -9,17 +9,17 @@ 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
|
||||
# 1. CONFIGURATION
|
||||
IMG_DIR = "/home/sierra/Documents/Test teams/Julia_msi_GUI-main/ai_data"
|
||||
ENCODER_PATH = "Report/Model/msi_encoder_trained.pth"
|
||||
CSV_PATH = "msi_clusters_results.csv" # Source of truth
|
||||
N_CLUSTERS = 10
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
# 2. CARGAR EL MODELO ENTRENADO
|
||||
# 2. LOAD THE TRAINED MODEL
|
||||
def load_trained_encoder(path):
|
||||
if not os.path.exists(path):
|
||||
raise FileNotFoundError(f"No se encontró el modelo en {path}")
|
||||
raise FileNotFoundError(f"Model not found at {path}")
|
||||
|
||||
model = models.efficientnet_b0()
|
||||
model.classifier = nn.Identity()
|
||||
@@ -30,7 +30,7 @@ def load_trained_encoder(path):
|
||||
model.eval()
|
||||
return model
|
||||
|
||||
# 3. DATASET BASADO EN EL CSV
|
||||
# 3. DATASET BASED ON THE CSV
|
||||
class MSIDatasetFromCSV(Dataset):
|
||||
def __init__(self, img_dir, img_names):
|
||||
self.img_dir = img_dir
|
||||
@@ -48,17 +48,17 @@ class MSIDatasetFromCSV(Dataset):
|
||||
image = Image.open(img_path).convert("RGB")
|
||||
return self.transform(image)
|
||||
|
||||
# --- PROCESO ---
|
||||
# --- PROCESS ---
|
||||
if __name__ == "__main__":
|
||||
# 4. CARGAR EL CSV DE RESULTADOS
|
||||
print(f"Cargando datos desde {CSV_PATH}...")
|
||||
# 4. LOAD THE RESULTS CSV
|
||||
print(f"Loading data from {CSV_PATH}...")
|
||||
df = pd.read_csv(CSV_PATH)
|
||||
ion_names = df['ion_image'].tolist()
|
||||
|
||||
# Asegurarnos de que cluster sea categórico para Plotly
|
||||
# Make sure cluster is categorical for Plotly
|
||||
df['cluster'] = df['cluster'].astype(str)
|
||||
|
||||
print("Extrayendo características con el encoder...")
|
||||
print("Extracting features with the encoder...")
|
||||
encoder = load_trained_encoder(ENCODER_PATH)
|
||||
dataset = MSIDatasetFromCSV(IMG_DIR, ion_names)
|
||||
loader = DataLoader(dataset, batch_size=1, shuffle=False)
|
||||
@@ -68,40 +68,40 @@ if __name__ == "__main__":
|
||||
for i, img in enumerate(loader):
|
||||
img = img.to(DEVICE)
|
||||
feat = encoder(img)
|
||||
# Normalización L2
|
||||
# L2 normalization
|
||||
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)}")
|
||||
print(f"Ions processed: {i+1}/{len(ion_names)}")
|
||||
|
||||
features = np.array(features)
|
||||
|
||||
# 5. t-SNE
|
||||
print("Calculando t-SNE...")
|
||||
print("Computing 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
|
||||
# Add t-SNE coordinates to the original DataFrame
|
||||
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...")
|
||||
# 6. INTERACTIVE VISUALIZATION WITH PLOTLY
|
||||
print("Generating interactive plot with Plotly...")
|
||||
|
||||
# Usar escala de colores similar a tab10 o cualitativa estándar
|
||||
# Use a color scale similar to tab10 or the standard qualitative one
|
||||
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})",
|
||||
title=f"Interactive t-SNE of MSI Ions (Consistent with {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
|
||||
color_discrete_sequence=px.colors.qualitative.Plotly # Or T10 if available
|
||||
)
|
||||
|
||||
# Mejorar el diseño
|
||||
# Improve the layout
|
||||
fig.update_traces(marker=dict(size=10, opacity=0.8, line=dict(width=1, color='DarkSlateGrey')))
|
||||
fig.update_layout(
|
||||
legend_title_text='Cluster ID',
|
||||
@@ -109,9 +109,9 @@ if __name__ == "__main__":
|
||||
hoverlabel=dict(bgcolor="white", font_size=16)
|
||||
)
|
||||
|
||||
# Guardar como HTML
|
||||
output_html = "msi_tsne_interactivo.html"
|
||||
# Save as HTML
|
||||
output_html = "msi_tsne_interactive.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.")
|
||||
print(f"\nSuccess! Interactive plot saved to '{output_html}'.")
|
||||
print("You can open this file in any browser to explore the clusters.")
|
||||
Reference in New Issue
Block a user