python編寫樸素貝葉斯用于文本分類
樸素貝葉斯估計(jì)
樸素貝葉斯是基于貝葉斯定理與特征條件獨(dú)立分布假設(shè)的分類方法。首先根據(jù)特征條件獨(dú)立的假設(shè)學(xué)習(xí)輸入/輸出的聯(lián)合概率分布,然后基于此模型,對(duì)給定的輸入x,利用貝葉斯定理求出后驗(yàn)概率最大的輸出y。
具體的,根據(jù)訓(xùn)練數(shù)據(jù)集,學(xué)習(xí)先驗(yàn)概率的極大似然估計(jì)分布
以及條件概率為
Xl表示第l個(gè)特征,由于特征條件獨(dú)立的假設(shè),可得
條件概率的極大似然估計(jì)為
根據(jù)貝葉斯定理
則由上式可以得到條件概率P(Y=ck|X=x)。
貝葉斯估計(jì)
用極大似然估計(jì)可能會(huì)出現(xiàn)所估計(jì)的概率為0的情況。后影響到后驗(yàn)概率結(jié)果的計(jì)算,使分類產(chǎn)生偏差。采用如下方法解決。
條件概率的貝葉斯改為
其中Sl表示第l個(gè)特征可能取值的個(gè)數(shù)。
同樣,先驗(yàn)概率的貝葉斯估計(jì)改為
$$
P(Y=c_k) = \frac{\sum\limits_{i=1}^NI(y_i=c_k)+\lambda}{N+K\lambda}
$K$
表示Y的所有可能取值的個(gè)數(shù),即類型的個(gè)數(shù)。
具體意義是,給每種可能初始化出現(xiàn)次數(shù)為1,保證每種可能都出現(xiàn)過一次,來解決估計(jì)為0的情況。
文本分類
樸素貝葉斯分類器可以給出一個(gè)最有結(jié)果的猜測(cè)值,并給出估計(jì)概率。通常用于文本分類。
分類核心思想為選擇概率最大的類別。貝葉斯公式如下:
詞條:將每個(gè)詞出現(xiàn)的次數(shù)作為特征。
假設(shè)每個(gè)特征相互獨(dú)立,即每個(gè)詞相互獨(dú)立,不相關(guān)。則
完整代碼如下;
import numpy as np import re import feedparser import operator def loadDataSet(): postingList=[['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'], ['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'], ['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him'], ['stop', 'posting', 'stupid', 'worthless', 'garbage'], ['mr', 'licks', 'ate', 'my', 'steak', 'how', 'to', 'stop', 'him'], ['quit', 'buying', 'worthless', 'dog', 'food', 'stupid']] classVec = [0,1,0,1,0,1] #1 is abusive, 0 not return postingList,classVec def createVocabList(data): #創(chuàng)建詞向量 returnList = set([]) for subdata in data: returnList = returnList | set(subdata) return list(returnList) def setofWords2Vec(vocabList,data): #將文本轉(zhuǎn)化為詞條 returnList = [0]*len(vocabList) for vocab in data: if vocab in vocabList: returnList[vocabList.index(vocab)] += 1 return returnList def trainNB0(trainMatrix,trainCategory): #訓(xùn)練,得到分類概率 pAbusive = sum(trainCategory)/len(trainCategory) p1num = np.ones(len(trainMatrix[0])) p0num = np.ones(len(trainMatrix[0])) p1Denom = 2 p0Denom = 2 for i in range(len(trainCategory)): if trainCategory[i] == 1: p1num = p1num + trainMatrix[i] p1Denom = p1Denom + sum(trainMatrix[i]) else: p0num = p0num + trainMatrix[i] p0Denom = p0Denom + sum(trainMatrix[i]) p1Vect = np.log(p1num/p1Denom) p0Vect = np.log(p0num/p0Denom) return p0Vect,p1Vect,pAbusive def classifyNB(vec2Classify,p0Vec,p1Vec,pClass1): #分類 p0 = sum(vec2Classify*p0Vec)+np.log(1-pClass1) p1 = sum(vec2Classify*p1Vec)+np.log(pClass1) if p1 > p0: return 1 else: return 0 def textParse(bigString): #文本解析 splitdata = re.split(r'\W+',bigString) splitdata = [token.lower() for token in splitdata if len(token) > 2] return splitdata def spamTest(): docList = [] classList = [] for i in range(1,26): with open('spam/%d.txt'%i) as f: doc = f.read() docList.append(doc) classList.append(1) with open('ham/%d.txt'%i) as f: doc = f.read() docList.append(doc) classList.append(0) vocalList = createVocabList(docList) trainList = list(range(50)) testList = [] for i in range(13): num = int(np.random.uniform(0,len(docList))-10) testList.append(trainList[num]) del(trainList[num]) docMatrix = [] docClass = [] for i in trainList: subVec = setofWords2Vec(vocalList,docList[i]) docMatrix.append(subVec) docClass.append(classList[i]) p0v,p1v,pAb = trainNB0(docMatrix,docClass) errorCount = 0 for i in testList: subVec = setofWords2Vec(vocalList,docList[i]) if classList[i] != classifyNB(subVec,p0v,p1v,pAb): errorCount += 1 return errorCount/len(testList) def calcMostFreq(vocabList,fullText): count = {} for vocab in vocabList: count[vocab] = fullText.count(vocab) sortedFreq = sorted(count.items(),key=operator.itemgetter(1),reverse=True) return sortedFreq[:30] def localWords(feed1,feed0): docList = [] classList = [] fullText = [] numList = min(len(feed1['entries']),len(feed0['entries'])) for i in range(numList): doc1 = feed1['entries'][i]['summary'] docList.append(doc1) classList.append(1) fullText.extend(doc1) doc0 = feed0['entries'][i]['summary'] docList.append(doc0) classList.append(0) fullText.extend(doc0) vocabList = createVocabList(docList) top30Words = calcMostFreq(vocabList,fullText) for word in top30Words: if word[0] in vocabList: vocabList.remove(word[0]) trainingSet = list(range(2*numList)) testSet = [] for i in range(20): randnum = int(np.random.uniform(0,len(trainingSet)-5)) testSet.append(trainingSet[randnum]) del(trainingSet[randnum]) trainMat = [] trainClass = [] for i in trainingSet: trainClass.append(classList[i]) trainMat.append(setofWords2Vec(vocabList,docList[i])) p0V,p1V,pSpam = trainNB0(trainMat,trainClass) errCount = 0 for i in testSet: testData = setofWords2Vec(vocabList,docList[i]) if classList[i] != classifyNB(testData,p0V,p1V,pSpam): errCount += 1 return errCount/len(testData) if __name__=="__main__": ny = feedparser.parse('http://newyork.craigslist.org/stp/index.rss') sf = feedparser.parse('http://sfbay.craigslist.org/stp/index.rss') print(localWords(ny,sf))
編程技巧:
1.兩個(gè)集合的并集
vocab = vocab | set(document)
2.創(chuàng)建元素全為零的向量
vec = [0]*10
代碼及數(shù)據(jù)集下載:貝葉斯
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 神經(jīng)網(wǎng)絡(luò)(BP)算法Python實(shí)現(xiàn)及應(yīng)用
- Python實(shí)現(xiàn)的三層BP神經(jīng)網(wǎng)絡(luò)算法示例
- Python編程實(shí)現(xiàn)的簡(jiǎn)單神經(jīng)網(wǎng)絡(luò)算法示例
- python實(shí)現(xiàn)BP神經(jīng)網(wǎng)絡(luò)回歸預(yù)測(cè)模型
- Python與人工神經(jīng)網(wǎng)絡(luò):使用神經(jīng)網(wǎng)絡(luò)識(shí)別手寫圖像介紹
- TensorFlow平臺(tái)下Python實(shí)現(xiàn)神經(jīng)網(wǎng)絡(luò)
- Python實(shí)現(xiàn)的NN神經(jīng)網(wǎng)絡(luò)算法完整示例
- python使用RNN實(shí)現(xiàn)文本分類
- Python使用循環(huán)神經(jīng)網(wǎng)絡(luò)解決文本分類問題的方法詳解
相關(guān)文章
python進(jìn)程管理工具supervisor的安裝與使用教程
supervisor是用python寫的一個(gè)進(jìn)程管理工具,用來啟動(dòng),重啟,關(guān)閉進(jìn)程。下面這篇文章主要給大家介紹了關(guān)于python實(shí)現(xiàn)的進(jìn)程管理工具supervisor的安裝與使用的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起看看吧。2017-09-09解讀FastAPI異步化為transformers模型打造高性能接口
這篇文章主要介紹了解讀FastAPI異步化為transformers模型打造高性能接口問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06簡(jiǎn)單的Apache+FastCGI+Django配置指南
這篇文章主要介紹了簡(jiǎn)單的Apache+FastCGI+Django配置指南,這也是Python上最流行的web框架Django的最流行搭配環(huán)境:)需要的朋友可以參考下2015-07-07PyCharm設(shè)置Ipython交互環(huán)境和宏快捷鍵進(jìn)行數(shù)據(jù)分析圖文詳解
這篇文章主要介紹了PyCharm設(shè)置Ipython交互環(huán)境和宏快捷鍵進(jìn)行數(shù)據(jù)分析圖文詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04Python深度學(xué)習(xí)實(shí)戰(zhàn)PyQt5安裝與環(huán)境配置過程詳解
本系列面向 Python 小白,從零開始實(shí)戰(zhàn)解說應(yīng)用 QtDesigner 進(jìn)行 PyQt5 的項(xiàng)目實(shí)戰(zhàn)。什么叫從零開始?從軟件安裝、環(huán)境配置開始。不跳過一個(gè)細(xì)節(jié),不漏掉一行代碼,不省略一個(gè)例圖2021-10-10詳解Python 爬取13個(gè)旅游城市,告訴你五一大家最愛去哪玩?
這篇文章主要介紹了Python 爬取13個(gè)旅游城市,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05tensorflow實(shí)現(xiàn)簡(jiǎn)單的卷積神經(jīng)網(wǎng)絡(luò)
這篇文章主要為大家詳細(xì)介紹了tensorflow實(shí)現(xiàn)簡(jiǎn)單的卷積神經(jīng)網(wǎng)絡(luò),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-05-05python實(shí)現(xiàn)內(nèi)存監(jiān)控系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)內(nèi)存監(jiān)控系統(tǒng),通過系統(tǒng)命令或操作系統(tǒng)文件獲取到內(nèi)存信息,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06