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()
时间: 2024-11-18 06:57:33