【问题标题】:Python gensim (TfidfModel): How is the Tf-Idf computed?Python gensim (TfidfModel):如何计算 Tf-Idf?
【发布时间】:2021-06-28 17:12:42
【问题描述】:

1.对于下面的测试文本,

test=['test test', 'test toy']

tf-idf 分数 [没有归一化 (smartirs: 'ntn')] 是

[['test', 1.17]]  
[['test', 0.58], ['toy', 1.58]]

这似乎与我通过直接计算得到的不符

tfidf (w, d) = tf x idf  
where idf(term)=log (total number of documents / number of documents containing term)   
tf = number of instances of word in d document / total number of words of d document  

例如

doc 1: 'test test'  
for "test" word  
tf= 1  
idf= log(2/2) = 0  
tf-idf = 0  

有人可以用我上面的测试文本告诉我计算吗?

2)当我更改为余弦归一化(smartirs:'ntc')时,我得到

[['test', 1.0]]  
[['test', 0.35], ['toy', 0.94]]

有人也可以告诉我计算吗?

谢谢

import gensim
from gensim import corpora
from gensim import models
import numpy as np
from gensim.utils import simple_preprocess

test=['test test', 'test toy']
 
texts = [simple_preprocess(doc) for doc in test]
 
mydict= corpora.Dictionary(texts)
mycorpus = [mydict.doc2bow(doc, allow_update=True) for doc in texts]
tfidf = models.TfidfModel(mycorpus, smartirs='ntn')
 
for doc in tfidf[mycorpus]:
    print([[mydict[id], np.around(freq, decimals=2)] for id, freq in doc])  

【问题讨论】:

    标签: python gensim tf-idf


    【解决方案1】:

    如果您想了解model.TfidfModel 的实施细节,您可以直接在GitHub repository for gensim 中查看。与smartirs='ntn' 对应的特定计算方案在SMART Information Retrieval System 的维基百科页面上进行了描述,并且确切的计算与您使用的不同,因此结果有所不同。

    例如您所指的特定差异:

    idf= log(2/2) = 0  
    

    实际上应该是log2(N+1/n_k):

    idf= log(2/1) = 1  
    

    我建议您同时查看实现和提到的页面,以确保您的手动检查遵循所选smartirs 标志的实现。

    【讨论】:

      猜你喜欢
      • 2017-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-17
      • 2018-03-21
      • 2012-04-23
      • 2016-06-29
      • 2018-08-22
      相关资源
      最近更新 更多