首页 > 解决方案 > 使用 Bokeh 和 Python 创建集群可视化;选择输入更改时绘图不更新

问题描述

我正在尝试创建一个交互式仪表板功能,我可以在其中选择一个集群算法,从而相应地更改绘图输出。但是,当我尝试更改聚类算法时,图并没有改变。

请注意,我从之前提出的一个问题中得到了很多帮助,但我觉得开始一个新帖子是合适的:Python 和 Bokeh 上的集群;选择允许用户更改聚类算法的小部件

这是迄今为止的代码: -

''' Example inspired by an example from the scikit-learn project:
http://scikit-learn.org/stable/auto_examples/cluster/plot_cluster_comparison.html
'''
#https://github.com/bokeh/bokeh/blob/branch-2.4/examples/webgl/clustering.py
from bokeh.models.annotations import Label
import numpy as np
from sklearn import cluster, datasets
from sklearn.preprocessing import StandardScaler

from bokeh.layouts import column, row
from bokeh.plotting import figure, output_file, show
from bokeh.models import CustomJS, Select
print("\n\n*** This example may take several seconds to run before displaying. ***\n\n")

N = 50000
PLOT_SIZE = 400

# generate datasets.
np.random.seed(0)
noisy_circles = datasets.make_circles(n_samples=N, factor=.5, noise=.04)
noisy_moons = datasets.make_moons(n_samples=N, noise=.05)
centers = [(-2, 3), (2, 3), (-2, -3), (2, -3)]
blobs1 = datasets.make_blobs(centers=centers, n_samples=N, cluster_std=0.4, random_state=8)
blobs2 = datasets.make_blobs(centers=centers, n_samples=N, cluster_std=0.7, random_state=8)

colors = np.array([x for x in ('#00f', '#0f0', '#f00', '#0ff', '#f0f', '#ff0')])
colors = np.hstack([colors] * 20)

# create clustering algorithms
dbscan   = cluster.DBSCAN(eps=.2)
birch    = cluster.Birch(n_clusters=2)
means    = cluster.MiniBatchKMeans(n_clusters=2)
spectral = cluster.SpectralClustering(n_clusters=2, eigen_solver='arpack', affinity="nearest_neighbors")
affinity = cluster.AffinityPropagation(damping=.9, preference=-200)
kmeans   = cluster.KMeans(n_clusters=2)

#menu     =[('DBSCAN','dbscan'),('Birch','birch'),('MiniBatchKmeans','means'),('Spectral','spectral'),('Affinity','affinity'),('K-means','kmeans')]
menu     =[('dbscan','DBSCAN'),('birch', 'Birch'), ('means','MiniBatchKmeans'),('spectral','Spectral'),('affinity','Affinity'), ('kmeans','Kmeans')]

select = Select(title="Option:", value="DBSCAN", options=menu)

select.js_on_change("value", CustomJS(code="""
    console.log('select: value=' + this.value, this.toString())
"""))
# change here, to select clustering algorithm (note: spectral is slow)
#algorithm = select.value  

algorithm = None

if select.value == 'DBSCAN':
    algorithm = dbscan # use dbscan algorithm function
elif select.value == 'Birch':
      algorithm = birch  # use birch algorithm function
elif select.value == 'MiniBatchKmeans':
      algorithm = means  # use means algorithm function
elif select.value == 'Spectral':
      algorithm = spectral
elif select.value == 'Affinity':
      algorithm = affinity
elif select.value == 'Kmeans':
      algorithm = kmeans




if algorithm is not None:
    plots =[]
    for dataset in (noisy_circles, noisy_moons, blobs1, blobs2):
        X, y = dataset
        X = StandardScaler().fit_transform(X)

        algorithm.fit(X)
        if hasattr(algorithm, 'labels_'):
            y_pred = algorithm.labels_.astype(int)
        else:
            y_pred = algorithm.predict(X)
        p = figure(output_backend="webgl", title=algorithm.__class__.__name__,width=PLOT_SIZE, height=PLOT_SIZE)
        p.circle(X[:, 0], X[:, 1], color=colors[y_pred].tolist(), alpha=0.1,)
        plots.append(p)
else:
   print('Please select an algorithm first')
    






# generate layout for the plots
layout = column(select,row(plots[:2]), row(plots[2:]))
#layout = column(row(plots[:2]), row(plots[2:]))
output_file("clustering.html", title="clustering with sklearn")

show(layout)

我有一种感觉,这与

select.js_on_change("value", CustomJS(code="""
    console.log('select: value=' + this.value, this.toString())
"""))

但我不确定我应该修改什么。任何指针?

提前致谢 :)

标签: pythonscikit-learnwidgetdata-visualizationbokeh

解决方案


推荐阅读