使用scikit-learn和手动计算的tf-idf矩阵值差异

8 投票
2 回答
2864 浏览
提问于 2025-04-18 08:32

我正在使用 scikit-learn 来计算 tf-idf 值。

我有一组 documents,内容如下:

D1 = "The sky is blue."
D2 = "The sun is bright."
D3 = "The sun in the sky is bright."

我想创建一个这样的矩阵:

   Docs      blue    bright       sky       sun
   D1 tf-idf 0.0000000 tf-idf 0.0000000
   D2 0.0000000 tf-idf 0.0000000 tf-idf
   D3 0.0000000 tf-idf tf-idf tf-idf

所以,我在 Python 中写的代码是:

import nltk
import string

from sklearn.feature_extraction.text import TfidfVectorizer
from nltk.corpus import stopwords

train_set = ["sky is blue", "sun is bright", "sun in the sky is bright"]
stop_words = stopwords.words('english')

transformer = TfidfVectorizer(stop_words=stop_words)

t1 = transformer.fit_transform(train_set).todense()
print t1

我得到的结果矩阵是:

[[ 0.79596054  0.          0.60534851  0.        ]
 [ 0.          0.4472136   0.          0.89442719]
 [ 0.          0.57735027  0.57735027  0.57735027]]

如果我手动计算的话,矩阵应该是:

            Docs  blue      bright       sky       sun
            D1    0.2385    0.0000000  0.0880    0.0000000
            D2    0.0000000 0.0880     0.0000000 0.0880
            D3    0.0000000 0.058      0.058     0.058 

我计算的时候,比如说 bluetf1/2 = 0.5,而 idflog(3/1) = 0.477121255。所以 tf-idf = tf*idf = 0.5*0.477 = 0.2385。我就是这样计算其他的 tf-idf 值的。现在,我在想,为什么我手动计算的矩阵和 Python 计算的矩阵结果不一样?哪个结果是正确的?我在手动计算的时候是不是哪里出错了,还是我的 Python 代码有问题?

2 个回答

0

smooth_idf : 布尔值,默认值为True

这里提到的“平滑版本的idf”是用来处理一些数据的。其实有很多种不同的版本。在Python中,使用的公式是:$1 + \log((N + 1) / (n + 1))$,其中$N$代表所有文档的总数,而$n$是包含特定词汇的文档数量。

tf : 1/2, 1/2
idf with smoothing: (log(4/2)+1) ,(log(4/3)+1)
tf-idf : 1/2* (log(4/2)+1) ,1/2 * (log(4/3)+1)
L-2 normalization: 0.79596054 0.60534851

顺便提一下,原问题中的第二个部分可能有误,应该是相同的。

这是我在Python中得到的输出

14

这里有两个原因:

  1. 你忽略了在这种情况下常常会用到的平滑处理
  2. 你假设使用的是以10为底的对数

根据这个来源,sklearn并没有这样的假设。

首先,它对文档计数进行了平滑处理(这样就永远不会出现0的情况):

df += int(self.smooth_idf)
n_samples += int(self.smooth_idf)

而且它使用的是自然对数(np.log(np.e)==1

idf = np.log(float(n_samples) / df) + 1.0

另外,还有默认的l2归一化处理。简单来说,scikit-learn在计算tfidf时做了很多“很不错的小细节”。他们的方法并不比你的差,只是他们的方法更先进一些。

撰写回答