资讯专栏INFORMATION COLUMN

机器学习 | 朴素贝叶斯

kohoh_ / 1971人阅读

摘要:由于近期学业繁重,所以我就不说废话了,直接上代码朴素贝叶斯进行文本词汇分类词表到向量的转换创建实验样本,返回的是进行词条切分后的文档集合,还有一个类别标签侮辱性的非侮辱性的代表侮辱性文字代表正常言论创建一个包含在所有文档中出现的不重复的词的

由于近期学业繁重QAQ,所以我就不说废话了,直接上代码~

朴素贝叶斯进行文本词汇分类
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()

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/20541.html

相关文章

  • 机器学习A-Z~朴素贝叶

    摘要:本文要讲述一个古老的机器学习算法,叫做朴素贝叶斯。带入贝叶斯定理公式结果为。朴素贝叶斯接下来来讲朴素贝叶斯分类器,我们要用到的就是上述的贝叶斯定理。这个是朴素贝叶斯中核心的一步。 本文要讲述一个古老的机器学习算法,叫做朴素贝叶斯。这个算法比较简单明了,没有使用非常复杂的数学定理。用到的核心的数学理论就是概率中的一个定理,叫做贝叶斯定理(Bayes Theorem)。 贝叶斯定理 现在我...

    twohappy 评论0 收藏0
  • 【数据科学系统学习机器学习算法 # 西瓜书学习记录 [4] 朴素贝叶

    摘要:又称贝叶斯原则。朴素贝叶斯分类器朴素贝叶斯的假设特征独立性一个特征出现的概率,与其它特征条件独立。这就是朴素贝叶斯法所采用的原理。解决这一问题的方法是采用贝叶斯估计。 本篇内容为西瓜书第 7 章贝叶斯分类器 7.3,7.1,7.2 的内容: 7.3 朴素贝叶斯分类器 7.1 贝叶斯决策论 7.2 极大似然估计 如移动端无法正常显示文中的公式,右上角跳至网页即可正常阅读。 贝叶斯法...

    summerpxy 评论0 收藏0
  • 机器学习从入门到放弃之朴素贝叶

    摘要:简介这次我们来谈谈机器学习中另外一个数学气息比较浓的算法朴素贝叶斯算法。既然如此,对机器学习感兴趣的同学,为什么不自己实现一次呢 简介 这次我们来谈谈机器学习中另外一个数学气息比较浓的算法朴素贝叶斯算法。 可能有朋友会看见数学气息比较浓心理就咯噔一下,先别急着叉掉本文,说朴素贝叶斯算法算法的数学气息比较浓,并非它有什么巨发杂的数学公式,而是它常见于概率统计之中,在本科教育就有对其比较详...

    DDreach 评论0 收藏0
  • 机器学习实战,使用朴素贝叶来做情感分析

    摘要:至于为什么选取朴素贝叶斯,很大一个原因是因为朴素贝叶斯在垃圾邮件分类上有不错的效果,而确定一个句子属于那种情感,和判断一封邮件是否为垃圾邮件有异曲同工之妙。 前言 前段时间更新了一系列基础的机器学习算法,感觉有些无味,而且恰好那时买了了国内某公司的云服务器,就打算部署一套文本处理的WEB API,顺别应用一下之前学习到的机器学习算法。(文末放出地址) 本文不会涉及过于复杂的数学原理,主...

    levinit 评论0 收藏0
  • 机器学习实战,使用朴素贝叶来做情感分析

    摘要:至于为什么选取朴素贝叶斯,很大一个原因是因为朴素贝叶斯在垃圾邮件分类上有不错的效果,而确定一个句子属于那种情感,和判断一封邮件是否为垃圾邮件有异曲同工之妙。 前言 前段时间更新了一系列基础的机器学习算法,感觉有些无味,而且恰好那时买了了国内某公司的云服务器,就打算部署一套文本处理的WEB API,顺别应用一下之前学习到的机器学习算法。(文末放出地址) 本文不会涉及过于复杂的数学原理,主...

    jsliang 评论0 收藏0
  • 机器学习3——朴素贝叶

    摘要:贝叶斯是基于概率论的分类方法,通过概率的方式来描述对象划分到某个分类的可能性。对象有多个属性假设各个属性之间是相互独立的,求解在出现的条件下各个类别出现的概率,选择最大的作为的分类,通过这种方法构造的分类算法称为朴素贝叶斯。 贝叶斯是基于概率论的分类方法,通过概率的方式来描述对象划分到某个分类的可能性。对象X有多个属性$$X={a_{1}, a_{2}, a_{3}, ... , a_...

    TesterHome 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<