使用Python中的scikit-learn kmeans对文本文档进行聚类

Nab*_*hid 23 python cluster-analysis k-means python-2.7 scikit-learn

我需要实现scikit-learn的kMeans来集群文本文档.该示例代码工作正常,因为它只是需要一些20newsgroups数据作为输入.我想使用相同的代码来集群文档列表,如下所示:

documents = ["Human machine interface for lab abc computer applications",
             "A survey of user opinion of computer system response time",
             "The EPS user interface management system",
             "System and human system engineering testing of EPS",
             "Relation of user perceived response time to error measurement",
             "The generation of random binary unordered trees",
             "The intersection graph of paths in trees",
             "Graph minors IV Widths of trees and well quasi ordering",
             "Graph minors A survey"]
Run Code Online (Sandbox Code Playgroud)

kMeans示例代码中我需要做哪些更改才能使用此列表作为输入?(简单地说'dataset = documents'不起作用)

ely*_*ase 65

这是一个更简单的例子:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score

documents = ["Human machine interface for lab abc computer applications",
             "A survey of user opinion of computer system response time",
             "The EPS user interface management system",
             "System and human system engineering testing of EPS",
             "Relation of user perceived response time to error measurement",
             "The generation of random binary unordered trees",
             "The intersection graph of paths in trees",
             "Graph minors IV Widths of trees and well quasi ordering",
             "Graph minors A survey"]
Run Code Online (Sandbox Code Playgroud)

矢量化文本即将字符串转换为数字特征

vectorizer = TfidfVectorizer(stop_words='english')
X = vectorizer.fit_transform(documents)
Run Code Online (Sandbox Code Playgroud)

集群文件

true_k = 2
model = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1)
model.fit(X)
Run Code Online (Sandbox Code Playgroud)

打印每个群集群的顶级术语

print("Top terms per cluster:")
order_centroids = model.cluster_centers_.argsort()[:, ::-1]
terms = vectorizer.get_feature_names()
for i in range(true_k):
    print "Cluster %d:" % i,
    for ind in order_centroids[i, :10]:
        print ' %s' % terms[ind],
    print
Run Code Online (Sandbox Code Playgroud)

如果你想更直观地了解它的外观,请看这个答案.