Clustering text documents using scikit-learn kmeans in Python

后端 未结 1 827
Happy的楠姐
Happy的楠姐 2020-11-28 21:23

I need to implement scikit-learn\'s kMeans for clustering text documents. The example code works fine as it is but takes some 20newsgroups data as input. I want to use the s

1条回答
  •  离开以前
    2020-11-28 21:52

    This is a simpler example:

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

    vectorize the text i.e. convert the strings to numeric features

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

    cluster 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 clusters

    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
    

    If you want to have a more visual idea of how this looks like see this answer.

    0 讨论(0)
提交回复
热议问题