当前位置:   article > 正文

TF-IDF 统计算法介绍与代码实现_tf-idf代码

tf-idf代码

目录

一、什么是TF-IDF?

二、TF与IDF的计算

三、TF-IDF应用

四、TF-IDF代码实现

4.1、初始实现

4.2、改写成类实现

五、TF-IDF算法特点

六、参考


一、什么是TF-IDF?

一种统计方法, 用以评估一字词对于一个文件集或一个语料库中的其中一份文件的重要程度
字词的重要性随着它在文件中出现的次数成正比增加,但随着它在语料库中出现的频率成反比下降
TF-IDF实际上是:TF * IDF。主要思想是 :如果某个词或短语在一篇文章中出现的频率高(即TF高),并且在其他文章中很少出现(即IDF高),则认为此词或者短语具有很好的类别区分能力,适合用来分类。通俗理解TF-IDF就是:TF刻画了词语t对某篇文档的重要性,IDF刻画了词语t对整个文档集的重要性。

二、TF与IDF的计算

    词频 (TF) 是一词语出现的次数除以该文件的总词语数。假如一篇文件的总词语数是100个,而词语“中国”出现了8次,那么“中国””一词在该文件中的词频就是8/100=0.08。一个计算文件频率 (IDF) 的方法是文件集里包含的文件总数除以测定有多少份文件出现过“中国””一词。所以,如果“中国””一词在1,000份文件出现过,而文件总数是10,000,000份的话,其逆向文件频率就是 lg(10,000,000 / 1,000)=4。最后的TF-IDF的分数为0.08 * 4=0.32。
下面是某篇文章中的解释:

三、TF-IDF应用

  1. 搜索引擎,Elasticsearch的相关性得分_score
  2. 关键词提取
  3. 文本相似度
  4. 文本摘要

四、TF-IDF代码实现

