python實現(xiàn)樸素貝葉斯分類器
更新時間:2018年03月28日 10:10:01 作者:shelmi
這篇文章主要為大家詳細介紹了python實現(xiàn)樸素貝葉斯分類器,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文用的是sciki-learn庫的iris數(shù)據(jù)集進行測試。用的模型也是最簡單的,就是用貝葉斯定理P(A|B) = P(B|A)*P(A)/P(B),計算每個類別在樣本中概率(代碼中是pLabel變量)
以及每個類下每個特征的概率(代碼中是pNum變量)。
寫得比較粗糙,對于某個類下沒有此特征的情況采用p=1/樣本數(shù)量。
有什么錯誤有人發(fā)現(xiàn)麻煩提出,謝謝。
[python] view plain copy # -*- coding:utf-8 -*- from numpy import * from sklearn import datasets import numpy as np class NaiveBayesClassifier(object): def __init__(self): self.dataMat = list() self.labelMat = list() self.pLabel = {} self.pNum = {} def loadDataSet(self): iris = datasets.load_iris() self.dataMat = iris.data self.labelMat = iris.target labelSet = set(iris.target) labelList = [i for i in labelSet] labelNum = len(labelList) for i in range(labelNum): self.pLabel.setdefault(labelList[i]) self.pLabel[labelList[i]] = np.sum(self.labelMat==labelList[i])/float(len(self.labelMat)) def seperateByClass(self): seperated = {} for i in range(len(self.dataMat)): vector = self.dataMat[i] if self.labelMat[i] not in seperated: seperated[self.labelMat[i]] = [] seperated[self.labelMat[i]].append(vector) return seperated # 通過numpy array二維數(shù)組來獲取每一維每種數(shù)的概率 def getProbByArray(self, data): prob = {} for i in range(len(data[0])): if i not in prob: prob[i] = {} dataSetList = list(set(data[:, i])) for j in dataSetList: if j not in prob[i]: prob[i][j] = 0 prob[i][j] = np.sum(data[:, i] == j) / float(len(data[:, i])) prob[0] = [1 / float(len(data[:,0]))] # 防止feature不存在的情況 return prob def train(self): featureNum = len(self.dataMat[0]) seperated = self.seperateByClass() t_pNum = {} # 存儲每個類別下每個特征每種情況出現(xiàn)的概率 for label, data in seperated.iteritems(): if label not in t_pNum: t_pNum[label] = {} t_pNum[label] = self.getProbByArray(np.array(data)) self.pNum = t_pNum def classify(self, data): label = 0 pTest = np.ones(3) for i in self.pLabel: for j in self.pNum[i]: if data[j] not in self.pNum[i][j]: pTest[i] *= self.pNum[i][0][0] else: pTest[i] *= self.pNum[i][j][data[j]] pMax = np.max(pTest) ind = np.where(pTest == pMax) return ind[0][0] def test(self): self.loadDataSet() self.train() pred = [] right = 0 for d in self.dataMat: pred.append(self.classify(d)) for i in range(len(self.labelMat)): if pred[i] == self.labelMat[i]: right += 1 print right / float(len(self.labelMat)) if __name__ == '__main__': NB = NaiveBayesClassifier() NB.test()
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python操作dict時避免出現(xiàn)KeyError的幾種解決方法
這篇文章主要介紹了Python操作dict時避免出現(xiàn)KeyError的幾種解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09keras-siamese用自己的數(shù)據(jù)集實現(xiàn)詳解
這篇文章主要介紹了keras-siamese用自己的數(shù)據(jù)集實現(xiàn)詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06python神經(jīng)網(wǎng)絡facenet人臉檢測及keras實現(xiàn)
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡facenet人臉檢測及keras實現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05