当前位置:   article > 正文

自然语言处理(NLP)之TF-IDF原理及使用_nlp tf-idf

nlp tf-idf

TF-IDF介绍

TF-IDF是NLP中一种常用的统计方法,用以评估一个字词对于一个文件集或一个语料库中的其中一份文件的重要程度,通常用于提取文本的特征,即关键词。字词的重要性随着它在文件中出现的次数成正比增加,但同时会随着它在语料库中出现的频率成反比下降。

在NLP中,TF-IDF的计算公式如下:

其中,tf是词频(Term Frequency),idf为逆向文件频率(Inverse Document Frequency)。

  • tf为词频,即一个词语在文档中的出现频率,假设一个词语在整个文档中出现了i次,而整个文档有N个词语,则tf的值为i/N.
  • idf为逆向文件频率,假设整个文档有n篇文章,而一个词语在k篇文章中出现,则idf值为
  • 当然,不同地方的idf值计算公式会有稍微的不同。比如有些地方会在分母的k上加1,防止分母为0,还有些地方会让分子,分母都加上1,这是smoothing技巧。在本文中,还是采用最原始的idf值计算公式,因为这与gensim里面的计算公式一致。

文本介绍及预处理

  我们将采用以下三个示例文本:

  1. text1 = """
  2. Football is a family of team sports that involve, to varying degrees, kicking a ball to score a goal.
  3. Unqualified, the word football is understood to refer to whichever form of football is the most popular
  4. in the regional context in which the word appears. Sports commonly called football in certain places
  5. include association football (known as soccer in some countries); gridiron football (specifically American
  6. football or Canadian football); Australian rules football; rugby football (either rugby league or rugby union);
  7. and Gaelic football. These different variations of football are known as football codes.
  8. """
  9. text2 = """
  10. Basketball is a team sport in which two teams of five players, opposing one another on a rectangular court,
  11. compete with the primary objective of shooting a basketball (approximately 9.4 inches (24 cm) in diameter)
  12. through the defender's hoop (a basket 18 inches (46 cm) in diameter mounted 10 feet (3.048 m) high to a backboard
  13. at each end of the court) while preventing the opposing team from shooting through their own hoop. A field goal is
  14. worth two points, unless made from behind the three-point line, when it is worth three. After a foul, timed play stops
  15. and the player fouled or designated to shoot a technical foul is given one or more one-point free throws. The team with
  16. the most points at the end of the game wins, but if regulation play expires with the score tied, an additional period
  17. of play (overtime) is mandated.
  18. """
  19. text3 = """
  20. Volleyball, game played by two teams, usually of six players on a side, in which the players use their hands to bat a
  21. ball back and forth over a high net, trying to make the ball touch the court within the opponents’ playing area before
  22. it can be returned. To prevent this a player on the opposing team bats the ball up and toward a teammate before it touches
  23. the court surface—that teammate may then volley it back across the net or bat it to a third teammate who volleys it across
  24. the net. A team is allowed only three touches of the ball before it must be returned over the net.
  25. """

这三篇文章分别是关于足球,篮球,排球的介绍,它们组成一篇文档。
  接下来是文本的预处理部分。
  首先是对文本去掉换行符,然后是分句,分词,再去掉其中的标点,完整的Python代码如下,输入的参数为文章text:

  1. import nltk
  2. import string
  3. # 文本预处理
  4. # 函数:text文件分句、分词,并去掉标点
  5. def get_token(text):
  6. text = text.replace('\n', '')
  7. sents = nltk.sent_tokenize(text) # 分句
  8. print(len(sents))
  9. tokens = []
  10. for sent in sents:
  11. for word in nltk.word_tokenize(sent): # 分词
  12. if word not in string.punctuation: # 去掉标点
  13. tokens.append(word)
  14. return tokens
  15. print(get_token(text1))

运行结果:

  1. 4
  2. ['Football', 'is', 'a', 'family', 'of', 'team', 'sports', 'that', 'involve', 'to', 'varying', 'degrees', 'kicking', 'a', 'ball', 'to', 'score', 'a', 'goal', 'Unqualified', 'the', 'word', 'football', 'is', 'understood', 'to', 'refer', 'to', 'whichever', 'form', 'of', 'football', 'is', 'the', 'most', 'popular', 'in', 'the', 'regional', 'context', 'in', 'which', 'the', 'word', 'appears', 'Sports', 'commonly', 'called', 'football', 'in', 'certain', 'places', 'include', 'association', 'football', 'known', 'as', 'soccer', 'in', 'some', 'countries', 'gridiron', 'football', 'specifically', 'American', 'football', 'or', 'Canadian', 'football', 'Australian', 'rules', 'football', 'rugby', 'football', 'either', 'rugby', 'league', 'or', 'rugby', 'union', 'and', 'Gaelic', 'football', 'These', 'different', 'variations', 'of', 'football', 'are', 'known', 'as', 'football', 'codes']

