在Python和Bokeh上进行聚类;选择允许用户更改聚类算法的小部件

问题描述

我正在尝试在Bokeh仪表板中构建一个功能,该功能允许用户对数据进行集群。我使用以下示例作为模板,以下是链接:- Clustering in Bokeh example

以下是本例中的代码:-

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

print("

*** This example may take several seconds to run before displaying. ***

")

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)

# change here, to select clustering algorithm (note: spectral is slow)
algorithm = dbscan  # <- SELECT ALG

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

    # predict cluster memberships
    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)

# generate layout for the plots
layout = column(row(plots[:2]), row(plots[2:]))

output_file("clustering.html", title="clustering with sklearn")

show(layout)

该示例允许用户对数据进行群集。在代码中,您可以指定要使用的算法;在上面粘贴的代码中,算法是dbscan。我尝试修改代码,以便可以添加允许用户指定要使用的算法的小部件:-


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("

*** This example may take several seconds to run before displaying. ***

")

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)

############################select widget for different clustering algorithms############


menu     =[('DBSCAN','dbscan'),('Birch','birch'),('MiniBatchKmeans','means'),('Spectral','spectral'),('Affinity','affinity'),('K-means','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  

############################################################
plots =[]
for dataset in (noisy_circles, noisy_moons, blobs1, blobs2):
    X, y = dataset
    X = StandardScaler().fit_transform(X)

    # predict cluster memberships
    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)

# generate layout for the plots
layout = column(select,row(plots[:2]), row(plots[2:]))

output_file("clustering.html", title="clustering with sklearn")

show(layout)

但是,当我尝试运行它时收到此错误:-

AttributeError: 'str' object has no attribute 'fit'

有人能告诉我为了修复此问题我遗漏了什么吗?

此外,如果不是太难做到的话,我还想添加一个数字输入小部件,它允许用户选择要查找的每个算法的聚类数。建议?

非常感谢:)

编辑

以下是@Tony解决方案的代码的当前状态。

''' 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("

*** This example may take several seconds to run before displaying. ***

")

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')]
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 == 'means':
      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)

    # predict cluster memberships
    algorithm.fit(X)           ######################This is what appears to be the problem######################
    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:]))

output_file("clustering.html", title="clustering with sklearn")

show(layout)
请参见algorithm.fit(X)这就是错误发生的地方。 错误消息:-

AttributeError: 'NoneType' object has no attribute 'fit'
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
m:okehdashclusteringbokeh.py in 
     67 
     68     # predict cluster memberships
---> 69     algorithm.fit(X)
     70     if hasattr(algorithm, 'labels_'):
     71         y_pred = algorithm.labels_.astype(int)

AttributeError: 'NoneType' object has no attribute 'fit'

解决方案

我不知道sklearn但将您的两个示例进行比较,我可以看到以下内容:

  1. Select是具有value类型string属性的Bokeh模型。因此select.value是字符串
  2. dbscan是算法函数
因此,当您执行algorithm = dbscan操作时,您为algorithm变量分配了一个算法函数,而在第二个示例中,您只为它分配了一个字符串,因此它将无法工作,因为string没有fit()函数。您应该这样做:

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
etc...

if algorithm is not None:
    plots =[]
    for dataset in (noisy_circles, noisy_moons, blobs1, blobs2):
        ...
else:
   print('Please select an algorithm first')

相关文章