【问题标题】:Difference in values of tf-idf matrix using scikit-learn and hand calculation使用 scikit-learn 和手动计算的 tf-idf 矩阵值的差异
【发布时间】:2016-09-24 04:57:08
【问题描述】:

我正在使用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 

我的计算就像说blue 为tf = 1/2 = 0.5 和idf 为log(3/1) = 0.477121255。因此tf-idf = tf*idf = 0.5*0.477 = 0.2385。这样,我正在计算其他 tf-idf 值。现在,我想知道,为什么我在手算矩阵和 Python 矩阵中得到不同的结果?哪个给出正确的结果?我的手算有问题还是我的 Python 代码有问题?

【问题讨论】:

    标签: python matrix machine-learning tf-idf


    【解决方案1】:

    有两个原因:

    1. 您忽略了在这种情况下经常发生的平滑
    2. 您假设以 10 为底的对数

    根据sourcesklearn 不使用这样的假设。

    首先,它会平滑文档计数(所以永远不会有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 时做了更多的“小事”。这些方法(他们的或你的)都不是坏的。他们只是更先进。

    【讨论】:

    • 我想知道为什么比率的差异是不同的。两个矩阵的所有值的差异不能用任何乘法或除法来表示。
    • 我的回答也给了你一个答案。平滑不仅仅是“不同的乘法”,在 idf 部分也不是不同的对数底
    【解决方案2】:

    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
    

    顺便说一句,原题中的第二个可能是错误的,应该是一样的。 my out put from python

    【讨论】:

      猜你喜欢
      • 2014-12-05
      • 2016-02-03
      • 1970-01-01
      • 2020-05-11
      • 2017-03-20
      • 2015-02-11
      • 2014-07-23
      • 2019-11-14
      • 2016-10-11
      相关资源
      最近更新 更多