接着,去掉文章中的停用词(stopwords),然后统计每个单词的出现次数,完整的Python代码如下,输入的参数为文章text:

  1. from nltk.corpus import stopwords # 停用词
  2. from collections import Counter
  3. # 对原始的text文件去掉停用词
  4. # 生成count字典,即每个单词的出现次数
  5. def make_count(text):
  6. tokens = get_token(text)
  7. filtered = [w for w in tokens if w not in stopwords.words('english')] # 去掉停用词
  8. count = Counter(filtered)
  9. return count
  10. print(make_count(text1))

以text1为例,生成的count字典如下:

Counter({'football': 12, 'rugby': 3, 'word': 2, 'known': 2, 'Football': 1, 'family': 1, 'team': 1, 'sports': 1, 'involve': 1, 'varying': 1, 'degrees': 1, 'kicking': 1, 'ball': 1, 'score': 1, 'goal': 1, 'Unqualified': 1, 'understood': 1, 'refer': 1, 'whichever': 1, 'form': 1, 'popular': 1, 'regional': 1, 'context': 1, 'appears': 1, 'Sports': 1, 'commonly': 1, 'called': 1, 'certain': 1, 'places': 1, 'include': 1, 'association': 1, 'soccer': 1, 'countries': 1, 'gridiron': 1, 'specifically': 1, 'American': 1, 'Canadian': 1, 'Australian': 1, 'rules': 1, 'either': 1, 'league': 1, 'union': 1, 'Gaelic': 1, 'These': 1, 'different': 1, 'variations': 1, 'codes': 1})

Gensim中的TF-IDF

  对文本进行预处理后,对于以上三个示例文本,我们都会得到一个count字典,里面是每个文本中单词的出现次数。下面,我们将用gensim中的已实现的TF-IDF模型,来输出每篇文章中TF-IDF排名前三的单词及它们的tfidf值,完整的代码如下:

  1. from nltk.corpus import stopwords
  2. from gensim import corpora, models, matutils
  3. # training by gensim tfidf model
  4. def get_words(text):
  5. tokens = get_token(text)
  6. filtered = [w for w in tokens if w not in stopwords.words('english')]
  7. return filtered
  8. # get text
  9. count1, count2, count3 = get_words(text1), get_words(text2), get_words(text3)
  10. count_list = [count1, count2, count3]
  11. # training by tfidf model in gensim
  12. dictionary = corpora.Dictionary(count_list)
  13. new_dict = {v: k for k, v in dictionary.token2id.items()}
  14. corpus2 = [dictionary.doc2bow(count) for count in count_list]
  15. tfidf2 = models.TfidfModel(corpus2)
  16. corpus_tfidf = tfidf2[corpus2]
  17. # output
  18. print('\nTraining by gensim tfidf model......\n')
  19. for i, doc in enumerate(corpus_tfidf):
  20. print('Top words in document %d' % (i + 1))
  21. sorted_words = sorted(doc, key=lambda x: x[1], reverse=True) # type=list
  22. for num, score in sorted_words[:3]:
  23. print('\tWord: %s, Tfidf: %s' % (new_dict[num], round(score, 5)))

运行结果:

  1. Training by gensim tfidf model......
  2. Top words in document 1
  3. Word: football, Tfidf: 0.84766
  4. Word: rugby, Tfidf: 0.21192
  5. Word: known, Tfidf: 0.14128
  6. Top words in document 2
  7. Word: play, Tfidf: 0.29872
  8. Word: cm, Tfidf: 0.19915
  9. Word: diameter, Tfidf: 0.19915
  10. Top words in document 3
  11. Word: net, Tfidf: 0.45775
  12. Word: teammate, Tfidf: 0.34331
  13. Word: across, Tfidf: 0.22888

输出的结果还是比较符合我们的预期的,比如关于足球的文章中提取了football, rugby关键词,关于篮球的文章中提取了plat, cm关键词,关于排球的文章中提取了net, teammate关键词。

