【问题标题】:How to use silhouette score in k-means clustering from sklearn library?如何在 sklearn 库的 k-means 聚类中使用轮廓分数?
【发布时间】:2018-12-10 19:55:06
【问题描述】:

我想在我的脚本中使用轮廓分数,以自动计算来自 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)

有人可以帮我打问号吗?我不明白该放什么而不是问号。我从一个例子中获取了代码。 注释的部分是之前的版本,我做k-means聚类,固定簇数设置为4。这种方式的代码是正确的,但是在我的项目中我需要自动选择簇数。

【问题讨论】:

  • 不幸的是,剪影在单集群数据集上存在很大问题。因为这个指标不负责单个集群问题。如果您的问题仍然存在,您可以尝试this

标签: python-2.7 machine-learning scikit-learn k-means silhouette


【解决方案1】:

那个?是您应用 K-means 的数据集或数据框。 谢谢。

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

我假设您要计算分数以获得最佳编号。的簇。

首先声明KMeans 的单独对象,然后像这样在您的数据df 上调用它的fit_predict 函数

for n_clusters in range_n_clusters:
    clusterer = KMeans(n_clusters=n_clusters)
    preds = clusterer.fit_predict(df)
    centers = clusterer.cluster_centers_

    score = silhouette_score(df, preds)
    print("For n_clusters = {}, silhouette score is {})".format(n_clusters, score))

请参阅this official example 了解更多信息。

【讨论】:

    猜你喜欢
    • 2017-11-20
    • 2014-07-04
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 2018-09-30
    • 2015-12-10
    相关资源
    最近更新 更多