我认为函数TfidfVectorizer没有正确计算IDF因子。 例如,从tf-idf feature weights using sklearn.feature_extraction.text.TfidfVectorizer复制代码:
from sklearn.feature_extraction.text import TfidfVectorizer
corpus = ["This is very strange",
"This is very nice"]
vectorizer = TfidfVectorizer(
use_idf=True, # utiliza o idf como peso, fazendo tf*idf
norm=None, # normaliza os vetores
smooth_idf=False, #soma 1 ao N e ao ni => idf = ln(N+1 / ni+1)
sublinear_tf=False, #tf = 1+ln(tf)
binary=False,
min_df=1, max_df=1.0, max_features=None,
strip_accents='unicode', # retira os acentos
ngram_range=(1,1), preprocessor=None, stop_words=None, tokenizer=None, vocabulary=None
)
X = vectorizer.fit_transform(corpus)
idf = vectorizer.idf_
print dict(zip(vectorizer.get_feature_names(), idf))
输出为:
{u'is': 1.0,
u'nice': 1.6931471805599454,
u'strange': 1.6931471805599454,
u'this': 1.0,
u'very': 1.0}`
但应该是:
{u'is': 0.0,
u'nice': 0.6931471805599454,
u'strange': 0.6931471805599454,
u'this': 0.0,
u'very': 0.0}
不是吗?我做错什么了?
而根据http://www.tfidf.com/,IDF的计算是:
IDF(t) = log_e(Total number of documents / Number of documents with term t in it)
因此,当术语“this”、“is”和“very”出现在两个句子中时,IDF=log_e(2/2)=0。
术语“奇怪”和“不错”只出现在两个文档中的一个,因此log_e(2/1)=069314。
在sklearn的实现过程中,有两件事情是你可能无法预料的:
TfidfTransformer
将smooth_idf=True
作为默认参数所以它使用:
这里是源代码:
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py#L987-L992
编辑: 您可以将标准
TfidfVectorizer
类划分为子类,如下所示:它们在计算idf时使用的实际公式(当smooth-idf为真时)是
它在源代码中,但我认为web文档对此有点模棱两可。
https://github.com/scikit-learn/scikit-learn/blob/14031f6/sklearn/feature_extraction/text.py#L966-L969
相关问题 更多 >
编程相关推荐