自己动手实践TF-IDF模型

  有了以上我们对TF-IDF模型的理解,其实我们自己也可以动手实践一把,这是学习算法的最佳方式!
  以下是笔者实践TF-IDF的代码(接文本预处理代码):

  1. import math
  2. # 计算tf
  3. def tf(word, count):
  4. return count[word] / sum(count.values())
  5. # 计算count_list有多少个文件包含word
  6. def n_containing(word, count_list):
  7. return sum(1 for count in count_list if word in count)
  8. # 计算idf
  9. def idf(word, count_list):
  10. return math.log2(len(count_list) / n_containing(word, count_list)) # 对数以2为底
  11. # 计算tf-idf
  12. def tfidf(word, count, count_lsit):
  13. return tf(word, count) * idf(word, count_list)
  14. # tf-idf测试
  15. # TF-IDF测试
  16. count1, count2, count3 = make_count(text1), make_count(text2), make_count(text3)
  17. countlist = [count1, count2, count3]
  18. print("Training by original algorithm......\n")
  19. for i, count in enumerate(countlist):
  20. print("Top words in document %d" % (i + 1))
  21. scores = {word: tfidf(word, count, countlist) for word in count}
  22. sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True) # type=list
  23. # sorted_words = matutils.unitvec(sorted_words)
  24. for word, score in sorted_words[:3]:
  25. print("\tWord: %s, TF-IDF: %s" % (word, round(score, 5)))

运行结果:

  1. Training by original algorithm......
  2. Top words in document 1
  3. Word: football, TF-IDF: 0.30677
  4. Word: rugby, TF-IDF: 0.07669
  5. Word: word, TF-IDF: 0.05113
  6. Top words in document 2
  7. Word: play, TF-IDF: 0.05283
  8. Word: one, TF-IDF: 0.03522
  9. Word: shooting, TF-IDF: 0.03522
  10. Top words in document 3
  11. Word: net, TF-IDF: 0.10226
  12. Word: teammate, TF-IDF: 0.07669
  13. Word: bat, TF-IDF: 0.05113

可以看到,笔者自己动手实践的TF-IDF模型提取的关键词与gensim一致,至于篮球中为什么后两个单词不一致,是因为这些单词的tfidf一样,随机选择的结果不同而已。但是有一个问题,那就是计算得到的tfidf值不一样,这是什么原因呢?

究其原因,也就是说,gensim对得到的tf-idf向量做了规范化(normalize),将其转化为单位向量。因此,我们需要在刚才的代码中加入规范化这一步,代码如下:

  1. import numpy as np
  2. # 对向量做规范化, normalize
  3. def unitvec(sorted_words):
  4. lst = [item[1] for item in sorted_words]
  5. L2Norm = math.sqrt(sum(np.array(lst) * np.array(lst)))
  6. unit_vector = [(item[0], item[1] / L2Norm) for item in sorted_words]
  7. return unit_vector
  8. # tf-idf测试
  9. # TF-IDF测试
  10. count1, count2, count3 = make_count(text1), make_count(text2), make_count(text3)
  11. countlist = [count1, count2, count3]
  12. print("Training by original algorithm......\n")
  13. for i, count in enumerate(countlist):
  14. print("Top words in document %d" % (i + 1))
  15. scores = {word: tfidf(word, count, countlist) for word in count}
  16. sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True) # type=list
  17. sorted_words = unitvec(sorted_words)
  18. for word, score in sorted_words[:3]:
  19. print("\tWord: %s, TF-IDF: %s" % (word, round(score, 5)))

运行结果:

  1. Training by original algorithm......
  2. Top words in document 1
  3. Word: football, TF-IDF: 0.84766
  4. Word: rugby, TF-IDF: 0.21192
  5. Word: word, TF-IDF: 0.14128
  6. Top words in document 2
  7. Word: play, TF-IDF: 0.29872
  8. Word: one, TF-IDF: 0.19915
  9. Word: shooting, TF-IDF: 0.19915
  10. Top words in document 3
  11. Word: net, TF-IDF: 0.45775
  12. Word: teammate, TF-IDF: 0.34331
  13. Word: bat, TF-IDF: 0.22888

现在的输出结果与gensim得到的结果一致!


