kmeans.py 2.2 KB
Newer Older
F
feilong 已提交
1
# -*- coding: UTF-8 -*-
F
feilong 已提交
2
# 作者:huanhuilong
F
feilong 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
# 标题:SK-Learn HelloWorld
# 描述:使用 TF-IDF+Kmeans 对文本聚类


from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import TfidfTransformer, TfidfVectorizer
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import random


def plot_result(data, cluster_res, cluster_num, algorithm='None'):
    nPoints = len(data)
    scatter_colors = ['blue', 'green', 'yellow',
                      'red', 'purple', 'orange', 'brown']
    for i in range(cluster_num):
        color = scatter_colors[i % len(scatter_colors)]
        x1 = []
        y1 = []
        for j in range(nPoints):
            if cluster_res[j] == i:
                x1.append(data[j, 0])
                y1.append(data[j, 1])
        plt.scatter(x1, y1, c=color, alpha=1, marker='o')
        plt.plot(marksize=10)
    plt.savefig('/tmp/' + algorithm + '-' +
                str(random.randint(10, 100)) + str(cluster_num) + '.png')
    plt.show()


def kmeans(sentences, num_of_class):
    # tfidf 向量化
    vertorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.46)
    transformer = TfidfTransformer()
    freq_words_matrix = vertorizer.fit_transform(sentences)

    # 获取词袋
    words = vertorizer.get_feature_names()
    tfidf = transformer.fit_transform(freq_words_matrix)
    weight = freq_words_matrix.toarray()
    trainingData = weight

    # K-Means 聚类
    clf = KMeans(
        n_clusters=num_of_class,
        max_iter=10000,
        init="k-means++",
        tol=1e-6
    )
    result = clf.fit(trainingData)
    source = list(clf.predict(trainingData))
    labels = clf.labels_

    # # 显示聚类结果
    plot_result(trainingData, source, num_of_class)


if __name__ == "__main__":
    sentences = [
        '今天 天气 很 好',
        '今天很 好',
        '今天 天气 很 好',
        '今天 天气 很 好',
        '今天 天',
        '今天 天气 很 好',
        '今天 天气 很 好',
        '今天 天气 很 好',
        '今天 天气 很 好',
        '今天 天',
        '今天 天气 很 好',
        '气 很 好',
        '今天 天气 很 差',
        '不错',
        '还行'
    ]

    kmeans(sentences, 3)