altered CNN, encoder and loss function to achieve better stability, and fixed morphing of the images lower than the desired resolution

This commit is contained in:
Pixelguy14
2026-06-04 11:58:02 -06:00
parent 242fc6a445
commit d98cfccb5f
48 changed files with 1339 additions and 1366 deletions
+33 -27
View File
@@ -11,6 +11,7 @@ from sklearn.decomposition import PCA
from sklearn.metrics import silhouette_score, davies_bouldin_score, calinski_harabasz_score, adjusted_rand_score
import matplotlib.pyplot as plt
from scipy.stats import ttest_ind
import torch.nn.functional as F
# 0. REPRODUCIBILITY
def set_seed(seed=42):
@@ -29,29 +30,43 @@ set_seed(42)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
MODEL_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
# ENABLE CUDA IF AVAILABLE
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
K = 10
class MSI_Structural_Encoder(nn.Module):
def __init__(self):
super(MSI_Structural_Encoder, self).__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)
# 1. DATA LOADING
def load_images():
img_names = sorted([f for f in os.listdir(IMG_DIR) if f.endswith('.png')])
raw_pixels = []
mzs = []
# transform = transforms.Compose([
# transforms.Resize((224, 224)),
# transforms.Grayscale(),
# transforms.ToTensor(),
# ])
print(f"Loading {len(img_names)} images for validation...")
for name in img_names:
img_path = os.path.join(IMG_DIR, name)
img = Image.open(img_path).convert("L")
raw_pixels.append(np.array(img).flatten())
# Extract mz from filename (ion_XXX.XX.png)
try:
mz = float(name.split('_')[1].replace('.png', ''))
mzs.append(mz)
@@ -61,15 +76,14 @@ def load_images():
return np.array(raw_pixels), np.array(mzs), img_names
def extract_simclr_features(img_names):
model = models.efficientnet_b0()
model.classifier = nn.Identity()
model = MSI_Structural_Encoder()
if os.path.exists(MODEL_PATH):
model.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
model.features.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
model.to(DEVICE)
model.eval()
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.Resize((256, 256)),
transforms.ToTensor(),
])
@@ -78,25 +92,23 @@ def extract_simclr_features(img_names):
with torch.no_grad():
for name in img_names:
img_path = os.path.join(IMG_DIR, name)
img = Image.open(img_path).convert("RGB")
img = Image.open(img_path).convert("L")
img_t = transform(img).unsqueeze(0).to(DEVICE)
feat = model(img_t).cpu().numpy().flatten()
features.append(feat)
feat = model(img_t)
# CRITICAL FIX: Project explicitly onto the unit hypersphere
feat_norm = F.normalize(feat, p=2, dim=1)
features.append(feat_norm.cpu().numpy().flatten())
return np.array(features)
# 2. VALIDATION TASKS
def baseline_comparison(X_raw, X_simclr):
print("\n--- TASK 1: BASELINE COMPARISON (PCA vs SimCLR) ---")
# Baseline: PCA on Raw Pixels
pca_raw = PCA(n_components=50, random_state=42)
X_pca_raw = pca_raw.fit_transform(X_raw)
# SimCLR: PCA on latent features (as done in the paper)
pca_simclr = PCA(n_components=50, random_state=42)
X_pca_simclr = pca_simclr.fit_transform(X_simclr)
# Cluster both
km_raw = KMeans(n_clusters=K, random_state=42, n_init=10)
labels_raw = km_raw.fit_predict(X_pca_raw)
@@ -129,7 +141,6 @@ def stability_analysis(X_features):
all_labels.append(labels)
metrics_list.append(silhouette_score(X_pca, labels))
# Calculate ARI between all pairs of runs
ari_scores = []
for i in range(len(all_labels)):
for j in range(i + 1, len(all_labels)):
@@ -140,22 +151,18 @@ def stability_analysis(X_features):
def isotope_validation(X_features, mzs):
print("\n--- TASK 3: ISOTOPE CO-LOCALIZATION VALIDATION ---")
# Normalize features for distance calculation
X_norm = X_features / np.linalg.norm(X_features, axis=1, keepdims=True)
isotope_dist = []
random_dist = []
# Find isotopic pairs (Adjusted to allow for binned channel drift)
for i in range(len(mzs)):
for j in range(i + 1, len(mzs)):
diff = abs(mzs[i] - mzs[j])
if 0.95 <= diff <= 1.05: # Accommodates binned spacing variations
if 0.95 <= diff <= 1.05:
dist = np.linalg.norm(X_norm[i] - X_norm[j])
isotope_dist.append(dist)
# Sample random pairs (same number as isotopes)
if len(isotope_dist) > 0:
for _ in range(len(isotope_dist)):
idx1 = random.randint(0, len(mzs)-1)
@@ -171,9 +178,8 @@ def isotope_validation(X_features, mzs):
t_stat, p_val = ttest_ind(isotope_dist, random_dist)
print(f"T-test p-value: {p_val:.4e} (Significant if < 0.05)")
# Plotting
plt.figure(figsize=(8, 6))
plt.boxplot([isotope_dist, random_dist], labels=['Isotopic Pairs', 'Random Pairs'])
plt.boxplot([isotope_dist, random_dist], tick_labels=['Isotopic Pairs', 'Random Pairs'])
plt.title('Latent Space Distances: Isotopes vs Random')
plt.ylabel('Euclidean Distance (Normalized Latent Space)')
plt.savefig(os.path.join(BASE_DIR, "..", "figures", "isotope_validation_plot.png"))