您好,登錄后才能下訂單哦!
import numpy as np #返回樣本數據集 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] return postingList,classVec #提取樣本數據中的單詞,構成詞匯表 def createVocabList(dataSet): vocabSet = set([]) for document in dataSet: vocabSet = vocabSet | set(document) return list(vocabSet) #傳入單詞表和待分析的數據,講數據轉為向量,這里記錄每行樣本的單詞是否出現 def setOfWords2Vec(vocabList, inputSet): retVocabList = [0] * len(vocabList) for word in inputSet: if word in vocabList: retVocabList[vocabList.index(word)] = 1 else: print 'word ',word ,'not in dict' return retVocabList #這里是每個樣本的出現次數 def bagOfWords2VecMN(vocabList, inputSet): returnVec = [0]*len(vocabList) for word in inputSet: if word in vocabList: returnVec[vocabList.index(word)] += 1 return returnVec #帶入樣本數據和結果,計算樣本對于某一類別的出現次數 #這個求出不同組中,每個詞出現的概率 def trainNB0(trainMatrix,trainCatergory): numTrainDoc = len(trainMatrix) numWords = len(trainMatrix[0]) pAbusive = sum(trainCatergory)/float(numTrainDoc) #防止多個概率的成績當中的一個為0 p0Num = np.ones(numWords) p1Num = np.ones(numWords) p0Denom = 2.0 p1Denom = 2.0 for i in range(numTrainDoc): if trainCatergory[i] == 1: p1Num +=trainMatrix[i] p1Denom += sum(trainMatrix[i]) else: p0Num +=trainMatrix[i] p0Denom += sum(trainMatrix[i]) #處于精度的考慮,否則很可能到限歸零,因為可能有太多項都為0 #避免下溢出和浮點數舍入導致的錯誤 p1Vect = np.log(p1Num/p1Denom) p0Vect = np.log(p0Num/p0Denom) return p0Vect,p1Vect,pAbusive #這里也就相當于log了一下 def classifyNB(vec2Classify, p0Vec, p1Vec, pClass1): p1 = sum(vec2Classify * p1Vec) + np.log(pClass1) p0 = sum(vec2Classify * p0Vec) + np.log(1.0 - pClass1) if p1 > p0: return 1 else: return 0 #測試方法 def testingNB(): listOPosts,listClasses = loadDataSet() myVocabList = createVocabList(listOPosts) trainMat=[] for postinDoc in listOPosts: trainMat.append(setOfWords2Vec(myVocabList, postinDoc)) p0V,p1V,pAb = trainNB0(np.array(trainMat),np.array(listClasses)) testEntry = ['love', 'my', 'dalmation'] thisDoc = np.array(setOfWords2Vec(myVocabList, testEntry)) print testEntry,'classified as: ',classifyNB(thisDoc,p0V,p1V,pAb) testEntry = ['stupid', 'garbage'] thisDoc = np.array(setOfWords2Vec(myVocabList, testEntry)) print testEntry,'classified as: ',classifyNB(thisDoc,p0V,p1V,pAb) def main(): testingNB() if __name__ == '__main__': main()
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。