python-3.x - k 均值聚类中如何使用 tfidf 值

标签 python-3.x nlp k-means tf-idf tfidfvectorizer

我正在使用 sckit-learn 库将 K-means 聚类与 TF-IDF 结合使用。我知道 K-means 使用距离来创建聚类,距离用(x 轴值,y 轴值)表示,但 tf-idf 是单个数值。我的问题是这个 tf-idf 值是如何通过 K-means 聚类转换成 (x,y) 值的。

最佳答案

TF-IDF 不是单个值(即标量)。对于每个文档,它返回一个向量,其中向量中的每个值对应于词汇表中的每个单词。

from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
from scipy.sparse.csr import csr_matrix

sent1 = "the quick brown fox jumps over the lazy brown dog"
sent2 = "mr brown jumps over the lazy fox"

corpus = [sent1, sent2]
vectorizer = TfidfVectorizer(input=corpus)

X = vectorizer.fit_transform(corpus)
print(X.todense())

[输出]:

matrix([[0.50077266, 0.35190925, 0.25038633, 0.25038633, 0.25038633,
         0.        , 0.25038633, 0.35190925, 0.50077266],
        [0.35409974, 0.        , 0.35409974, 0.35409974, 0.35409974,
         0.49767483, 0.35409974, 0.        , 0.35409974]])

它返回一个二维矩阵,其中行代表句子,列代表词汇。

>>> vectorizer.vocabulary_
{'the': 8,
 'quick': 7,
 'brown': 0,
 'fox': 2,
 'jumps': 3,
 'over': 6,
 'lazy': 4,
 'dog': 1,
 'mr': 5}

因此,当 K-means 试图找出两个文档之间的距离/相似性时,它会计算矩阵中两行之间的相似性。例如。假设相似性只是两行之间的点积:

import numpy as np
vector1 = X.todense()[0]
vector2 = X.todense()[1]
float(np.dot(vector1, vector2.T))

[输出]:

0.7092938737640962

Chris Potts 有一个很好的教程,介绍如何创建像 TF-IDF 这样的向量空间模型 http://web.stanford.edu/class/linguist236/materials/ling236-handout-05-09-vsm.pdf

关于python-3.x - k 均值聚类中如何使用 tfidf 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60293351/

相关文章:

java - 在运行时更改 CoreNLP 设置

python - 如何使 spaCy 匹配不区分大小写

python - 应用PCA和聚类方法后,如何找到每个簇中数据的索引?

Matlab:Kmeans每次给出不同的结果

python - 在 1 年的时间跨度内有效地分发大量事件

Python:将嵌套列表作为输入?

java - 如何判断一个句子是否是疑问句(疑问句)?

matlab - 将一个matlab矩阵分成几个相等的部分

Python:如何调用子类的重写方法

python-3.x - 有没有办法让 Selenium 异步工作?