Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
from sklearn.cluster import KMeans
|
| 5 |
+
|
| 6 |
+
def cluster_plot(data_text, n_clusters):
|
| 7 |
+
try:
|
| 8 |
+
# Parse user input
|
| 9 |
+
# Expect input like: [[1,30],[2,32],[1.5,31],[5,60]]
|
| 10 |
+
X = np.array(eval(data_text))
|
| 11 |
+
if X.ndim != 2 or X.shape[1] != 2:
|
| 12 |
+
return " Please enter a 2D list with two columns (e.g. [[1,30],[2,32],[3,35]])", None
|
| 13 |
+
|
| 14 |
+
# KMeans clustering
|
| 15 |
+
kmeans = KMeans(n_clusters=n_clusters, random_state=0)
|
| 16 |
+
labels = kmeans.fit_predict(X)
|
| 17 |
+
centroids = kmeans.cluster_centers_
|
| 18 |
+
|
| 19 |
+
# Plot scatter
|
| 20 |
+
plt.figure(figsize=(6,4))
|
| 21 |
+
plt.scatter(X[:,0], X[:,1], c=labels, s=80, cmap='rainbow', edgecolors='k', alpha=0.8)
|
| 22 |
+
plt.scatter(centroids[:,0], centroids[:,1], c='black', s=150, marker='X', label='Centroids')
|
| 23 |
+
plt.xlabel("Years of Experience")
|
| 24 |
+
plt.ylabel("Salary")
|
| 25 |
+
plt.title("KMeans Clustering")
|
| 26 |
+
plt.legend()
|
| 27 |
+
plt.grid(True)
|
| 28 |
+
|
| 29 |
+
# Return plot
|
| 30 |
+
return f" Cluster labels: {labels.tolist()}", plt.gcf()
|
| 31 |
+
|
| 32 |
+
except Exception as e:
|
| 33 |
+
return f" Error: {e}", None
|
| 34 |
+
|
| 35 |
+
# Gradio interface
|
| 36 |
+
demo = gr.Interface(
|
| 37 |
+
fn=cluster_plot,
|
| 38 |
+
inputs=[
|
| 39 |
+
gr.Textbox(
|
| 40 |
+
label="Enter 2D Array (Experience vs Salary)",
|
| 41 |
+
placeholder="Example: [[1,30],[2,32],[1.5,31],[5,60],[10,100]]"
|
| 42 |
+
),
|
| 43 |
+
gr.Slider(2, 10, value=3, step=1, label="Number of Clusters")
|
| 44 |
+
],
|
| 45 |
+
outputs=[
|
| 46 |
+
gr.Textbox(label="Result"),
|
| 47 |
+
gr.Plot(label="Cluster Plot")
|
| 48 |
+
],
|
| 49 |
+
title="KMeans Clustering Visualizer",
|
| 50 |
+
description="Enter a 2D array of points and choose the number of clusters to see the scatter plot."
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
demo.launch()
|