【问题标题】:Is there a way to find the data points in a K-means Cluster from SciKit-Learn?有没有办法从 SciKit-Learn 中找到 K-means 集群中的数据点?
【发布时间】:2020-08-22 21:53:58
【问题描述】:

我有一个数据集,其中包含来自鸟类观察者的 cmets。我使用 TF-IDF 矢量化器将文本 cmets 转换为矢量特征,然后运行 ​​K-means 聚类将我的数据分成簇。我有一组清晰的集群。但是,我一直在尝试找到一种方法来找出哪些单词进入了哪些集群。我知道如何获取特征标签/名称,但我想查看每个特征下的实际数据点,然后将它们转换回原始单词。我正在使用 Python 和 Scikit-Learn 的 K-means 算法。

def final_k_model(X, finalk):
    final_k_mod = KMeans(n_clusters=finalk, init='random', n_init=10, max_iter=300, tol=1e-04, random_state=0)
    final_k_mod.fit(X)

    # plot the results:
    centroids = final_k_mod.cluster_centers_

    tsne_init = 'pca'
    tsne_perplexity = 20.0
    tsne_early_exaggeration = 4.0
    tsne_learning_rate = 1000
    random_state = 1
    tsnemodel = TSNE(n_components=2, random_state=random_state, init=tsne_init, perplexity=tsne_perplexity,
                 early_exaggeration=tsne_early_exaggeration, learning_rate=tsne_learning_rate)

    transformed_centroids = tsnemodel.fit_transform(centroids)

    plt.figure(1)
    plt.scatter(transformed_centroids[:, 0], transformed_centroids[:, 1], marker='x')
    plt.savefig('plots\\cluster.png')
    plt.show()

    return final_k_mod

我包含了一些代码,但不确定它是否有帮助,因为我没有错误。我只是想弄清楚这是否可能,我一直在谷歌搜索并查看教程但没有找到。

【问题讨论】:

  • 下一次,请花一分钟看看如何格式化你的代码(这次为你完成了)。

标签: python scikit-learn k-means


【解决方案1】:

假设您通过以下方法计算代码中的 X,

#corpus = list of all documents
#vocab = list of all words in corpus
tdf_idf = TfidfVectorizer(vocabulary=vocab)
X = tdf_idf.fit_transform(corpus)

您正在寻找以下内容吗?

for centroid in centroids:
    score_this_centroid = {}
    for word in tdf_idf.vocabulary_.keys():
        score_this_centroid[word] = centroid[tdf_idf.vocabulary_[word]]
        pass

【讨论】:

  • 谢谢,这有帮助!我试图投票赞成你的答案,但我认为我太新了。 :(
猜你喜欢
  • 1970-01-01
  • 2017-09-19
  • 1970-01-01
  • 2019-11-26
  • 1970-01-01
  • 2019-01-21
  • 2017-10-13
  • 2013-10-12
  • 2017-03-11
相关资源
最近更新 更多