NauRaa/Gene_Expression_Clustering_App
0
1import gradio as gr
2import pandas as pd
3import joblib
4import numpy as np
5
6# ===========================
7# Load Saved Model & Objects
8# ===========================
9model = joblib.load("best_cluster_model.joblib")
10pca = joblib.load("pca_transform.joblib")
11scaler = joblib.load("scaler.joblib")
12selector = joblib.load("selector.joblib")
13
14# ===========================
15# Prediction Function
16# ===========================
17def predict_clusters(file):
18 try:
19 df = pd.read_csv(file.name)
20 except Exception as e:
21 return f"❌ Error loading file: {e}"
22
23 # Drop non-numeric columns
24 df = df.select_dtypes(include=[np.number])
25
26 if df.empty:
27 return "❌ No numeric columns found in the dataset."
28
29 # 🔧 Remove unseen columns (like 'Cluster')
30 df = df.loc[:, [c for c in df.columns if c in selector.feature_names_in_]]
31
32 # Feature selection
33 X_selected = selector.transform(df)
34
35 # Scaling
36 X_scaled = scaler.transform(X_selected)
37
38 # PCA transformation
39 X_pca = pca.transform(X_scaled)
40
41 # Prediction
42 try:
43 labels = model.predict(X_pca)
44 except:
45 labels = model.fit_predict(X_pca)
46
47 # Create output dataframe
48 df_out = pd.DataFrame({
49 "PC1": X_pca[:, 0],
50 "PC2": X_pca[:, 1],
51 "Cluster": labels
52 })
53
54 return df_out
55
56# ===========================
57# Gradio Interface
58# ===========================
59interface = gr.Interface(
60 fn=predict_clusters,
61 inputs=gr.File(label="📂 Upload your gene expression CSV file"),
62 outputs=gr.Dataframe(label="🧬 Clustered Results (PCA + Cluster)"),
63 title="🧫 Gene Expression Clustering App",
64 description="Upload a gene expression CSV file. The app will perform scaling, PCA, and clustering using the trained unsupervised model."
65)
66
67if __name__ == "__main__":
68 interface.launch()
69 