機器學習 | 樸素貝葉斯

因爲近期學業繁重QAQ,因此我就不說廢話了,直接上代碼~app

樸素貝葉斯進行文本詞彙分類

from numpy import *

#詞表到向量的轉換
#建立實驗樣本,返回的是進行詞條切分後的文檔集合,
#還有一個類別標籤——侮辱性的or非侮辱性的
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']]
    #1 表明侮辱性文字   0表明正常言論
    classVec = [0,1,0,1,0,1]
    return postingList,classVec
    
#建立一個包含在全部文檔中出現的不重複的詞的列表    
def createVocabList(dataSet):
    vocabSet=set([])
    #document:['my', 'dog', 'has', 'flea', 'problems', 'help', 'please']
    for document in dataSet:
        #求並集
        vocabSet=vocabSet|set(document)
        #print(vocabSet)
    return list(vocabSet)
    
#參數爲詞彙表以及某個文檔,輸出的是文檔向量
#輸出的向量的每個元素爲1或0,表示詞彙表中
#的單詞在輸入文檔中是否出現
def setOfWords2Vec(vocabList,inputSet):
    #建立一個所含元素都爲0的向量
    returnVec=[0]*len(vocabList)
    #遍歷文檔中的全部單詞,若是出現了詞彙表中的單詞,
    #則將輸出文檔的對應值設爲1
    for word in inputSet:
        if word in vocabList:
            returnVec[vocabList.index(word)]=1
        else:
            print("the word: %s is not in my Vocabulary!"%word)
    return returnVec
    

    

#輸入的參數:文檔矩陣trainMatrix
#由每篇文檔類別標籤構成的向量trainCategory
#樸素貝葉斯分類器訓練函數
#trainMatrix:每一個詞向量中的詞,在詞彙表中出現的就是1
#trainMatrix:[[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], 
#[0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0],
#[1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
#[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0], 
#[0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1], 
#[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0]]
#該詞向量中帶有侮辱性的詞的就是1
#trainCategory:[0, 1, 0, 1, 0, 1]
def trainNBO(trainMatrix,trainCategory):
    #一共有幾個詞向量
    numTrainDocs=len(trainMatrix)
    #詞彙表的長度
    numWords=len(trainMatrix[0])
    #3/6 表示6個詞向量中,3個帶侮辱詞
    pAbusive=sum(trainCategory)/float(numTrainDocs)
    #初始化機率
    p0Num=ones(numWords)
    p1Num=ones(numWords)
    p0Denom=2.0;p1Denom=2.0
    #遍歷訓練集trainMatrix中的全部文檔
    #一旦某個詞在某一文檔中出現
    #該文檔的總詞數加1
    #兩個類別都要進行一樣的處理
    #i:012345
    for i in range(numTrainDocs):
        #該詞向量帶侮辱
        if trainCategory[i]==1:
            #向量相加
            p1Num+=trainMatrix[i]
            p1Denom+=sum(trainMatrix[i])
        else:
            p0Num+=trainMatrix[i]
            p0Denom+=sum(trainMatrix[i])
    #每一個元素除以該類別的總詞數
    p1Vect=log(p1Num/p1Denom)
    p0Vect=log(p0Num/p0Denom)
    return p0Vect,p1Vect,pAbusive
            
    
    
    
#樸素貝葉斯分類函數
def classifyNB(vec2Classify,p0Vec,p1Vec,pClass1):
    #元素相乘
    p1=sum(vec2Classify*p1Vec)+log(pClass1)
    p0=sum(vec2Classify*p0Vec)+log(1.0-pClass1)
    if p1>p0:
        return 1
    else:
        return 0    
    
    
def testingNB():
    listOPosts,listClasses=loadDataSet()
    myVocabList=createVocabList(listOPosts)
    trainMat=[]
    #使用詞向量填充trainMat列表
    for postinDoc in listOPosts:
        Vec01=setOfWords2Vec(myVocabList,postinDoc)
        trainMat.append(Vec01)    
    p0V,p1V,pAb=trainNBO(trainMat,listClasses)
    #測試集
    testEntry=['love','my','dalmation']
    thisDoc=array(setOfWords2Vec(myVocabList,testEntry))
    #print(thisDoc)
    print(testEntry,' classified as: ',classifyNB(thisDoc,p0V,p1V,pAb))
    testEntry=['stupid','garbage']
    thisDoc=array(setOfWords2Vec(myVocabList,testEntry))
    #print(thisDoc)
    print(testEntry,' classified as: ',classifyNB(thisDoc,p0V,p1V,pAb))

    
