朴素貝葉斯最著名的一個應用:電子郵件垃圾過濾。
准備數據:切分文本
采用正則表達式和split()函數進行,和Java語言的字符串分割基本類似,略去不講
1 def textParse(bigString): #input is big string, #output is word list 2 import re 3 listOfTokens = re.split(r'\W*', bigString) 4 return [tok.lower() for tok in listOfTokens if len(tok) > 2] 5 6 def spamTest(): 7 docList=[]; classList = []; fullText =[] 8 for i in range(1,26): #1,2,3.。。25 9 wordList = textParse(open('email/spam/%d.txt' % i).read()) 10 docList.append(wordList) 11 fullText.extend(wordList) 12 classList.append(1) 13 wordList = textParse(open('email/ham/%d.txt' % i).read()) 14 docList.append(wordList) 15 fullText.extend(wordList) 16 classList.append(0) 17 vocabList = createVocabList(docList)#create vocabulary 18 trainingSet = range(50); testSet=[] #create test set 19 for i in range(10): 20 randIndex = int(random.uniform(0,len(trainingSet))) 21 testSet.append(trainingSet[randIndex]) 22 del(trainingSet[randIndex]) 23 trainMat=[]; trainClasses = [] 24 for docIndex in trainingSet:#train the classifier (get probs) trainNB0 25 trainMat.append(bagOfWords2VecMN(vocabList, docList[docIndex])) 26 trainClasses.append(classList[docIndex]) 27 p0V,p1V,pSpam = trainNB0(array(trainMat),array(trainClasses)) 28 errorCount = 0 29 for docIndex in testSet: #classify the remaining items 30 wordVector = bagOfWords2VecMN(vocabList, docList[docIndex]) 31 if classifyNB(array(wordVector),p0V,p1V,pSpam) != classList[docIndex]: 32 errorCount += 1 33 print "classification error",docList[docIndex] 34 print 'the error rate is: ',float(errorCount)/len(testSet) 35 #return vocabList,fullText
第一個函數傳入一個字符串,將其轉化成字符串列表,並且去掉少於兩個字符的字符串,並將所有字符串轉換為小寫
第二個函數對貝葉斯垃圾郵件分類器進行自動化處理。導入文件夾spam和ham下的文版文件,並將其解析為詞列表。接下來構建一個測試集和一個訓練集,兩個集合中的郵件都是隨機選出的。總數有50封電子郵件,其中10封電子郵件被隨機選擇為測試集。分類器所需要的概率計算只利用訓練集中的文檔來完成。trainingSet是一個整數列表,值從0到49。接下來,隨機選擇其中10個文件,選出的數字所對應的文檔被添加到測試集,同時也將其從訓練集中剔除。這種隨機選擇數據的一部分作為訓練集,而剩余部分作為測試集的過程叫做留存交叉驗證。