Pythonでscikit-learn kmeansを使用してテキストドキュメントをクラスタリングする質問する

Pythonでscikit-learn kmeansを使用してテキストドキュメントをクラスタリングする質問する

実装する必要がある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"]

どのような変更が必要ですか?kMeans サンプルコードこのリストを入力として使用しますか? (単に「dataset = documents」とするだけでは機能しません)

ベストアンサー1

これはもっと簡単な例です:

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"]

テキストをベクトル化する、つまり文字列を数値特徴に変換する

vectorizer = TfidfVectorizer(stop_words='english')
X = vectorizer.fit_transform(documents)

クラスタードキュメント

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

クラスターごとに上位の用語を印刷する

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

これがどのように見えるかもっと視覚的に知りたい場合は、この答え

おすすめ記事