python - 如何可视化用于 kmeans 聚类的 tf-idf 向量的数据点?

标签 python scipy scikit-learn k-means tf-idf

我有一个文档列表和整个语料库中每个唯一单词的 tf-idf 分数。 我如何在二维图上将其可视化,以便衡量运行 k-means 需要多少集群?

这是我的代码:

sentence_list=["Hi how are you", "Good morning" ...]
vectorizer=TfidfVectorizer(min_df=1, stop_words='english', decode_error='ignore')
vectorized=vectorizer.fit_transform(sentence_list)
num_samples, num_features=vectorized.shape
print "num_samples:  %d, num_features: %d" %(num_samples,num_features)
num_clusters=10

如您所见,我能够将句子转换为 tf-idf 文档矩阵。但我不确定如何绘制 tf-idf 分数的数据点。

我在想:

  1. 添加更多变量,如文档长度等
  2. 执行 PCA 以获得二维输出

谢谢

最佳答案

我目前正在做类似的事情,试图在二维中绘制文本数据集的 tf-idf 分数。与其他评论中的建议类似,我的方法是使用 scikit-learn 中的 PCA 和 t-SNE。

import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE

num_clusters = 10
num_seeds = 10
max_iterations = 300
labels_color_map = {
    0: '#20b2aa', 1: '#ff7373', 2: '#ffe4e1', 3: '#005073', 4: '#4d0404',
    5: '#ccc0ba', 6: '#4700f9', 7: '#f6f900', 8: '#00f91d', 9: '#da8c49'
}
pca_num_components = 2
tsne_num_components = 2

# texts_list = some array of strings for which TF-IDF is being computed

# calculate tf-idf of texts
tf_idf_vectorizer = TfidfVectorizer(analyzer="word", use_idf=True, smooth_idf=True, ngram_range=(2, 3))
tf_idf_matrix = tf_idf_vectorizer.fit_transform(texts_list)

# create k-means model with custom config
clustering_model = KMeans(
    n_clusters=num_clusters,
    max_iter=max_iterations,
    precompute_distances="auto",
    n_jobs=-1
)

labels = clustering_model.fit_predict(tf_idf_matrix)
# print labels

X = tf_idf_matrix.todense()

# ----------------------------------------------------------------------------------------------------------------------

reduced_data = PCA(n_components=pca_num_components).fit_transform(X)
# print reduced_data

fig, ax = plt.subplots()
for index, instance in enumerate(reduced_data):
    # print instance, index, labels[index]
    pca_comp_1, pca_comp_2 = reduced_data[index]
    color = labels_color_map[labels[index]]
    ax.scatter(pca_comp_1, pca_comp_2, c=color)
plt.show()



# t-SNE plot
embeddings = TSNE(n_components=tsne_num_components)
Y = embeddings.fit_transform(X)
plt.scatter(Y[:, 0], Y[:, 1], cmap=plt.cm.Spectral)
plt.show()

关于python - 如何可视化用于 kmeans 聚类的 tf-idf 向量的数据点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27494202/

相关文章:

python - 如何在 Tensorflow 中使用 L2 池化?

python - 使用 nltk 从文本文件中提取所有名词

python - lxml 获取倒数第二个元素

python - scipy.integrate.trapz 和不连续函数

python - 如何检查文本特征的特征重要性?

python - 如何使用@cython装饰器声明np.ndarray类型

python - 创建大小为 2e5 的随机数组时 VisibleDeprecationWarning

python - 在 SciPy 中使用固定参数拟合分布

python - 从 sklearn RandomForestClassifier 制作 graphviz(不是从单独的 clf.estimators_)

python - 如何根据 PCA 的特征向量对特征进行正确排序