def main():
    testingNB()
    #建立數據    
    #listOPosts,listClasses=loadDataSet()
    #print(listOPosts)
    #構建一個包含全部詞的列表
    #myVocabList=createVocabList(listOPosts)
    #print(myVocabList)
    #returnVec=setOfWords2Vec(myVocabList,listOPosts[0])
    #print(returnVec)
    #trainMat=[]
    #使用詞向量填充trainMat列表
    #for postinDoc in listOPosts:
        #傳入詞彙表 以及每一行詞向量
        #返回的是一個與詞彙表一樣size的向量
        #1表示這個詞在詞向量中出現過
        #Vec01=setOfWords2Vec(myVocabList,postinDoc)
        #print(Vec01)
        #將01list填充trainMat
        #trainMat.append(Vec01)
    #print(trainMat)
    #print(listClasses)
    #p0V,p1V,pAB=trainNBO(trainMat,listClasses)
    #print(p0V)
    #print(p1V)
    #print(pAB)
    
if __name__=='__main__':
    main()



樸素貝葉斯分類垃圾郵件

#文件解析及完整的垃圾郵件測試函數
#返回傳入的bigString中的單詞
#接收一大個字符串並將其解析爲字符串列表
#去掉少於兩個字符的字符串,並將全部的字符串轉換成小寫
def textParse(bigString):
    listOfTokens=re.split(r'\W*',bigString)
    return [tok.lower() for tok in listOfTokens if len(tok)>2]


#對貝葉斯垃圾郵件分類器進行自動化處理
#導入spam與ham下的文本文件,並將它們轉換爲詞列表
#存留交叉驗證:隨機選擇數據中的一部分做爲訓練集,
#而剩餘的部分做爲測試集
def spamTest():
    docList=[]
    classList=[]
    fullText=[]
    for i in range(1,26):
        wordList=textParse(open('./MLiA_SourceCode/machinelearninginaction/Ch04/email/spam/%d.txt' % i).read())
        #每篇郵件中組成的list
        #[[...],[...],[...]...]
        docList.append(wordList)
        #所有郵件組成的大list
        #[...]
        fullText.extend(wordList)
        #1010組成的list
        classList.append(1)
        wordList=textParse(open('./MLiA_SourceCode/machinelearninginaction/Ch04/email/ham/%d.txt' % i).read())
        docList.append(wordList)
        fullText.extend(wordList)
        classList.append(0)
    #print(docList)
    #print(fullText)
    #print(classList)
    #建立詞彙表——全部的單詞都只出現一次
    vocabList=createVocabList(docList)
    #print(vocabList)
    #[1,2,...49]
    trainingSet=list(range(50))
    #print(trainingSet)
    testSet=[]
    #建立測試集
    #隨機選取10個文件做爲測試集
    for i in range(10):
        #在1-49中取隨機數
        randIndex=int(random.uniform(0,len(trainingSet)))
        #print(randIndex)
        testSet.append(trainingSet[randIndex])
        #將選出來的數從訓練集中delete
        del(trainingSet[randIndex])
    #[2, 6, 15, 31, 23, 12, 3, 17, 37, 47]
    #print(testSet)    
    trainMat=[]
    trainClasses=[]
    #進行訓練
    for docIndex in trainingSet:
        #返回一個和詞彙表size同樣的list,爲1的表示這個詞彙在詞彙表中出現過
        trainMat.append(setOfWords2Vec(vocabList,docList[docIndex]))
        trainClasses.append(classList[docIndex])
    #print(trainMat)
    #print(trainClasses)
    #計算分類所需的機率
    p0V,p1V,pSpam=trainNBO(array(trainMat),array(trainClasses))
    errorCount=0
    #進行測試
    #遍歷測試集,進行分類
    for docIndex in testSet:
        wordVector=setOfWords2Vec(vocabList,docList[docIndex])
        #對測試集分類的準確性進行判斷
        if classifyNB(array(wordVector),p0V,p1V,pSpam)!=classList[docIndex]:
            errorCount+=1
            print("classification error",docList[docIndex])
    #求出平均錯誤率
    print('the error rate is: ',float(errorCount)/len(testSet))



