使用朴素贝叶斯方法在 Python 中对文本文档进行分类


朴素贝叶斯算法是一个强大的工具,可以用来将文档或文本的单词分类到不同的类别中。例如,如果一个文档包含“潮湿”、“下雨”或“阴天”等词,那么我们可以使用贝叶斯算法来检查该文档是否属于“晴天”或“雨天”类别。

请注意,朴素贝叶斯算法基于这样一个假设:比较的两个文档中的词语彼此独立。然而,考虑到语言的细微差别,这种情况很少发生。这就是为什么该算法的名称中包含“朴素”一词,但尽管如此,它的性能仍然足够好。

算法

  • 步骤 1 − 输入文档数量、文本字符串和相应的类别。使用列表对文本和关键词进行必要的拆分,并输入要分类的字符串/文本。

  • 步骤 2 − 创建一个列表,用于存储每个文档所有关键词的频率。使用 pretty table 库以表格形式打印出来。根据需要命名标题。

  • 步骤 3 − 统计每个类别(正类和负类)的总词数和文档数量。

  • 步骤 4 − 计算每个词的概率,并将其四舍五入到 4 位小数。

  • 步骤 5 − 使用贝叶斯公式计算类别的概率,并将其四舍五入到 8 位小数。

  • 步骤 6 − 使用贝叶斯公式计算类别的概率,并将其四舍五入到 8 位小数。

  • 步骤 7 − 对负类重复上述两个步骤。

  • 步骤 8 − 比较两个类别的结果概率,并打印结果。

示例

在这个例子中,为了简单起见和便于理解,我们将只取两个包含一个句子的文档,并在类似于这两个句子的字符串上执行朴素贝叶斯分类。此外,每个文档都将有一个类别,我们的目标是得出被测字符串属于哪个类别的结论。

#Step 1 - Input the required data and split the text and keywords
total_documents = 2
text_list = ["they love laugh and pray", "without faith you suffer"]
category_list = ["Positive", "Negative"]
doc_class = []
i = 0
keywords = []
while not i == total_documents:
   doc_class.append([])
   text = text_list[i]
   category = category_list[i]
   doc_class[i].append(text.split())
   doc_class[i].append(category)
   keywords.extend(text.split())
   i = i+1
keywords = set(keywords)
keywords = list(keywords)
keywords.sort()
to_find = "suffer without love laugh and pray"

#step 2 - make frequency table for keywords and print the table
probability_table = []
for i in range(total_documents):
   probability_table.append([])
   for j in keywords:
      probability_table[i].append(0)
doc_id = 1
for i in range(total_documents):
   for k in range(len(keywords)):
      if keywords[k] in doc_class[i][0]:
         probability_table[i][k] += doc_class[i][0].count(keywords[k])
print('\n')
import prettytable
keywords.insert(0, 'Document Number')
keywords.append("Class/Category")
Prob_Table = prettytable.PrettyTable()
Prob_Table.field_names = keywords
Prob_Table.title = 'Probability table'
x=0
for i in probability_table:
   i.insert(0,x+1)
   i.append(doc_class[x][1])
   Prob_Table.add_row(i)
   x=x+1
print(Prob_Table)
print('\n')
for i in probability_table:
   i.pop(0)
    
#step 3 - count the words and documents based on categories    
totalpluswords=0
totalnegwords=0
totalplus=0
totalneg=0
vocabulary=len(keywords)-2
for i in probability_table:
   if i[len(i)-1]=="+":
      totalplus+=1
      totalpluswords+=sum(i[0:len(i)-1])
   else:
      totalneg+=1
      totalnegwords+=sum(i[0:len(i)-1])
keywords.pop(0)
keywords.pop(len(keywords)-1)

#step - 4 Find probability of each word for positive class
temp=[]
for i in to_find:
   count=0
   x=keywords.index(i)
   for j in probability_table:
      if j[len(j)-1]=="Positive":
         count=count+j[x]
   temp.append(count)
   count=0
for i in range(len(temp)):
   temp[i]=format((temp[i]+1)/(vocabulary+totalpluswords),".4f")
print()
temp=[float(f) for f in temp]
print("Probabilities of each word in the 'Positive' category are: ")
h=0
for i in to_find:
   print(f"P({i}/+) = {temp[h]}")
   h=h+1
print()

#step - 5 Find probability of class using Bayes formula
prob_pos=float(format((totalplus)/(totalplus+totalneg),".8f"))
for i in temp:
   prob_pos=prob_pos*i
prob_pos=format(prob_pos,".8f")
print("Probability of text in 'Positive' class is :",prob_pos)
print()

#step - 6 Repeat above two steps for the negative class
temp=[]
for i in to_find:
   count=0
   x=keywords.index(i)
   for j in probability_table:
      if j[len(j)-1]=="Negative":
         count=count+j[x]
   temp.append(count)
   count=0
for i in range(len(temp)):
   temp[i]=format((temp[i]+1)/(vocabulary+totalnegwords),".4f")
print()
temp=[float(f) for f in temp]
print("Probabilities of each word in the 'Negative' category are: ")
h=0
for i in to_find:
   print(f"P({i}/-) = {temp[h]}")
   h=h+1
print()
prob_neg=float(format((totalneg)/(totalplus+totalneg),".8f"))
for i in temp:
   prob_neg=prob_neg*i
prob_neg=format(prob_neg,".8f")
print("Probability of text in 'Negative' class is :",prob_neg)
print('\n')

#step - 7 Compare the probabilities and print the result 
if prob_pos>prob_neg:
   print(f"By Naive Bayes Classification, we can conclude that the given belongs to 'Positive' class with the probability {prob_pos}")
else:
   print(f"By Naive Bayes Classification, we can conclude that the given belongs to 'Negative' class with the probability {prob_neg}")
print('\n')

我们迭代每个文档,将关键词存储在一个单独的列表中。我们通过迭代文档来存储关键词的频率,并绘制概率表。代码计算文档中正词和负词的数量,并确定唯一关键词的大小。

然后,我们计算正类别中每个关键词的概率,并迭代输入文本中的关键词,并计算在正类别中的出现次数。然后将得到的概率存储在一个新的列表中。然后,我们使用贝叶斯公式计算输入文本属于正类别的概率。类似地,我们计算负类别中每个关键词的概率并将其存储。然后,我们比较两个类别的概率,并确定概率较高的类别。

输出

Probabilities of each word in the 'Positive' category are: 
P(suffer/+) = 0.1111
P(without/+) = 0.1111
P(love/+) = 0.2222
P(laugh/+) = 0.2222
P(and/+) = 0.2222
P(pray/+) = 0.2222

Probability of text in 'Positive' class is : 0.00000000

Probabilities of each word in the 'Negative' category are: 
P(suffer/-) = 0.1111
P(without/-) = 0.1111
P(love/-) = 0.0556
P(laugh/-) = 0.0556
P(and/-) = 0.0556
P(pray/-) = 0.0556

Probability of text in 'Negative' class is : 0.00000012

By Naive Bayes Classification, we can conclude that the given belongs to 'Negative' class with the probability 0.00000012

结论

朴素贝叶斯算法就是这样一种算法,它在没有太多训练的情况下也能很好地工作。但是,对于文档中不存在的任何新数据,该算法可能会给出荒谬的结果或错误。尽管如此,该算法在实时预测和基于过滤的功能中得到了广泛的应用。其他此类分类算法包括逻辑回归、决策树和随机森林等。

更新于: 2023年8月7日

155 次查看

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.