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
+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})