使用樸素貝葉斯分類器從我的廣告中獲取區域傾向

#使用樸素貝葉斯分類器從我的廣告中獲取區域傾向
#rss源:https://www.nasa.gov/rss/dyn/image_of_the_day.rss
#http://www.ftchinese.com/rss/news
#RSS源分類器及高頻詞去除函數
#遍歷詞彙表中的每一個詞 並統計他在文本中出現的次數
#根據出現次數從高到低對詞典進行排序,最後返回排序最高的100個詞
def calcMostFreq(vocabList,fullText):
    freqDict={}
    for token in vocabList:
        freqDict[token]=fullText.count(token)
    #獲得詞彙及其出現的次數
    #{'hours': 1, 'airbus': 1, '柯特妮': 1, ... }
    #print(freqDict)
    sortedFreq=sorted(freqDict.items(),key=operator.itemgetter(1),reverse=True)
    #進行排序
    #[('the', 32), ('http', 22), ('ftimg', 20), ... ]
    #print(sortedFreq)
    return sortedFreq[:30]
    
    
#使用兩個rss源做爲參數    
def localWords(feed1,feed0):
    docList=[]
    classList=[]
    fullText=[]
    minLen=min(len(feed1['entries']),len(feed0['entries']))
    for i in range(minLen):
        #將summary的內容拆分紅一個個單詞
        wordList=textParse(feed1['entries'][i]['summary'])
        docList.append(wordList)
        fullText.extend(wordList)
        classList.append(1)
        wordList=textParse(feed0['entries'][i]['summary'])
        docList.append(wordList)
        fullText.extend(wordList)
        classList.append(0)
    #建立詞彙表
    vocabList=createVocabList(docList)
    
    ##增長下面三行代碼會致使錯誤率升高
    
    #獲得詞彙表中出現頻率最高的top30
    top30Words=calcMostFreq(vocabList,fullText)
    #將高頻詞彙去除
    for pairW in top30Words:
        if pairW[0] in vocabList: vocabList.remove(pairW[0])
    
    ##
    
    #建立訓練集與測試集
    trainingSet=list(range(2*minLen))
    testSet=[]
    for i in range(20):
        randIndex=int(random.uniform(0,len(trainingSet)))
        testSet.append(trainingSet[randIndex])
        del(trainingSet[randIndex])
    trainMat=[]
    trainClasses=[]
    
    #開始訓練
    for docIndex in trainingSet:
        trainMat.append(bagOfWords2VecMN(vocabList,docList[docIndex]))
        trainClasses.append(classList[docIndex])
    #print(trainMat)
    
    p0V,p1V,pSpam=trainNBO(array(trainMat),array(trainClasses))
    errorCount=0
    for docIndex in testSet:
        wordVector=bagOfWords2VecMN(vocabList,docList[docIndex])
        if classifyNB(array(wordVector),p0V,p1V,pSpam)!=classList[docIndex]:
            errorCount+=1
    print('the error rate is: ',float(errorCount)/len(testSet))
    return vocabList,p0V,p1V
    
    
#顯示地域相關的用詞
def getTopWords(ny,sf):
    import operator
    vocabList,p0V,p1V=localWords(ny,sf)
    topNY=[]
    topSF=[]
    for i in range(len(p0V)):
        #print(p0V[i])
        if p0V[i]>-5.0:
            topSF.append((vocabList[i],p0V[i]))
        if p1V[i]>-5.0:
            topNY.append((vocabList[i],p1V[i]))
    sortedSF=sorted(topSF,key=lambda pair:pair[1],reverse=True)
    print("SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF")
    for item in sortedSF:
        print(item[0])
    sortedNY=sorted(topNY,key=lambda pair:pair[1],reverse=True)
    print("NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY")
    for item in sortedNY:
        print(item[0])



完整代碼

from numpy import *
import feedparser
import re
import operator

#詞表到向量的轉換
#建立實驗樣本,返回的是進行詞條切分後的文檔集合,
#還有一個類別標籤——侮辱性的or非侮辱性的
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']]
    #1 表明侮辱性文字   0表明正常言論
    classVec = [0,1,0,1,0,1]
    return postingList,classVec
    
