1

我想将剪影分数附加到循环中的列表中。

        from sklearn.cluster import KMeans
        from sklearn.metrics import silhouette_score

        ks = range(1, 11) # for 1 to 10 clusters
        #sse = []
        sil = []

        for k in ks:
             # Create a KMeans instance with k clusters: model
             kmeans = KMeans(n_clusters = k)
             # Fit model to samples
             #kmeans.fit(X)
             cluster_labels = kmeans.fit_predict(X) #X is dataset that preprocess already.
             silhouette = silhouette_score(X, cluster_labels)


             # Append the inertia to the list of inertias
             #sse.append(kmeans.inertia_)

             #Append silhouette to the list
             sil.append(silhouette)

但是,当我使用 silhouette_score 设置剪影时,我在第 21 行收到以下错误

       ValueError                   Traceback (most recent call last)
       <ipython-input-12-2570ccf62502> in <module>()
       18     #kmeans.fit(X)
       19     cluster_labels = kmeans.fit_predict(X)
   --->20     silhouette = silhouette_score(X, cluster_labels)
       21 
       22 
4

2 回答 2

1

from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples, silhouette_score
  
X, y = make_blobs(n_samples=500,
                  n_features=2,
                  centers=4,
                  cluster_std=1,
                  center_box=(-10.0, 10.0),
                  shuffle=True,
                  random_state=1) 
sil=[]
#start the cluster range from 2
range_n_clusters = range(2,10)

for n_clusters in range_n_clusters:
    clusterer = KMeans(n_clusters=n_clusters, random_state=10)
    cluster_labels = clusterer.fit_predict(X)
    silhouette_avg = silhouette_score(X, cluster_labels)
    print("For n_clusters =", n_clusters,
          "The average silhouette_score is :", silhouette_avg)
    sil.append(silhouette_avg)

这是一个将 Kmeans 聚类应用于随机样本并根据轮廓分数找到最佳聚类的示例。我认为这会对您有所帮助或请提供更多信息 在此处输入图像描述

于 2019-11-10T09:47:11.127 回答
0

这是整个代码还是其中的一部分?如果在此之前没有代码,那么很明显X在分配之前没有定义或使用。

因此,将行放置在您分配的位置X,事情应该可以正常工作。

否则,请将完整的跟踪添加到错误中

于 2019-11-10T09:08:14.440 回答