gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:35:31 26 4
gpt4 key购买 nike

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

我一直无法找到任何来源证明将 1 添加到 idf 值是合理的。我使用的是 scikit-learn 版本“0.14.1”。

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

最佳答案

这不是错误,它是 a feature

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

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

关于python - Scikit-learn TfidfTranformer 产生错误的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24105887/

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