#建立一個包含在全部文檔中出現的不重複的詞的列表    
def createVocabList(dataSet):
    vocabSet=set([])
    #document:['my', 'dog', 'has', 'flea', 'problems', 'help', 'please']
    for document in dataSet:
        #求並集
        vocabSet=vocabSet|set(document)
        #print(vocabSet)
    return list(vocabSet)
    
#參數爲詞彙表以及某個文檔,輸出的是文檔向量
#輸出的向量的每個元素爲1或0,表示詞彙表中
#的單詞在輸入文檔中是否出現
def setOfWords2Vec(vocabList,inputSet):
    #建立一個所含元素都爲0的向量
    returnVec=[0]*len(vocabList)
    #遍歷文檔中的全部單詞,若是出現了詞彙表中的單詞,
    #則將輸出文檔的對應值設爲1
    for word in inputSet:
        if word in vocabList:
            returnVec[vocabList.index(word)]=1
        else:
            print("the word: %s is not in my Vocabulary!"%word)
    return returnVec
    
    
#樸素貝葉斯詞袋模型
#與上面的setOfWords2Vec功能基本相同,
#只是每遇到一個單詞就會增長詞向量中對應的值
#而不是簡單地設置1
def bagOfWords2VecMN(vocabList,inputSet):
    returnVec =[0]*len(vocabList)
    for word in inputSet:
        if word in vocabList:
            returnVec[vocabList.index(word)]+=1
    return returnVec
    

    

#輸入的參數:文檔矩陣trainMatrix
#由每篇文檔類別標籤構成的向量trainCategory
#樸素貝葉斯分類器訓練函數
#trainMatrix:每一個詞向量中的詞,在詞彙表中出現的就是1
#trainMatrix:[[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], 
#[0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0],
#[1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
#[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0], 
#[0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1], 
#[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0]]
#該詞向量中帶有侮辱性的詞的就是1
#trainCategory:[0, 1, 0, 1, 0, 1]
def trainNBO(trainMatrix,trainCategory):
    #一共有幾個詞向量
    numTrainDocs=len(trainMatrix)
    #詞彙表的長度
    numWords=len(trainMatrix[0])
    #3/6 表示6個詞向量中,3個帶侮辱詞
    pAbusive=sum(trainCategory)/float(numTrainDocs)
    #初始化機率
    p0Num=ones(numWords)
    p1Num=ones(numWords)
    p0Denom=2.0;p1Denom=2.0
    #遍歷訓練集trainMatrix中的全部文檔
    #一旦某個詞在某一文檔中出現
    #該文檔的總詞數加1
    #兩個類別都要進行一樣的處理
    #i:012345
    for i in range(numTrainDocs):
        #該詞向量帶侮辱
        if trainCategory[i]==1:
            #向量相加
            p1Num+=trainMatrix[i]
            p1Denom+=sum(trainMatrix[i])
        else:
            p0Num+=trainMatrix[i]
            p0Denom+=sum(trainMatrix[i])
    #每一個元素除以該類別的總詞數
    p1Vect=log(p1Num/p1Denom)
    p0Vect=log(p0Num/p0Denom)
    return p0Vect,p1Vect,pAbusive
            
    
    
    
#樸素貝葉斯分類函數
def classifyNB(vec2Classify,p0Vec,p1Vec,pClass1):
    #元素相乘
    p1=sum(vec2Classify*p1Vec)+log(pClass1)
    p0=sum(vec2Classify*p0Vec)+log(1.0-pClass1)
    if p1>p0:
        return 1
    else:
        return 0    
    
    
def testingNB():
    listOPosts,listClasses=loadDataSet()
    myVocabList=createVocabList(listOPosts)
    trainMat=[]
    #使用詞向量填充trainMat列表
    for postinDoc in listOPosts:
        Vec01=setOfWords2Vec(myVocabList,postinDoc)
        trainMat.append(Vec01)    
    p0V,p1V,pAb=trainNBO(trainMat,listClasses)
    #測試集
    testEntry=['love','my','dalmation']
    thisDoc=array(setOfWords2Vec(myVocabList,testEntry))
    #print(thisDoc)
    print(testEntry,' classified as: ',classifyNB(thisDoc,p0V,p1V,pAb))
    testEntry=['stupid','garbage']
    thisDoc=array(setOfWords2Vec(myVocabList,testEntry))
    #print(thisDoc)
    print(testEntry,' classified as: ',classifyNB(thisDoc,p0V,p1V,pAb))

    
