tf-idf

时间:2022-05-30
本文章向大家介绍tf-idf,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

计算tf-idf建模有很多种,具体看TF-IDF,nltk包实现tf是使用单词t出现的次数除以字符串长度,源码使用字符串count函数,这个函数有个缺点就是如,单词‘td’在‘tddddtd’会算作2词,总长使用的是字符串长度

# TF_IDF
# nltk实现TF_IDF
from nltk.text import TextCollection

# 首先,把所有文档放到TextCollection类中
# 这个类会自动帮你断句,做统计,做计算
help(TextCollection.tf)
corpus = TextCollection(['this is sentence one',
        'this is sentence two',
    'this is sentence three'])
# 直接就能算出tfidf
# 'td'在'tddd td'出现2次,字符串长度为7,tf=2/7
print corpus.tf('td', 'tddd td')
# idf 出现在三个文档中一个,log(3/1)
print corpus.idf('one')