我想在我的脚本中使用轮廓分数,以自动计算来自 sklearn 的 k-means 聚类中的聚类数。
import numpy as np
import pandas as pd
import csv
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
filename = "CSV_BIG.csv"
# Read the CSV file with the Pandas lib.
path_dir = ".\\"
dataframe = pd.read_csv(path_dir + filename, encoding = "utf-8", sep = ';' ) # "ISO-8859-1")
df = dataframe.copy(deep=True)
#Use silhouette score
range_n_clusters = list (range(2,10))
print ("Number of clusters from 2 to 9: \n", range_n_clusters)
for n_clusters in range_n_clusters:
clusterer = KMeans (n_clusters=n_clusters).fit(?)
preds = clusterer.predict(?)
centers = clusterer.cluster_centers_
score = silhouette_score (?, preds, metric='euclidean')
print ("For n_clusters = {}, silhouette score is {})".format(n_clusters, score)
有人可以帮我打问号吗?我不明白该放什么而不是问号。我从一个例子中获取了代码。注释的部分是之前的版本,这里我用固定的簇数设置为4进行k-means聚类。这种方式的代码是正确的,但是在我的项目中我需要自动选择簇的数量。