全部代码:

  1. import nltk
  2. import string
  3. import math
  4. import numpy as np
  5. from nltk.corpus import stopwords # 停用词
  6. from collections import Counter
  7. from gensim import corpora, models, matutils
  8. text1 = """
  9. Football is a family of team sports that involve, to varying degrees, kicking a ball to score a goal.
  10. Unqualified, the word football is understood to refer to whichever form of football is the most popular
  11. in the regional context in which the word appears. Sports commonly called football in certain places
  12. include association football (known as soccer in some countries); gridiron football (specifically American
  13. football or Canadian football); Australian rules football; rugby football (either rugby league or rugby union);
  14. and Gaelic football. These different variations of football are known as football codes.
  15. """
  16. text2 = """
  17. Basketball is a team sport in which two teams of five players, opposing one another on a rectangular court,
  18. compete with the primary objective of shooting a basketball (approximately 9.4 inches (24 cm) in diameter)
  19. through the defender's hoop (a basket 18 inches (46 cm) in diameter mounted 10 feet (3.048 m) high to a backboard
  20. at each end of the court) while preventing the opposing team from shooting through their own hoop. A field goal is
  21. worth two points, unless made from behind the three-point line, when it is worth three. After a foul, timed play stops
  22. and the player fouled or designated to shoot a technical foul is given one or more one-point free throws. The team with
  23. the most points at the end of the game wins, but if regulation play expires with the score tied, an additional period
  24. of play (overtime) is mandated.
  25. """
  26. text3 = """
  27. Volleyball, game played by two teams, usually of six players on a side, in which the players use their hands to bat a
  28. ball back and forth over a high net, trying to make the ball touch the court within the opponents’ playing area before
  29. it can be returned. To prevent this a player on the opposing team bats the ball up and toward a teammate before it touches
  30. the court surface—that teammate may then volley it back across the net or bat it to a third teammate who volleys it across
  31. the net. A team is allowed only three touches of the ball before it must be returned over the net.
  32. """
  33. # 文本预处理
  34. # 函数:text文件分句、分词,并去掉标点
  35. def get_token(text):
  36. text = text.replace('\n', '')
  37. sents = nltk.sent_tokenize(text) # 分句
  38. print(len(sents))
  39. tokens = []
  40. for sent in sents:
  41. for word in nltk.word_tokenize(sent): # 分词
  42. if word not in string.punctuation: # 去掉标点
  43. tokens.append(word)
  44. return tokens
  45. print(get_token(text1))
  46. # 对原始的text文件去掉停用词
  47. # 生成count字典,即每个单词的出现次数
  48. def make_count(text):
  49. tokens = get_token(text)
  50. filtered = [w for w in tokens if w not in stopwords.words('english')] # 去掉停用词
  51. count = Counter(filtered)
  52. return count
  53. print(make_count(text1))
  54. # training by gensim tfidf model
  55. def get_words(text):
  56. tokens = get_token(text)
  57. filtered = [w for w in tokens if w not in stopwords.words('english')]
  58. return filtered
  59. # get text
  60. count1, count2, count3 = get_words(text1), get_words(text2), get_words(text3)
  61. count_list = [count1, count2, count3]
  62. # training by tfidf model in gensim
  63. dictionary = corpora.Dictionary(count_list)
  64. new_dict = {v: k for k, v in dictionary.token2id.items()}
  65. corpus2 = [dictionary.doc2bow(count) for count in count_list]
  66. tfidf2 = models.TfidfModel(corpus2)
  67. corpus_tfidf = tfidf2[corpus2]
  68. # output
  69. print('\nTraining by gensim tfidf model......\n')
  70. for i, doc in enumerate(corpus_tfidf):
  71. print('Top words in document %d' % (i + 1))
  72. sorted_words = sorted(doc, key=lambda x: x[1], reverse=True) # type=list
  73. for num, score in sorted_words[:3]:
  74. print('\tWord: %s, Tfidf: %s' % (new_dict[num], round(score, 5)))
  75. # 计算tf
  76. def tf(word, count):
  77. return count[word] / sum(count.values())
  78. # 计算count_list有多少个文件包含word
  79. def n_containing(word, count_list):
  80. return sum(1 for count in count_list if word in count)
  81. # 计算idf
  82. def idf(word, count_list):
  83. return math.log2(len(count_list) / n_containing(word, count_list)) # 对数以2为底
  84. # 计算tf-idf
  85. def tfidf(word, count, count_lsit):
  86. return tf(word, count) * idf(word, count_list)
  87. # 对向量做规范化, normalize
  88. def unitvec(sorted_words):
  89. lst = [item[1] for item in sorted_words]
  90. L2Norm = math.sqrt(sum(np.array(lst) * np.array(lst)))
  91. unit_vector = [(item[0], item[1] / L2Norm) for item in sorted_words]
  92. return unit_vector
  93. # tf-idf测试
  94. # TF-IDF测试
  95. count1, count2, count3 = make_count(text1), make_count(text2), make_count(text3)
  96. countlist = [count1, count2, count3]
  97. print("Training by original algorithm......\n")
  98. for i, count in enumerate(countlist):
  99. print("Top words in document %d" % (i + 1))
  100. scores = {word: tfidf(word, count, countlist) for word in count}
  101. sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True) # type=list
  102. sorted_words = unitvec(sorted_words)
  103. for word, score in sorted_words[:3]:
  104. print("\tWord: %s, TF-IDF: %s" % (word, round(score, 5)))

