Scikit-learn TfidfTranformer 产生错误的结果?

lab*_*hat 2 python nlp tf-idf scikit-learn

我使用 scikit-learn 的 Tfidf 转换器得到了“奇怪”的结果。通常,我希望出现在语料库中所有文档中的单词的 idf 等于 0(不使用任何平滑或规范化),因为我将使用的公式是文档中文档数量的对数语料库除以包含该术语的文档数。显然(如下图所示)与我的手动实现相比,scikit-learn 的实现为每个 idf 值增加了一个。有人知道为什么吗?再次注意,我已将平滑和归一化设置为 None/False。

In [101]: from sklearn.feature_extraction.text import TfidfTransformer

In [102]: counts
Out[102]: 
array([[3, 0, 1],
       [2, 0, 0],
       [3, 0, 0],
       [4, 0, 0],
       [3, 2, 0],
       [3, 0, 2]])

In [103]: transformer = TfidfTransformer(norm=None, smooth_idf=False)

In [104]: transformer
Out[104]: 
TfidfTransformer(norm=None, smooth_idf=False, sublinear_tf=False,
         use_idf=True)

In [105]: tfidf = transformer.fit_transform(counts)

In [106]: tfidf.toarray()
Out[106]: 
array([[ 3.        ,  0.        ,  2.09861229],
       [ 2.        ,  0.        ,  0.        ],
       [ 3.        ,  0.        ,  0.        ],
       [ 4.        ,  0.        ,  0.        ],
       [ 3.        ,  5.58351894,  0.        ],
       [ 3.        ,  0.        ,  4.19722458]])

In [107]: transformer.idf_
Out[107]: array([ 1.        ,  2.79175947,  2.09861229])

In [108]: idf1 = np.log(6/6)

In [109]: idf1
Out[109]: 0.0

In [110]: idf2 = np.log(6/1)

In [111]: idf2
Out[111]: 1.791759469228055

In [112]: idf3 = np.log(6/2)

In [113]: idf3
Out[113]: 1.0986122886681098
Run Code Online (Sandbox Code Playgroud)

我一直无法找到任何证明在 idf 值中添加一个的来源。我正在使用 scikit-learn 版本“0.14.1”。

顺便说一句,除了 scikit-learn 之外的另一种解决方案对我来说并不是真的有用,因为我需要为 gridsearch 构建一个 scikit-learn 管道。

lej*_*lot 6

这不是错误,它是一个功能

# log1p instead of log makes sure terms with zero idf don't get
# suppressed entirely
idf = np.log(float(n_samples) / df) + 1.0
Run Code Online (Sandbox Code Playgroud)

+1(如评论中所述)用于使 idf normalizator变弱,否则,所有文档中出现的元素将被完全删除(它们的 idf=0 所以整个 tfidf=0)