1. <ul id="0c1fb"></ul>

      <noscript id="0c1fb"><video id="0c1fb"></video></noscript>
      <noscript id="0c1fb"><listing id="0c1fb"><thead id="0c1fb"></thead></listing></noscript>

      99热在线精品一区二区三区_国产伦精品一区二区三区女破破_亚洲一区二区三区无码_精品国产欧美日韩另类一区

      RELATEED CONSULTING
      相關(guān)咨詢
      選擇下列產(chǎn)品馬上在線溝通
      服務(wù)時間:8:30-17:00
      你可能遇到了下面的問題
      關(guān)閉右側(cè)工具欄

      新聞中心

      這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
      怎么在Python中實現(xiàn)一個樸素貝葉斯算法-創(chuàng)新互聯(lián)

      本篇文章為大家展示了怎么在Python中實現(xiàn)一個樸素貝葉斯算法,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

      成都創(chuàng)新互聯(lián)公司網(wǎng)站建設(shè)服務(wù)商,為中小企業(yè)提供成都網(wǎng)站制作、成都網(wǎng)站設(shè)計服務(wù),網(wǎng)站設(shè)計,成都網(wǎng)站托管等一站式綜合服務(wù)型公司,專業(yè)打造企業(yè)形象網(wǎng)站,讓您在眾多競爭對手中脫穎而出成都創(chuàng)新互聯(lián)公司
      #encoding:utf-8
      #在該算法中類標簽為1和0,如果是多標簽稍微改動代碼既可
      import numpy as np
      path=u"D:\\Users\\zhoumeixu204\Desktop\\python語言機器學(xué)習(xí)\\機器學(xué)習(xí)實戰(zhàn)代碼  python\\機器學(xué)習(xí)實戰(zhàn)代碼\\machinelearninginaction\\Ch04\\"
      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]  #1 is abusive, 0 not
        return postingList,classVec
      def createVocabList(dataset):
        vocabSet=set([])
        for document in dataset:
          vocabSet=vocabSet|set(document)
        return list(vocabSet)
      def setOfWordseVec(vocabList,inputSet):
        returnVec=[0]*len(vocabList)
        for word in inputSet:
          if word in vocabList:
            returnVec[vocabList.index(word)]=1  #vocabList.index() 函數(shù)獲取vocabList列表某個元素的位置,這段代碼得到一個只包含0和1的列表
          else:
            print("the word :%s is not in my Vocabulary!"%word)
        return returnVec
      listOPosts,listClasses=loadDataSet()
      myVocabList=createVocabList(listOPosts)
      print(len(myVocabList))
      print(myVocabList)
      print(setOfWordseVec(myVocabList, listOPosts[0]))
      print(setOfWordseVec(myVocabList, listOPosts[3]))
      #上述代碼是將文本轉(zhuǎn)化為向量的形式,如果出現(xiàn)則在向量中為1,若不出現(xiàn) ,則為0
      def trainNB0(trainMatrix,trainCategory):  #創(chuàng)建樸素貝葉斯分類器函數(shù)
        numTrainDocs=len(trainMatrix)
        numWords=len(trainMatrix[0])
        pAbusive=sum(trainCategory)/float(numTrainDocs)
        p0Num=np.ones(numWords);p1Num=np.ones(numWords)
        p0Deom=2.0;p1Deom=2.0
        for i in range(numTrainDocs):
          if trainCategory[i]==1:
            p1Num+=trainMatrix[i]
            p1Deom+=sum(trainMatrix[i])
          else:
            p0Num+=trainMatrix[i]
            p0Deom+=sum(trainMatrix[i])
        p1vect=np.log(p1Num/p1Deom)  #change to log
        p0vect=np.log(p0Num/p0Deom)  #change to log
        return p0vect,p1vect,pAbusive
      listOPosts,listClasses=loadDataSet()
      myVocabList=createVocabList(listOPosts)
      trainMat=[]
      for postinDoc in listOPosts:
        trainMat.append(setOfWordseVec(myVocabList, postinDoc))
      p0V,p1V,pAb=trainNB0(trainMat, listClasses)
      if __name__!='__main__':
        print("p0的概況")
        print (p0V)
        print("p1的概率")
        print (p1V)
        print("pAb的概率")
        print (pAb)

      運行結(jié)果:

      32
      ['him', 'garbage', 'problems', 'take', 'steak', 'quit', 'so', 'is', 'cute', 'posting', 'dog', 'to', 'love', 'licks', 'dalmation', 'flea', 'I', 'please', 'maybe', 'buying', 'my', 'stupid', 'park', 'food', 'stop', 'has', 'ate', 'help', 'how', 'mr', 'worthless', 'not']
      [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 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, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]

      # -*- coding:utf-8 -*-
      #!python2
      #構(gòu)建樣本分類器testEntry=['love','my','dalmation'] testEntry=['stupid','garbage']到底屬于哪個類別
      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]  #1 is abusive, 0 not
        return postingList,classVec
      def createVocabList(dataset):
        vocabSet=set([])
        for document in dataset:
          vocabSet=vocabSet|set(document)
        return list(vocabSet)
      def setOfWordseVec(vocabList,inputSet):
        returnVec=[0]*len(vocabList)
        for word in inputSet:
          if word in vocabList:
            returnVec[vocabList.index(word)]=1  #vocabList.index() 函數(shù)獲取vocabList列表某個元素的位置,這段代碼得到一個只包含0和1的列表
          else:
            print("the word :%s is not in my Vocabulary!"%word)
        return returnVec
      def trainNB0(trainMatrix,trainCategory):  #創(chuàng)建樸素貝葉斯分類器函數(shù)
        numTrainDocs=len(trainMatrix)
        numWords=len(trainMatrix[0])
        pAbusive=sum(trainCategory)/float(numTrainDocs)
        p0Num=np.ones(numWords);p1Num=np.ones(numWords)
        p0Deom=2.0;p1Deom=2.0
        for i in range(numTrainDocs):
          if trainCategory[i]==1:
            p1Num+=trainMatrix[i]
            p1Deom+=sum(trainMatrix[i])
          else:
            p0Num+=trainMatrix[i]
            p0Deom+=sum(trainMatrix[i])
        p1vect=np.log(p1Num/p1Deom)  #change to log
        p0vect=np.log(p0Num/p0Deom)  #change to log
        return p0vect,p1vect,pAbusive
      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(setOfWordseVec(myVocabList, postinDoc))
        p0V,p1V,pAb=trainNB0(np.array(trainMat),np.array(listClasses))
        print("p0V={0}".format(p0V))
        print("p1V={0}".format(p1V))
        print("pAb={0}".format(pAb))
        testEntry=['love','my','dalmation']
        thisDoc=np.array(setOfWordseVec(myVocabList, testEntry))
        print(thisDoc)
        print("vec2Classify*p0Vec={0}".format(thisDoc*p0V))
        print(testEntry,'classified as :',classifyNB(thisDoc, p0V, p1V, pAb))
        testEntry=['stupid','garbage']
        thisDoc=np.array(setOfWordseVec(myVocabList, testEntry))
        print(thisDoc)
        print(testEntry,'classified as :',classifyNB(thisDoc, p0V, p1V, pAb))
      if __name__=='__main__':
        testingNB()

      運行結(jié)果:

      p0V=[-3.25809654 -2.56494936 -3.25809654 -3.25809654 -2.56494936 -2.56494936
       -3.25809654 -2.56494936 -2.56494936 -3.25809654 -2.56494936 -2.56494936
       -2.56494936 -2.56494936 -1.87180218 -2.56494936 -2.56494936 -2.56494936
       -2.56494936 -2.56494936 -2.56494936 -3.25809654 -3.25809654 -2.56494936
       -2.56494936 -3.25809654 -2.15948425 -2.56494936 -3.25809654 -2.56494936
       -3.25809654 -3.25809654]
      p1V=[-2.35137526 -3.04452244 -1.94591015 -2.35137526 -1.94591015 -3.04452244
       -2.35137526 -3.04452244 -3.04452244 -1.65822808 -3.04452244 -3.04452244
       -2.35137526 -3.04452244 -3.04452244 -3.04452244 -3.04452244 -3.04452244
       -3.04452244 -3.04452244 -3.04452244 -2.35137526 -2.35137526 -3.04452244
       -3.04452244 -2.35137526 -2.35137526 -3.04452244 -2.35137526 -2.35137526
       -2.35137526 -2.35137526]
      pAb=0.5
      [0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0]
      vec2Classify*p0Vec=[-0.         -0.         -0.         -0.         -0.         -0.         -0.
       -0.         -0.         -0.         -0.         -0.         -0.         -0.
       -1.87180218 -0.         -0.         -2.56494936 -0.         -0.         -0.
       -0.         -0.         -0.         -0.         -0.         -0.
       -2.56494936 -0.         -0.         -0.         -0.        ]
      ['love', 'my', 'dalmation'] classified as : 0
      [0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]
      ['stupid', 'garbage'] classified as : 1

      # -*- coding:utf-8 -*-
      #! python2
      #使用樸素貝葉斯過濾垃圾郵件
      # 1.收集數(shù)據(jù):提供文本文件
      # 2.準備數(shù)據(jù):講文本文件見習(xí)成詞條向量
      # 3.分析數(shù)據(jù):檢查詞條確保解析的正確性
      # 4.訓(xùn)練算法:使用我們之前簡歷的trainNB0()函數(shù)
      # 5.測試算法:使用classifyNB(),并且對建一個新的測試函數(shù)來計算文檔集的錯誤率
      # 6.使用算法,構(gòu)建一個完整的程序?qū)σ唤M文檔進行分類,將錯分的文檔輸出到屏幕上
      # import re
      # mySent='this book is the best book on python or M.L. I hvae ever laid eyes upon.'
      # print(mySent.split())
      # regEx=re.compile('\\W*')
      # print(regEx.split(mySent))
      # emailText=open(path+"email\\ham\\6.txt").read()
      import numpy as np
      path=u"C:\\py\\jb51PyDemo\\src\\Demo\\Ch04\\"
      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]  #1 is abusive, 0 not
        return postingList,classVec
      def createVocabList(dataset):
        vocabSet=set([])
        for document in dataset:
          vocabSet=vocabSet|set(document)
        return list(vocabSet)
      def setOfWordseVec(vocabList,inputSet):
        returnVec=[0]*len(vocabList)
        for word in inputSet:
          if word in vocabList:
            returnVec[vocabList.index(word)]=1  #vocabList.index() 函數(shù)獲取vocabList列表某個元素的位置,這段代碼得到一個只包含0和1的列表
          else:
            print("the word :%s is not in my Vocabulary!"%word)
        return returnVec
      def trainNB0(trainMatrix,trainCategory):  #創(chuàng)建樸素貝葉斯分類器函數(shù)
        numTrainDocs=len(trainMatrix)
        numWords=len(trainMatrix[0])
        pAbusive=sum(trainCategory)/float(numTrainDocs)
        p0Num=np.ones(numWords);p1Num=np.ones(numWords)
        p0Deom=2.0;p1Deom=2.0
        for i in range(numTrainDocs):
          if trainCategory[i]==1:
            p1Num+=trainMatrix[i]
            p1Deom+=sum(trainMatrix[i])
          else:
            p0Num+=trainMatrix[i]
            p0Deom+=sum(trainMatrix[i])
        p1vect=np.log(p1Num/p1Deom)  #change to log
        p0vect=np.log(p0Num/p0Deom)  #change to log
        return p0vect,p1vect,pAbusive
      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 textParse(bigString):
        import re
        listOfTokens=re.split(r'\W*',bigString)
        return [tok.lower() for tok in listOfTokens if len(tok)>2]
      def spamTest():
        docList=[];classList=[];fullText=[]
        for i in range(1,26):
          wordList=textParse(open(path+"email\\spam\\%d.txt"%i).read())
          docList.append(wordList)
          fullText.extend(wordList)
          classList.append(1)
          wordList=textParse(open(path+"email\\ham\\%d.txt"%i).read())
          docList.append(wordList)
          fullText.extend(wordList)
          classList.append(0)
        vocabList=createVocabList(docList)
        trainingSet=range(50);testSet=[]
        for i in range(10):
          randIndex=int(np.random.uniform(0,len(trainingSet)))
          testSet.append(trainingSet[randIndex])
          del (trainingSet[randIndex])
        trainMat=[];trainClasses=[]
        for  docIndex in trainingSet:
          trainMat.append(setOfWordseVec(vocabList, docList[docIndex]))
          trainClasses.append(classList[docIndex])
        p0V,p1V,pSpam=trainNB0(np.array(trainMat),np.array(trainClasses))
        errorCount=0
        for  docIndex in testSet:
          wordVector=setOfWordseVec(vocabList, docList[docIndex])
          if classifyNB(np.array(wordVector), p0V, p1V, pSpam)!=classList[docIndex]:
            errorCount+=1
        print 'the error rate is :',float(errorCount)/len(testSet)
      if __name__=='__main__':
        spamTest()

      運行結(jié)果:

      the error rate is : 0.0

      上述內(nèi)容就是怎么在Python中實現(xiàn)一個樸素貝葉斯算法,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。


      分享題目:怎么在Python中實現(xiàn)一個樸素貝葉斯算法-創(chuàng)新互聯(lián)
      網(wǎng)址分享:http://www.ef60e0e.cn/article/djsdco.html
      99热在线精品一区二区三区_国产伦精品一区二区三区女破破_亚洲一区二区三区无码_精品国产欧美日韩另类一区
      1. <ul id="0c1fb"></ul>

        <noscript id="0c1fb"><video id="0c1fb"></video></noscript>
        <noscript id="0c1fb"><listing id="0c1fb"><thead id="0c1fb"></thead></listing></noscript>

        武鸣县| 都匀市| 神木县| 兰考县| 靖边县| 凤凰县| 西乌| 神木县| 宝山区| 徐闻县| 内江市| 聂拉木县| 秭归县| 南漳县| 平阴县| 静安区| 寻甸| 永昌县| 利川市| 中方县| 思茅市| 梁河县| 盐山县| 丹寨县| 丰台区| 大姚县| 连江县| 云南省| 商河县| 涡阳县| 盖州市| 石台县| 嫩江县| 普兰店市| 通城县| 郯城县| 嘉定区| 福州市| 榆树市| 东海县| 永兴县|