4.1、初始实现

  1. import numpy as np
  2. import pandas as pd
  3. import math
  4. import jieba
  5. # 定义数据
  6. docA = "The cat sat on my bed"
  7. docB = "The dog sat on my knees"
  8. bowA = docA.split(" "# list(jieba.cut(docA))   split适合英文语句分词,jieba更适用于中文语句分词
  9. bowB = docB.split(" "# list(jieba.cut(docB))  # 关键词的提取可以使用jieba分词提取
  10. # 构建词库
  11. wordSet = set(bowA).union(set(bowB))
  12. print("wordSet:%s" % wordSet)  # {'on', 'bed', 'cat', 'my', 'dog', 'The', 'knees', 'sat'}
  13. # 次数统计
  14. wordDictA = dict.fromkeys(wordSet, 0# 用统计字典来保存词出现的次数
  15. wordDictB = dict.fromkeys(wordSet, 0)
  16. for word in bowA:
  17.     wordDictA[word] += 1
  18. for word in bowB:
  19.     wordDictB[word] += 1
  20. print("wordDictA:%s" % wordDictA)  # {'bed': 1, 'The': 1, 'sat': 1, 'on': 1, 'my': 1, 'cat': 1, 'dog': 0, 'knees': 0}
  21. print("wordDictB:%s" % wordDictB)  # {'bed': 0, 'The': 1, 'sat': 1, 'on': 1, 'my': 1, 'cat': 0, 'dog': 1, 'knees': 1}
  22. data_frame = pd.DataFrame([wordDictA, wordDictB])
  23. print("data_frame:\n%s" % data_frame)
  24. '''
  25. data_frame:
  26.    bed  The  sat  on  my  cat  dog  knees
  27. 0    1    1    1   1   1    1    0      0
  28. 1    0    1    1   1   1    0    1      1
  29. '''
  30. # 计算词频TF
  31. def compute_TF(word_dict, bow):
  32.     """
  33.     func:用一个字典对象记录tf,把所有的词对应在bow文档里的tf都算出来
  34.     :param word_dict: 文件中的单词次数字典
  35.     :param bow: 文件内容
  36.     :return:
  37.     """
  38.     tf_dict = {}
  39.     n_bow_count = len(bow)
  40.     for word, count in word_dict.items():
  41.         tf_dict[word] = count/n_bow_count
  42.     return tf_dict
  43. tfA = compute_TF(wordDictA, bowA)
  44. tfB = compute_TF(wordDictB, bowB)
  45. print("tfA:%s, \ntfB:%s" % (tfA, tfB))
  46. '''
  47. tfA:{'dog': 0.0, 'cat': 0.16666666666666666, 'The': 0.16666666666666666, 'bed': 0.16666666666666666, 'sat': 0.16666666666666666, 'my': 0.16666666666666666, 'knees': 0.0, 'on': 0.16666666666666666},
  48. tfB:{'dog': 0.16666666666666666, 'cat': 0.0, 'The': 0.16666666666666666, 'bed': 0.0, 'sat': 0.16666666666666666, 'my': 0.16666666666666666, 'knees': 0.16666666666666666, 'on': 0.16666666666666666}
  49. '''
  50. # 计算逆文档频率IDF
  51. def compute_IDF(wordDictList):
  52.     """
  53.     func:用一个字典对象保存idf结果,每个词作为key,初始值为0
  54.     :param wordDictList: 文件内容组成的列表
  55.     :return:
  56.     """
  57.     idfDict = dict.fromkeys(wordDictList[0], 0)
  58.     N = len(wordDictList)
  59.     for wordDict in wordDictList:
  60.         for word, count in wordDict.items():
  61.             if count > 0:
  62.                 idfDict[word] += 1
  63.     for word, ni in idfDict.items():  # {'dog': 1, 'on': 2, 'The': 2, 'bed': 1, 'sat': 2, 'knees': 1, 'cat': 1, 'my': 2}
  64.         idfDict[word] = math.log10((N + 1) / (ni + 1))
  65.     return idfDict
  66. idfs = compute_IDF([wordDictA, wordDictB])
  67. print("idfs:%s" % idfs)  # {'dog': 0.17609125905568124, 'on': 0.0, 'The': 0.0, 'bed': 0.17609125905568124, 'sat': 0.0, 'knees': 0.17609125905568124, 'cat': 0.17609125905568124, 'my': 0.0}
  68. # 计算TF-IDF
  69. def compute_TFIDF(tf, idfs):
  70.     tfidf = {}
  71.     for word, tfval in tf.items():
  72.         tfidf[word] = tfval * idfs[word]
  73.     return tfidf
  74. tfidfA = compute_TFIDF(tfA, idfs)
  75. tfidfB = compute_TFIDF(tfB, idfs)
  76. result = pd.DataFrame([tfidfA, tfidfB])
  77. print("result:\n %s" % result)
  78. '''
  79. result:
  80.          bed  The   my       cat   on     knees  sat       dog
  81. 0  0.029349  0.0  0.0  0.029349  0.0  0.000000  0.0  0.000000
  82. 1  0.000000  0.0  0.0  0.000000  0.0  0.029349  0.0  0.029349
  83. '''
  84. # 余弦相似度,利用词频TF
  85. import scipy.spatial
  86. def cos(a, b):
  87.     '''
  88.     a和b都要是2维,a和b中的元素个数不定
  89.     '''
  90.     dis = scipy.spatial.distance.cdist(a, b, 'cosine')
  91.     cos = 1 - dis[0]
  92.     return cos
  93. a = np.array([list(wordDictA.values())])
  94. b = np.array([list(wordDictB.values())])
  95. print(cos(a, b))  # [0.66666667]

4.2、改写成类实现

  1. # https://baijiahao.baidu.com/s?id=1668933015186340529&wfr=spider&for=pc
  2. import numpy as np
  3. import pandas as pd
  4. import math
  5. import jieba
  6. import collections
  7. import scipy.spatial
  8. class TFIDF(object):
  9. def __init__(self, documents):
  10. self.document_list = documents
  11. self.word_dict_list = []
  12. self.word_set = set([word for doc in self.document_list for word in jieba.lcut_for_search(doc)]) # 构建词库
  13. print("self.word_set:%s" % self.word_set) # {'自古', '长存', '不朽', '中国'}
  14. def word_num(self):
  15. """
  16. func:次数统计
  17. """
  18. for doc in self.document_list:
  19. word_dict = dict.fromkeys(self.word_set, 0)
  20. bow = jieba.lcut_for_search(doc)
  21. for word in bow:
  22. word_dict[word] += 1
  23. self.word_dict_list.append(word_dict)
  24. data_frame = pd.DataFrame(self.word_dict_list)
  25. print("data_frame:\n%s" % data_frame)
  26. def compute_tf(self):
  27. """
  28. func:计算词频TF
  29. """
  30. tf_list = []
  31. for word_dict, document in zip(self.word_dict_list, self.document_list):
  32. tf_dict = {}
  33. n_bow_count = len(jieba.lcut_for_search(document))
  34. for word, count in word_dict.items():
  35. tf_dict[word] = count / n_bow_count # 某个词在单文件中的词频
  36. tf_list.append(tf_dict)
  37. tf_data_frame = pd.DataFrame(tf_list)
  38. print("tf_data_frame:\n%s" % tf_data_frame)
  39. return tf_list
  40. def compute_idf(self):
  41. """
  42. func:计算逆文档频率IDF.用一个字典对象保存idf结果,每个词作为key,初始值为0
  43. """
  44. N = len(self.document_list) # 语料库的文档总数
  45. idfDict = dict.fromkeys(self.word_dict_list[0], 0)
  46. for word_dict in self.word_dict_list:
  47. for word, count in word_dict.items():
  48. if count > 0:
  49. idfDict[word] += 1 # 某个词在多少份文档中出现
  50. for word, ni in idfDict.items():
  51. print("word:%s, N+1:%s, ni+1:%s" % (word, N+1, ni+1))
  52. idfDict[word] = math.log10((N + 1) / (ni + 1)) # log(语料库文档总数/(某个词在多少份文档中出现+1))
  53. print("idfDict:%s" % idfDict)
  54. return idfDict
  55. def compute_tdidf(self, tf_dict, idfs_dict):
  56. """
  57. 计算TF-IDF
  58. """
  59. tfidf = {}
  60. for word, tfval in tf_dict.items():
  61. tfidf[word] = tfval * idfs_dict[word]
  62. return tfidf
  63. # 定义数据
  64. docA = "中国自古长存"
  65. docB = "中国长存"
  66. docC = "中国自古长存不朽"
  67. # docA = "The cat sat on my bed"
  68. # docB = "The dog sat on my knees" # 分词用split
  69. document_list = [docA, docB, docC]
  70. tf_idf = TFIDF(document_list)
  71. tf_idf.word_num()
  72. tf_list = tf_idf.compute_tf()
  73. idf_dict = tf_idf.compute_idf()
  74. tf_idf_list = []
  75. for tf in tf_list:
  76. tdidf = tf_idf.compute_tdidf(tf, idf_dict)
  77. tf_idf_list.append(tdidf)
  78. tfidf_data_frame = pd.DataFrame(tf_idf_list)
  79. print("tfidf_data_frame:\n%s" % tfidf_data_frame)
  80. # 余弦相似度
  81. def cos_similarity(a, b):
  82. """
  83. a和b都要是2维,a和b中的元素个数不定
  84. """
  85. dis = scipy.spatial.distance.cdist(a, b, 'cosine')
  86. cos = 1 - dis[0]
  87. return cos
  88. # 利用词频TF
  89. array = [list(item.values()) for item in tf_list]
  90. cos_list = []
  91. for i in range(len(array) - 1):
  92. cos_list.append(cos_similarity([array[i]], array[i+1:]))
  93. print("余弦相似度:%s" % cos_list)

五、TF-IDF算法特点

TF-IDF算法实现简单快速,但是仍有许多不足之处:
(1)没有考虑特征词的位置因素对文本的区分度,词条出现在文档的不同位置时,对区分度的贡献大小是不一样的。
(2)按照传统TF-IDF,往往一些生僻词的IDF(反文档频率)会比较高、因此这些生僻词常会被误认为是文档关键词。
(3)传统TF-IDF中的IDF部分只考虑了特征词与它出现的文本数之间的关系,而忽略了特征项在一个类别中不同的类别间的分布情况。
(4)对于文档中出现次数较少的重要人名、地名信息提取效果不佳。

六、参考

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

闽ICP备14008679号