gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:15:58 26 4
gpt4 key购买 nike

我正在使用 scikit-learn 来查找 tf-idf 值。

我有一组文档,例如:

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.5idf 作为 log(3/1) = 0.477121255。因此 tf-idf = tf*idf = 0.5*0.477 = 0.2385。通过这种方式,我正在计算其他 tf-idf 值。现在,我想知道,为什么我在手算矩阵和 Python 矩阵中得到不同的结果?哪个给出了正确的结果?是我手算有问题还是我的 Python 代码有问题?

最佳答案

有两个原因:

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

根据 source 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 时做了更多“不错的小事”。这些方法(他们的或你的)都不是坏事。他们只是更先进。

关于python - 使用 scikit-learn 和手工计算的 tf-idf 矩阵值的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24032485/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com