如果需要完整代碼可以關注下方公眾號,后臺回復“代碼”即可獲取,阿光期待著您的光臨~
文章目錄
- 代碼實踐
2021人工智能領域新星創作者,帶你從入門到精通,該博客每天更新,逐漸完善各個知識體系的文章,幫助大家更高效學習,
請用貝葉斯網路實作一個簡單的拼寫檢查
演算法步驟:
1)建立一個足夠大的文本庫
2)對文本庫的每一個單詞統計其出現頻率
3)根據用戶輸入的單詞,得到其所有可能的拼寫相近的形式
4)比較所有拼寫相近的詞在文本庫的出現頻率,頻率最高的那個詞,就是正確的拼法
- 首先自己建立文本庫(外文文獻)
- 計算先驗概率
- 計算似然
- 回傳最大條件概率的單詞
為了簡單沒有考慮不同特征之間的聯合概率,如果是聯合概率需要使用圖計算,基于概率圖(貝葉斯網路),這里僅僅考慮各特征之間獨立分布,



代碼實踐
"""
* Created with PyCharm
* 作者: Laura
* 日期: 2021/11/6
* 時間: 18:30
* 描述: 貝葉斯網路實作一個簡單的拼寫檢查
"""
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
import pandas as pd
import jieba
import re
import collections
class Bayes():
def __init__(self,):
self.dic={}
def cut_word(self):
string=''
with open('text', 'r', encoding='utf-8') as file:
for line in file.readlines():
string+=line
pattern = re.compile(u'\t|\n|\.|-|:|;|\)|\(|\?|"')
string = re.sub(pattern, '', string)
seg_list_exact = jieba.cut(string, cut_all = False)
object_list = []
remove_words = [u',',u'.',u"'",u' ',u'!',u'It',u'The',u'like',u'//',u'So',u'is',u'are',u'it',u'/'
,u'a',u'b',u'c',u'd',u'e',u'f',u'g',u'h',u'i',u'j',u'k',u'l',u'm',u'n',u'o',u'p',u'q',u'r',u's',u't',u'u',u'v',u'w',u'x',u'y',u'z'
,u'A',u'B',u'C',u'D',u'E',u'F',u'G',u'H',u'I',u'J',u'K',u'L',u'M',u'N',u'O',u'P',u'Q',u'R',u'S',u'T',u'U',u'V',u'W',u'X',u'Y',u'Z'
,u'0',u'1',u'2',u'3',u'4',u'5',u'6',u'7',u'8',u'9',u'10']
for word in seg_list_exact:
if word not in remove_words:
object_list.append(word)
words=[]
for word in object_list:
words.append(word)
word_counts = collections.Counter(object_list)
word_counts_top10 = word_counts.most_common(100)
dic=dict()
for val in word_counts_top10:
dic[val[0]]=val[1]
self.dic=dic
def calculate_frequency(self):
frequency_ = 0.
for value in self.dic.values():
frequency_ += value
self.dic = dict(map(lambda x:[x, [self.dic[x] / frequency_]],self.dic))
def calculate_p_r_c(self,word):
for key in self.dic.keys():
count=0.
len_word=len(word)
len_key=len(key)
for num in range(min(len_word,len_key)):
if key[num]==word[num]:
count+=1
self.dic[key].append(count)
def run(self,word):
self.cut_word()
self.calculate_frequency()
self.calculate_p_r_c(word)
print(sorted(dict(map(lambda x:[x, self.dic[x][0]*self.dic[x][1]],self.dic)).items(), key=lambda item:item[1],reverse=True)[0][0])
model=Bayes()
model.run('appl')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/350804.html
標籤:AI

