Spaces:
Runtime error
Runtime error
import numpy as np | |
import matplotlib.pyplot as plt | |
from sklearn.cluster import AgglomerativeClustering | |
from sklearn.neighbors import kneighbors_graph | |
import gradio as gr | |
np.random.seed(42) | |
def agglomorative_cluster(n_samples: int, n_neighbours: int, n_clusters: int, linkage: str, connectivity: bool) -> "plt.Figure": | |
t = 1.5 * np.pi * (1 + 3 * np.random.rand(1, n_samples)) | |
x = t * np.cos(t) | |
y = t * np.sin(t) | |
X = np.concatenate((x, y)) | |
X += 0.7 * np.random.randn(2, n_samples) | |
X = X.T | |
knn_graph = kneighbors_graph(X, n_neighbors=n_neighbours, include_self=False) | |
connectivity = knn_graph if not connectivity else None | |
fig, ax = plt.subplots(1, 1, figsize=(24, 15)) | |
model = AgglomerativeClustering(linkage=linkage, connectivity=connectivity, n_clusters=int(n_clusters)) | |
model.fit(X) | |
ax.scatter(X[:, 0], X[:, 1], c=model.labels_, cmap=plt.cm.nipy_spectral) | |
ax.axis("equal") | |
ax.axis("off") | |
return fig | |
demo = gr.Interface( | |
fn = agglomorative_cluster, | |
inputs = [gr.Slider(0, 20_000, label="n_samples", info="the number of samples in the data.", step=1), | |
gr.Slider(0, 30, label="n_neighbours", info="the number of neighbours in the data", step=1), | |
gr.Dropdown([3, 30], label="n_clusters", info="the number of clusters in the data"), | |
gr.Dropdown(['average', 'complete', 'ward', 'single'], label="linkage", info="the different types of aggolomorative clustering techniques"), | |
gr.Checkbox(True, label="connectivity", info="whether to impose a connectivity into the graph")], | |
outputs = [gr.Plot(label="Plot")] | |
) | |
demo.launch() | |