当前位置:   article > 正文

tf-idf的原理及计算_怎么只输出tfidf值较大的数据

怎么只输出tfidf值较大的数据

tf:term frequency

idf;inverse document frequency

TF=某个词在文章中出现的次数/文章的总次数

TF=某个词在文章中出现的次数/该问出现次数最多的词出现的次数

IDF=log(语料库的文档总数/(包含该词的文档数+1))

TF-IDF=TF*IDF

方法1:基于gensim的计算

  1. from gensim.models import TfidfModel
  2. from pprint import pprint
  3. from gensim.corpora import Dictionary
  4. data_set = [["tag1","tag2","tag3"],["tag2","tag2","tag3"],["tag1","tag4","tag3"]]
  5. dct = Dictionary(data_set)
  6. corpus = [dct.doc2bow(line) for line in data_set]
  7. pprint(corpus)
  8. model = TfidfModel(corpus)
  9. model[corpus[0]]
  10. [(0, 0.7071067811865476), (1, 0.7071067811865476)]

方法2:基于scikit-learn的tfidf

  1. from sklearn.feature_extraction.text import TfidfVectorizer
  2. tfidf_vec = TfidfVectorizer()
  3. # stop words自定义停用词表,为列表List类型
  4. # token_pattern过滤规则,正则表达式,如r"(?u)bw+b
  5. # max_df=0.5,代表一个单词在 50% 的文档中都出现过了,那么它只携带了非常少的信息,因此就不作为分词统计
  6. documents = [
  7. 'this is the bayes document',
  8. 'this is the second second document',
  9. 'and the third one',
  10. 'is this the document'
  11. ]
  12. tfidf_matrix = tfidf_vec.fit_transform(documents)
  13. # 拟合模型,并返回文本矩阵 表示了每个单词在每个文档中的 TF-IDF 值
  14. print('输出每个单词在每个文档中的 TF-IDF 值,向量里的顺序是按照词语的 id 顺序来的:', '\n', tfidf_matrix.toarray())
  15. print('不重复的词:', tfidf_vec.get_feature_names())
  16. print('输出每个单词对应的 id 值:', tfidf_vec.vocabulary_)
  17. print('返回idf值:', tfidf_vec.idf_)
  18. print('返回停用词表:', tfidf_vec.stop_words_)

参考:TF-IDF 原理与实现 - 知乎 

TF-IDF介绍及相关代码实现 - 简书 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/357837
推荐阅读
相关标签
  

闽ICP备14008679号