#文件解析及完整的垃圾郵件測試函數
#返回傳入的bigString中的單詞
#接收一大個字符串並將其解析爲字符串列表
#去掉少於兩個字符的字符串,並將全部的字符串轉換成小寫
def textParse(bigString):
    listOfTokens=re.split(r'\W*',bigString)
    return [tok.lower() for tok in listOfTokens if len(tok)>2]


#對貝葉斯垃圾郵件分類器進行自動化處理
#導入spam與ham下的文本文件,並將它們轉換爲詞列表
#存留交叉驗證:隨機選擇數據中的一部分做爲訓練集,
#而剩餘的部分做爲測試集
def spamTest():
    docList=[]
    classList=[]
    fullText=[]
    for i in range(1,26):
        wordList=textParse(open('./MLiA_SourceCode/machinelearninginaction/Ch04/email/spam/%d.txt' % i).read())
        #每篇郵件中組成的list
        #[[...],[...],[...]...]
        docList.append(wordList)
        #所有郵件組成的大list
        #[...]
        fullText.extend(wordList)
        #1010組成的list
        classList.append(1)
        wordList=textParse(open('./MLiA_SourceCode/machinelearninginaction/Ch04/email/ham/%d.txt' % i).read())
        docList.append(wordList)
        fullText.extend(wordList)
        classList.append(0)
    #print(docList)
    #print(fullText)
    #print(classList)
    #建立詞彙表——全部的單詞都只出現一次
    vocabList=createVocabList(docList)
    #print(vocabList)
    #[1,2,...49]
    trainingSet=list(range(50))
    #print(trainingSet)
    testSet=[]
    #建立測試集
    #隨機選取10個文件做爲測試集
    for i in range(10):
        #在1-49中取隨機數
        randIndex=int(random.uniform(0,len(trainingSet)))
        #print(randIndex)
        testSet.append(trainingSet[randIndex])
        #將選出來的數從訓練集中delete
        del(trainingSet[randIndex])
    #[2, 6, 15, 31, 23, 12, 3, 17, 37, 47]
    #print(testSet)    
    trainMat=[]
    trainClasses=[]
    #進行訓練
    for docIndex in trainingSet:
        #返回一個和詞彙表size同樣的list,爲1的表示這個詞彙在詞彙表中出現過
        trainMat.append(setOfWords2Vec(vocabList,docList[docIndex]))
        trainClasses.append(classList[docIndex])
    #print(trainMat)
    #print(trainClasses)
    #計算分類所需的機率
    p0V,p1V,pSpam=trainNBO(array(trainMat),array(trainClasses))
    errorCount=0
    #進行測試
    #遍歷測試集,進行分類
    for docIndex in testSet:
        wordVector=setOfWords2Vec(vocabList,docList[docIndex])
        #對測試集分類的準確性進行判斷
        if classifyNB(array(wordVector),p0V,p1V,pSpam)!=classList[docIndex]:
            errorCount+=1
            print("classification error",docList[docIndex])
    #求出平均錯誤率
    print('the error rate is: ',float(errorCount)/len(testSet))
        
        
    
    
#使用樸素貝葉斯分類器從我的廣告中獲取區域傾向
#rss源:https://www.nasa.gov/rss/dyn/image_of_the_day.rss
#http://www.ftchinese.com/rss/news
#RSS源分類器及高頻詞去除函數
#遍歷詞彙表中的每一個詞 並統計他在文本中出現的次數
#根據出現次數從高到低對詞典進行排序,最後返回排序最高的100個詞
def calcMostFreq(vocabList,fullText):
    freqDict={}
    for token in vocabList:
        freqDict[token]=fullText.count(token)
    #獲得詞彙及其出現的次數
    #{'hours': 1, 'airbus': 1, '柯特妮': 1, ... }
    #print(freqDict)
    sortedFreq=sorted(freqDict.items(),key=operator.itemgetter(1),reverse=True)
    #進行排序
    #[('the', 32), ('http', 22), ('ftimg', 20), ... ]
    #print(sortedFreq)
    return sortedFreq[:30]
    
    
