我想将剪影分数附加到循环中的列表中。
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