Files

118 lines
3.9 KiB
Python

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. 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. LOAD THE TRAINED MODEL
def load_trained_encoder(path):
if not os.path.exists(path):
raise FileNotFoundError(f"Model not found at {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 BASED ON THE 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)
# --- PROCESS ---
if __name__ == "__main__":
# 4. LOAD THE RESULTS CSV
print(f"Loading data from {CSV_PATH}...")
df = pd.read_csv(CSV_PATH)
ion_names = df['ion_image'].tolist()
# Make sure cluster is categorical for Plotly
df['cluster'] = df['cluster'].astype(str)
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)
features = []
with torch.no_grad():
for i, img in enumerate(loader):
img = img.to(DEVICE)
feat = encoder(img)
# 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"Ions processed: {i+1}/{len(ion_names)}")
features = np.array(features)
# 5. t-SNE
print("Computing t-SNE...")
tsne = TSNE(n_components=2, perplexity=30, random_state=42)
embeddings_2d = tsne.fit_transform(features)
# Add t-SNE coordinates to the original DataFrame
df['tsne_1'] = embeddings_2d[:, 0]
df['tsne_2'] = embeddings_2d[:, 1]
# 6. INTERACTIVE VISUALIZATION WITH PLOTLY
print("Generating interactive plot with Plotly...")
# 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"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 # Or T10 if available
)
# 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',
font=dict(size=14),
hoverlabel=dict(bgcolor="white", font_size=16)
)
# Save as HTML
output_html = "msi_tsne_interactive.html"
fig.write_html(output_html)
print(f"\nSuccess! Interactive plot saved to '{output_html}'.")
print("You can open this file in any browser to explore the clusters.")