使用樸素貝葉斯方法在 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.