运行结果:

  1. 4
  2. ['Football', 'is', 'a', 'family', 'of', 'team', 'sports', 'that', 'involve', 'to', 'varying', 'degrees', 'kicking', 'a', 'ball', 'to', 'score', 'a', 'goal', 'Unqualified', 'the', 'word', 'football', 'is', 'understood', 'to', 'refer', 'to', 'whichever', 'form', 'of', 'football', 'is', 'the', 'most', 'popular', 'in', 'the', 'regional', 'context', 'in', 'which', 'the', 'word', 'appears', 'Sports', 'commonly', 'called', 'football', 'in', 'certain', 'places', 'include', 'association', 'football', 'known', 'as', 'soccer', 'in', 'some', 'countries', 'gridiron', 'football', 'specifically', 'American', 'football', 'or', 'Canadian', 'football', 'Australian', 'rules', 'football', 'rugby', 'football', 'either', 'rugby', 'league', 'or', 'rugby', 'union', 'and', 'Gaelic', 'football', 'These', 'different', 'variations', 'of', 'football', 'are', 'known', 'as', 'football', 'codes']
  3. 4
  4. Counter({'football': 12, 'rugby': 3, 'word': 2, 'known': 2, 'Football': 1, 'family': 1, 'team': 1, 'sports': 1, 'involve': 1, 'varying': 1, 'degrees': 1, 'kicking': 1, 'ball': 1, 'score': 1, 'goal': 1, 'Unqualified': 1, 'understood': 1, 'refer': 1, 'whichever': 1, 'form': 1, 'popular': 1, 'regional': 1, 'context': 1, 'appears': 1, 'Sports': 1, 'commonly': 1, 'called': 1, 'certain': 1, 'places': 1, 'include': 1, 'association': 1, 'soccer': 1, 'countries': 1, 'gridiron': 1, 'specifically': 1, 'American': 1, 'Canadian': 1, 'Australian': 1, 'rules': 1, 'either': 1, 'league': 1, 'union': 1, 'Gaelic': 1, 'These': 1, 'different': 1, 'variations': 1, 'codes': 1})
  5. 4
  6. 4
  7. 3
  8. Training by gensim tfidf model......
  9. Top words in document 1
  10. Word: football, Tfidf: 0.84766
  11. Word: rugby, Tfidf: 0.21192
  12. Word: known, Tfidf: 0.14128
  13. Top words in document 2
  14. Word: play, Tfidf: 0.29872
  15. Word: cm, Tfidf: 0.19915
  16. Word: diameter, Tfidf: 0.19915
  17. Top words in document 3
  18. Word: net, Tfidf: 0.45775
  19. Word: teammate, Tfidf: 0.34331
  20. Word: across, Tfidf: 0.22888
  21. 4
  22. 4
  23. 3
  24. Training by original algorithm......
  25. Top words in document 1
  26. Word: football, TF-IDF: 0.84766
  27. Word: rugby, TF-IDF: 0.21192
  28. Word: word, TF-IDF: 0.14128
  29. Top words in document 2
  30. Word: play, TF-IDF: 0.29872
  31. Word: one, TF-IDF: 0.19915
  32. Word: shooting, TF-IDF: 0.19915
  33. Top words in document 3
  34. Word: net, TF-IDF: 0.45775
  35. Word: teammate, TF-IDF: 0.34331
  36. Word: bat, TF-IDF: 0.22888

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

闽ICP备14008679号