DrAmar commited on
Commit
52d8bf1
·
verified ·
1 Parent(s): 4205dc5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -53
app.py CHANGED
@@ -1,57 +1,104 @@
1
- import gradio as gr
2
  import pandas as pd
3
  import numpy as np
4
- import joblib
5
- import seaborn as sns
6
  import matplotlib.pyplot as plt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- # Load saved models
9
- imputer = joblib.load("imputer.pkl")
10
- scaler = joblib.load("scaler.pkl")
11
- tsne = joblib.load("tsne.pkl")
12
- columns_to_transform = joblib.load("columns.pkl")
13
-
14
- # Function to process test data
15
- def process_data(file):
16
- try:
17
- # Load test data
18
- test_df = pd.read_excel(file.name)
19
-
20
- # Ensure correct columns
21
- if set(test_df.columns) != set(columns_to_transform):
22
- return "ERROR: Incorrect columns. Ensure data has only these columns: " + ", ".join(columns_to_transform), None
23
-
24
- # Apply log transformation
25
- test_df[columns_to_transform] = test_df[columns_to_transform].apply(lambda x: np.log1p(x))
26
-
27
- # Preprocess (impute, scale)
28
- X_test = imputer.transform(test_df[columns_to_transform])
29
- X_test_scaled = scaler.transform(X_test)
30
-
31
- # Apply trained t-SNE model
32
- X_test_tsne = tsne.fit_transform(X_test_scaled)
33
-
34
- # Plot t-SNE
35
- plt.figure(figsize=(8, 6))
36
- plt.scatter(X_test_tsne[:, 0], X_test_tsne[:, 1], color='red', label='Test Data', alpha=0.7)
37
- plt.xlabel('t-SNE Component 1')
38
- plt.ylabel('t-SNE Component 2')
39
- plt.legend()
40
- plt.title('t-SNE Visualization')
41
- plt.tight_layout()
42
- tsne_fig = plt.gcf()
43
-
44
- return tsne_fig
45
-
46
- except Exception as e:
47
- return str(e)
48
-
49
- # Gradio UI
50
- with gr.Blocks() as demo:
51
- gr.Markdown("## Upload Geochemical Test Data")
52
- file_input = gr.File(label="Upload Test Data (.xlsx)")
53
- output = gr.Plot(label="t-SNE Visualization")
54
- file_input.change(process_data, inputs=file_input, outputs=output)
55
-
56
- if __name__ == "__main__":
57
- demo.launch(share=True)
 
 
1
  import pandas as pd
2
  import numpy as np
 
 
3
  import matplotlib.pyplot as plt
4
+ import seaborn as sns
5
+ from sklearn.impute import SimpleImputer
6
+ from sklearn.preprocessing import StandardScaler
7
+ from sklearn.manifold import TSNE
8
+ import gradio as gr
9
+ import os
10
+
11
+ # --- Load Precomputed Training t-SNE Data ---
12
+ training_tsne_path = "training_tsne.xlsx" # Ensure this file is uploaded to Hugging Face
13
+
14
+ if os.path.exists(training_tsne_path):
15
+ training_tsne_df = pd.read_excel(training_tsne_path)
16
+ print("Training t-SNE data loaded successfully!")
17
+ else:
18
+ training_tsne_df = None
19
+ print("Error: training_tsne.xlsx not found. Please upload it.")
20
+
21
+ # Feature columns used for log transformation
22
+ columns_to_transform = ['Mn', 'Co', 'Ni', 'Cu', 'Zn', 'As', 'Se', 'Mo', 'Ag', 'Cd', 'Sb', 'Te', 'Tl', 'Pb', 'Bi']
23
+
24
+ # Define global preprocessing objects (to ensure test data uses the same transformation as training)
25
+ imputer = SimpleImputer(strategy='mean')
26
+ scaler = StandardScaler()
27
+
28
+ def process_test_data(test_file):
29
+ """
30
+ Load and preprocess test data.
31
+ Assumes test data has the same feature columns as training.
32
+ """
33
+ test_df = pd.read_excel(test_file.name)
34
+
35
+ # Ensure all required columns exist
36
+ missing_columns = [col for col in columns_to_transform if col not in test_df.columns]
37
+ if missing_columns:
38
+ return f"Error: Missing columns in the uploaded data: {', '.join(missing_columns)}"
39
+
40
+ # Apply log transformation
41
+ test_df[columns_to_transform] = np.log1p(test_df[columns_to_transform])
42
+
43
+ # Apply the same imputer and scaler as training (fit on test data)
44
+ X_test_imputed = imputer.fit_transform(test_df[columns_to_transform])
45
+ X_test_scaled = scaler.fit_transform(X_test_imputed)
46
+
47
+ return X_test_scaled
48
+
49
+ def visualize_tsne_interface(test_file):
50
+ """
51
+ Compute the t-SNE embedding for the test data,
52
+ load the saved training t-SNE data,
53
+ and overlay the test points on the training plot.
54
+ """
55
+ if training_tsne_df is None:
56
+ return "Error: Training t-SNE data not found. Please upload `training_tsne.xlsx`."
57
+
58
+ # Preprocess the uploaded test data
59
+ X_test_scaled = process_test_data(test_file)
60
+ if isinstance(X_test_scaled, str):
61
+ return X_test_scaled # Return error message if preprocessing failed
62
+
63
+ # Compute t-SNE embedding for test data
64
+ tsne_test = TSNE(n_components=2, random_state=42)
65
+ X_tsne_test = tsne_test.fit_transform(X_test_scaled)
66
+
67
+ # Create the plot
68
+ plt.figure(figsize=(10, 7))
69
+
70
+ # Plot training data t-SNE with color-coded labels
71
+ sns.scatterplot(data=training_tsne_df,
72
+ x='x',
73
+ y='y',
74
+ hue='label',
75
+ palette=sns.color_palette("hsv", len(training_tsne_df['label'].unique())),
76
+ legend='full',
77
+ alpha=0.6)
78
+
79
+ # Overlay the test data points (using black 'x' markers)
80
+ plt.scatter(X_tsne_test[:, 0], X_tsne_test[:, 1],
81
+ c='black', label='Test Data', marker='x')
82
+
83
+ # Customize the plot
84
+ plt.title('t-SNE Visualization: Training Data with Test Data Points')
85
+ plt.xlabel('t-SNE Component 1')
86
+ plt.ylabel('t-SNE Component 2')
87
+ plt.legend(title='Class Labels')
88
+
89
+ # Save and return the plot image file
90
+ output_file = "tsne_overlay.png"
91
+ plt.savefig(output_file)
92
+ plt.close() # Close the plot to avoid overlap on subsequent calls
93
+ return output_file
94
+
95
+ # Create and launch the Gradio interface
96
+ iface = gr.Interface(
97
+ fn=visualize_tsne_interface,
98
+ inputs=gr.File(label="Upload Test Data Excel File"),
99
+ outputs=gr.Image(type="filepath", label="t-SNE Plot"),
100
+ title="t-SNE Overlay Visualization",
101
+ description="Upload an Excel file with test data. Ensure the file includes the same feature columns used in the training data."
102
+ )
103
 
104
+ iface.launch()