#使用兩個rss源做爲參數    
def localWords(feed1,feed0):
    docList=[]
    classList=[]
    fullText=[]
    minLen=min(len(feed1['entries']),len(feed0['entries']))
    for i in range(minLen):
        #將summary的內容拆分紅一個個單詞
        wordList=textParse(feed1['entries'][i]['summary'])
        docList.append(wordList)
        fullText.extend(wordList)
        classList.append(1)
        wordList=textParse(feed0['entries'][i]['summary'])
        docList.append(wordList)
        fullText.extend(wordList)
        classList.append(0)
    #建立詞彙表
    vocabList=createVocabList(docList)
    
    ##增長下面三行代碼會致使錯誤率升高
    
    #獲得詞彙表中出現頻率最高的top30
    top30Words=calcMostFreq(vocabList,fullText)
    #將高頻詞彙去除
    for pairW in top30Words:
        if pairW[0] in vocabList: vocabList.remove(pairW[0])
    
    ##
    
    #建立訓練集與測試集
    trainingSet=list(range(2*minLen))
    testSet=[]
    for i in range(20):
        randIndex=int(random.uniform(0,len(trainingSet)))
        testSet.append(trainingSet[randIndex])
        del(trainingSet[randIndex])
    trainMat=[]
    trainClasses=[]
    
    #開始訓練
    for docIndex in trainingSet:
        trainMat.append(bagOfWords2VecMN(vocabList,docList[docIndex]))
        trainClasses.append(classList[docIndex])
    #print(trainMat)
    
    p0V,p1V,pSpam=trainNBO(array(trainMat),array(trainClasses))
    errorCount=0
    for docIndex in testSet:
        wordVector=bagOfWords2VecMN(vocabList,docList[docIndex])
        if classifyNB(array(wordVector),p0V,p1V,pSpam)!=classList[docIndex]:
            errorCount+=1
    print('the error rate is: ',float(errorCount)/len(testSet))
    return vocabList,p0V,p1V
    
    
#顯示地域相關的用詞
def getTopWords(ny,sf):
    import operator
    vocabList,p0V,p1V=localWords(ny,sf)
    topNY=[]
    topSF=[]
    for i in range(len(p0V)):
        #print(p0V[i])
        if p0V[i]>-5.0:
            topSF.append((vocabList[i],p0V[i]))
        if p1V[i]>-5.0:
            topNY.append((vocabList[i],p1V[i]))
    sortedSF=sorted(topSF,key=lambda pair:pair[1],reverse=True)
    print("SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF")
    for item in sortedSF:
        print(item[0])
    sortedNY=sorted(topNY,key=lambda pair:pair[1],reverse=True)
    print("NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY")
    for item in sortedNY:
        print(item[0])
        
    
    
#rss源:https://www.nasa.gov/rss/dyn/image_of_the_day.rss
#http://www.ftchinese.com/rss/news
def main():
    ny=feedparser.parse('https://www.nasa.gov/rss/dyn/image_of_the_day.rss')
    sf=feedparser.parse('http://www.ftchinese.com/rss/news')
    #vocabList,pSF,pNY=localWords(ny,sf)
    getTopWords(ny,sf)
    #vocabList,pSF,pNY=localWords(ny,sf)
    #spamTest()
    #testingNB()
    #建立數據    
    #listOPosts,listClasses=loadDataSet()
    #print(listOPosts)
    #構建一個包含全部詞的列表
    #myVocabList=createVocabList(listOPosts)
    #print(myVocabList)
    #returnVec=setOfWords2Vec(myVocabList,listOPosts[0])
    #print(returnVec)
    #trainMat=[]
    #使用詞向量填充trainMat列表
    #for postinDoc in listOPosts:
        #傳入詞彙表 以及每一行詞向量
        #返回的是一個與詞彙表一樣size的向量
        #1表示這個詞在詞向量中出現過
        #Vec01=setOfWords2Vec(myVocabList,postinDoc)
        #print(Vec01)
        #將01list填充trainMat
        #trainMat.append(Vec01)
    #print(trainMat)
    #print(listClasses)
    #p0V,p1V,pAB=trainNBO(trainMat,listClasses)
    #print(p0V)
    #print(p1V)
    #print(pAB)
    
if __name__=='__main__':
    main()
相關文章
相關標籤/搜索