为什么silhouette_score总是在这个Iris数据集上返回0?

时间:2018-06-16 18:12:37

标签: python matplotlib scikit-learn k-means

我正在测试Scikitlearn的一些功能,虽然他们的example对我来说很好并且返回一个剪影数字,当我在Iris数据集上做等效时它会显示一个聚类,然后总是输出0平均轮廓:

from sklearn import datasets
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples, silhouette_score
import matplotlib.pyplot as plt

iris = datasets.load_iris()

print(dir(iris))
print(iris.DESCR)
#print(iris.data[:,1:3]) second and third part of each, columns.
X = iris.data[:, 1:3]

for i in range(2,11):
    model = KMeans(n_clusters=i, random_state=0)
    model.fit(X)
    #print(model.labels_) #Different number for each "cluster" found.
    centroids = model.cluster_centers_
    #Separate xs [:, 0], ys [:,1] and scatter plot:
    plt.scatter(centroids[:, 0], centroids[:, 1], marker='x', s=170, zorder=10, c='m')
    plt.scatter(X[:, 0], X[:, 1], c=model.labels_)
    #print(plt.scatter.__doc__) # <--- what are the arguments?
    plt.xlabel("Sepal width")
    plt.ylabel("Petal length")
    print(X)
    print(model.labels_)
    print('For %d clusters the average silhouette score is %d' % (i, silhouette_score(X, model.labels_)))
    plt.show()

为什么它会这样做,因为它似乎给它一个类似的X数组和标签作为Scikit示例?

1 个答案:

答案 0 :(得分:2)

将print语句切换为:

print('For %f clusters the average silhouette score is %f' % (i, silhouette_score(X, model.labels_)))

或者:

print('For {} clusters the average silhouette score is {}'.format(i, silhouette_score(X, model.labels_)))

或者:

print(f"For {i} clusters the average silhouette score is {silhouette_score(X, model.labels_)}")

...解决了这个问题。

如@shahaf在评论中所述,您正在从float转换为int(%d)。