我有一个关于sklearn的TfidfVectorizer的问题,当它在每个文档中执行单词的频率时。
我看到的示例代码是:
>>> from sklearn.feature_extraction.text import TfidfVectorizer
>>> corpus = [
>>> 'The dog ate a sandwich and I ate a sandwich',
>>> 'The wizard transfigured a sandwich'
>>> ]
>>> vectorizer = TfidfVectorizer(stop_words='english')
>>> print vectorizer.fit_transform(corpus).todense()
[[ 0.75458397 0.37729199 0.53689271 0. 0. ]
[ 0. 0. 0.44943642 0.6316672 0.6316672 ]]我的问题是:我如何解释矩阵中的数字?我理解0意味着,即向导这个词在第一个文档中出现0次,因此它是0,但是我如何解释数字0.75458397呢?是不是“吃”这个词出现在第一份文件中的频率?还是“吃”这个词在整个语料库中出现的频率?
发布于 2016-03-03 08:41:15
TF-国防军(意思是“术语频率-反向文档频率”),并不是给你一个词的频率在它的代表。
工作队-以色列国防军只对少数文件中出现的术语给予高分,对许多文件中出现的术语给予较低的分数,因此粗略地说,它是衡量某一特定文件中某一术语是否具有歧视性的一种衡量标准。看一看这资源,可以找到TF的优秀描述,并更好地了解它正在做什么。
如果您只需要计数,则需要使用CountVectorizer。
发布于 2018-03-07 00:20:39
我想你忘了TF-以色列国防军向量通常是标准化的,所以它们的大小(长度或2范数)总是1。
因此,TFIDF值0.75是"ate“的频率乘以"ate”的逆文档频率,然后除以TFIDF向量的大小。
下面是所有脏的细节(跳到tfidf0 =中的文章):
from sklearn.feature_extraction.text import TfidfVectorizer
corpus = ["The dog ate a sandwich and I ate a sandwich",
"The wizard transfigured a sandwich"]
vectorizer = TfidfVectorizer(stop_words='english')
tfidfs = vectorizer.fit_transform(corpus)
from collections import Counter
import pandas as pd
columns = [k for (v, k) in sorted((v, k)
for k, v in vectorizer.vocabulary_.items())]
tfidfs = pd.DataFrame(tfidfs.todense(),
columns=columns)
# ate dog sandwich transfigured wizard
#0 0.75 0.38 0.54 0.00 0.00
#1 0.00 0.00 0.45 0.63 0.63
df = (1 / pd.DataFrame([vectorizer.idf_], columns=columns))
# ate dog sandwich transfigured wizard
#0 0.71 0.71 1.0 0.71 0.71
corp = [txt.lower().split() for txt in corpus]
corp = [[w for w in d if w in vectorizer.vocabulary_] for d in corp]
tfs = pd.DataFrame([Counter(d) for d in corp]).fillna(0).astype(int)
# ate dog sandwich transfigured wizard
#0 2 1 2 0 0
#1 0 0 1 1 1
# The first document's TFIDF vector:
tfidf0 = tfs.iloc[0] * (1. / df)
tfidf0 = tfidf0 / pd.np.linalg.norm(tfidf0)
# ate dog sandwich transfigured wizard
#0 0.754584 0.377292 0.536893 0.0 0.0
tfidf1 = tfs.iloc[1] * (1. / df)
tfidf1 = tfidf1 / pd.np.linalg.norm(tfidf1)
# ate dog sandwich transfigured wizard
#0 0.0 0.0 0.449436 0.631667 0.631667发布于 2018-06-06 07:21:26
只要在下面的代码中打印,您就会看到类似的输出。
#(0, 1) 0.448320873199 Document 1, term = Dog
#(0, 3) 0.630099344518 Document 1, term = Sandwitch
print(vectorizer.fit_transform(corpus))
# if python 3 other wise remove () in printhttps://stackoverflow.com/questions/35757560
复制相似问题