转载自:http://blog.csdn.net/wowcplusplus/article/details/25190809

朴素贝叶斯算法是被工业界广泛应用的机器学习算法,它有较强的数学理论基础,在一些典型的应用中效果显著。朴素贝叶斯算法基于概率论的贝叶斯理论。该理论的核心公式如下:

式中,表示某种分类,则表示已知的情况下类型为的条件概率。我们求出各个类别下的,然后比较它们的大小,以概率最大的作为最后的类别,以此达到分类的目的。下面我们来看如何计算这些条件概率。

已知,则。朴素贝叶斯假定互为独立变量,则。而为指示函数,存在则为1,不存在则为0),都可用训练数据直接统计得出。故可依据上述分析求得的大小。又由于对所有类别都是固定大小,所以比较条件概率的大小等同于比较的大小。这就是朴素贝叶斯的数学原理。

下面,我们以朴素贝叶斯的一个典型应用——过滤垃圾邮件来展示该算法的python实现。

现在,我们有25件垃圾邮件和25件正常邮件,如何使用这些邮件作为训练数据得到过滤垃圾邮件的朴素贝叶斯模型呢?首先,我们用各邮件的词组成词向量表示在邮件中出现过的词,再计算孰大孰小即可决定这是封正常邮件(ham)还是封垃圾邮件(spam)。

第一步,我们将邮件转换为numpy的array形式,使用如下函数:

[python] view plaincopy
  1. def file2array(filename):
  2. fileReader=open(filename,'r').read()
  3. listOfWord=re.split(r'\W*',fileReader)
  4. fileArray=[word.lower() for word in listOfWord if len(word)>3]
  5. return fileArray

然后我们将所有邮件合在一个array里面,并在其中随机选取5封作为测试集:

[python] view plaincopy
  1. def getAllInfo():
  2. allTextMat=[]
  3. allTypeArray=[]
  4. testMat=[]
  5. testTypeArray=[]
  6. for i in range(1,26):
  7. allTextMat.append(file2array('email/spam/%d.txt'%i))
  8. allTypeArray.append(1)
  9. allTextMat.append(file2array('email/ham/%d.txt'%i))
  10. allTypeArray.append(0)
  11. for i in range(5):
  12. randIndex=int(random.uniform(0,len(allTextMat)))
  13. testMat.append(allTextMat[randIndex])
  14. testTypeArray.append(allTypeArray[randIndex])
  15. del(allTextMat[randIndex])
  16. del(allTypeArray[randIndex])
  17. return allTextMat,allTypeArray,testMat,testTypeArray

接着我们计算所有词的出现次数和在垃圾邮件、正常邮件中分别出现的次数:

[python] view plaincopy
  1. def getWordList(allTextMat):
  2. wordSet=set()
  3. for textVec in allTextMat:
  4. wordSet|=set(textVec)
  5. return list(wordSet)
  6. def getCountList(wordList,allTextMat,allTypeArray):
  7. wordListLen=len(wordList)
  8. totalCntList=ones(wordListLen)
  9. totalCntList*=2
  10. p0CntList=ones(wordListLen)
  11. p1CntList=ones(wordListLen)
  12. order=0
  13. p0Cnt=0
  14. p1Cnt=0
  15. for textVec in allTextMat:
  16. for word in textVec:
  17. wordPos=wordList.index(word)
  18. totalCntList[wordPos]+=1
  19. if allTypeArray[order]==1:
  20. p1CntList[wordPos]+=1
  21. p1Cnt+=1
  22. elif allTypeArray[order]==0:
  23. p0CntList[wordPos]+=1
  24. p0Cnt+=1
  25. order+=1
  26. p0=float(p0Cnt)/(p0Cnt+p1Cnt)
  27. p1=1-p0
  28. return totalCntList,p0CntList,p1CntList,p0,p1

最后我们进行贝叶斯分类:

[python] view plaincopy
  1. def bayesClassify(testMat,testTypeArray,totalCntList,p0CntList,p1CntList,p0,p1,wordList):
  2. docIndex=0
  3. errorCnt=0
  4. for testVec in testMat:
  5. sum0=0.0
  6. sum1=0.0
  7. for word in testVec:
  8. if word not in wordList:
  9. continue
  10. wordPos=wordList.index(word)
  11. sum0+=log(float(p0CntList[wordPos]/totalCntList[wordPos]))
  12. sum1+=log(float(p1CntList[wordPos]/totalCntList[wordPos]))
  13. sum0+=log(p0)
  14. sum1+=log(p1)
  15. decType=0 if sum0>sum1 else 1
  16. if decType != testTypeArray[docIndex]:
  17. errorCnt+=1
  18. print sum0,sum1
  19. docIndex+=1
  20. return errorCnt

整体的代码如下:

[python] view plaincopy
  1. import os
  2. import re
  3. from numpy import *
  4. def file2array(filename):
  5. fileReader=open(filename,'r').read()
  6. listOfWord=re.split(r'\W*',fileReader)
  7. fileArray=[word.lower() for word in listOfWord if len(word)>3]
  8. return fileArray
  9. def getAllInfo():
  10. allTextMat=[]
  11. allTypeArray=[]
  12. testMat=[]
  13. testTypeArray=[]
  14. for i in range(1,26):
  15. allTextMat.append(file2array('email/spam/%d.txt'%i))
  16. allTypeArray.append(1)
  17. allTextMat.append(file2array('email/ham/%d.txt'%i))
  18. allTypeArray.append(0)
  19. for i in range(5):
  20. randIndex=int(random.uniform(0,len(allTextMat)))
  21. testMat.append(allTextMat[randIndex])
  22. testTypeArray.append(allTypeArray[randIndex])
  23. del(allTextMat[randIndex])
  24. del(allTypeArray[randIndex])
  25. return allTextMat,allTypeArray,testMat,testTypeArray
  26. def getWordList(allTextMat):
  27. wordSet=set()
  28. for textVec in allTextMat:
  29. wordSet|=set(textVec)
  30. return list(wordSet)
  31. def getCountList(wordList,allTextMat,allTypeArray):
  32. wordListLen=len(wordList)
  33. totalCntList=ones(wordListLen)
  34. totalCntList*=2
  35. p0CntList=ones(wordListLen)
  36. p1CntList=ones(wordListLen)
  37. order=0
  38. p0Cnt=0
  39. p1Cnt=0
  40. for textVec in allTextMat:
  41. for word in textVec:
  42. wordPos=wordList.index(word)
  43. totalCntList[wordPos]+=1
  44. if allTypeArray[order]==1:
  45. p1CntList[wordPos]+=1
  46. p1Cnt+=1
  47. elif allTypeArray[order]==0:
  48. p0CntList[wordPos]+=1
  49. p0Cnt+=1
  50. order+=1
  51. p0=float(p0Cnt)/(p0Cnt+p1Cnt)
  52. p1=1-p0
  53. return totalCntList,p0CntList,p1CntList,p0,p1
  54. def bayesClassify(testMat,testTypeArray,totalCntList,p0CntList,p1CntList,p0,p1,wordList):
  55. docIndex=0
  56. errorCnt=0
  57. for testVec in testMat:
  58. sum0=0.0
  59. sum1=0.0
  60. for word in testVec:
  61. if word not in wordList:
  62. continue
  63. wordPos=wordList.index(word)
  64. sum0+=log(float(p0CntList[wordPos]/totalCntList[wordPos]))
  65. sum1+=log(float(p1CntList[wordPos]/totalCntList[wordPos]))
  66. sum0+=log(p0)
  67. sum1+=log(p1)
  68. decType=0 if sum0>sum1 else 1
  69. if decType != testTypeArray[docIndex]:
  70. errorCnt+=1
  71. print sum0,sum1
  72. docIndex+=1
  73. return errorCnt
  74. def main():
  75. allTextMat,allTypeArray,testMat,testTypeArray=getAllInfo()
  76. wordList=getWordList(allTextMat)
  77. totalCntList,p0CntList,p1CntList,p0,p1=getCountList(wordList,allTextMat,allTypeArray)
  78. print bayesClassify(testMat,testTypeArray,totalCntList,p0CntList,p1CntList,p0,p1,wordList)
  79. if __name__=='__main__':
  80. main()

我使用的邮件数据来源于《机器学习实战》第四章。感兴趣的同学可以去它官网http://www.manning.com/pharrington/下载数据集。

以上就是贝叶斯算法的基本介绍。作为本系列的开篇之作,我在表述上可能会有不当之处,还请各位同学在评论中指正。

利用朴素贝叶斯算法识别垃圾邮件相关推荐

  1. 机器学习:朴素贝叶斯算法与垃圾邮件过滤

    简介 贝叶斯算法是由英国数学家托马斯·贝叶斯提出的,这个算法的提出是为了解决"逆向概率"的问题.首先我们先来解释下正向概率与逆向概率的含义: 正向概率:假设一个箱子里有5个黄色球和 ...

  2. 朴素贝叶斯算法实现垃圾邮件过滤(Python3实现)

    目录 1.朴素贝叶斯实现垃圾邮件分类的步骤 2.邮件数据 3.代码实现 4.朴素贝叶斯的优点和缺点 1.朴素贝叶斯实现垃圾邮件分类的步骤 (1)收集数据:提供文本文件. (2)准备数据:将文本文件解析 ...

  3. python:基于朴素贝叶斯算法的垃圾邮件过滤分类

    目录 一.朴素贝叶斯算法 1.概述 2.推导过程 二.实现垃圾邮件过滤分类 1.垃圾邮件问题背景 2.朴素贝叶斯算法实现垃圾邮件分类的步骤 3.python实现 参考学习网址:https://blog ...

  4. 朴素贝叶斯算法实现垃圾邮件过滤

    朴素贝叶斯算法实现垃圾邮件过滤 1.1 题目的主要研究内容 (1)贝叶斯垃圾邮件过滤技术是一种电子邮件过滤的统计学技术,它使用贝叶斯分类来进行垃圾邮件的判别. (2)贝叶斯分类的运作是借着使用标记(一 ...

  5. 利用朴素贝叶斯原理过滤垃圾邮件(TF-IDF算法)

    本人是新手,为了还原该过程用了自己的方法,可能时间复杂度较高,并且在训练数据时也没有用到SKlearn模块中的贝叶斯分类器,是为了尝试自己去还原求后验条件概率这个过程. 目录 一.简述朴素贝叶斯原理 ...

  6. 机器学习——朴素贝叶斯算法(垃圾邮件分类)

    朴素贝叶斯算法介绍以及垃圾邮件分类实现 1.一些数学知识 2.贝叶斯公式 3.朴素贝叶斯算法 (1)介绍 (2)核心思想 (3)朴素贝叶斯算法 (4)拉普拉斯修正 (5)防溢出策略 (6)一般过程 ( ...

  7. 《机器学习实战》基于朴素贝叶斯算法实现垃圾邮件分类

    import random import sys import numpy as np import pandas as pd from pandas import Series, DataFrame ...

  8. 朴素贝叶斯算法实现对邮件的分类

    通过朴素贝叶斯算法来分类垃圾邮件的PYTHON实现(超易懂) 文章目录 通过朴素贝叶斯算法来分类垃圾邮件的PYTHON实现(超易懂) 前言 一.朴素贝叶斯算法分类垃圾邮件原理 二.python实现 1 ...

  9. 利用贝叶斯算法对垃圾邮件进行分类处理

    代码及注释如下: #使用贝叶斯算法实现垃圾邮件过滤 #将一个大字符串解析为字符串列表 def textParse(bigString):import relistOfTokens = re.split ...

最新文章

  1. 微信红包随机算法实现
  2. SCAU 1078 破密
  3. IE11 统治浏览器市场 Chrome 终超 Firefox
  4. boost::intrusive::splaytree_algorithms用法的测试程序
  5. 网银系统服务器架构设计,网上银行建设架构精选.pdf
  6. 转载:Windows CE内存管理
  7. entity framework框架生成摘要文档为空(没有元数据文档可用)的bug解决方案
  8. CentOS7.1下targetcli的使用
  9. python 菜鸟-Python3 模块
  10. 计算硬盘的计算机,硬盘整数分区计算器免费版
  11. 记一次带有FSG壳的熊猫烧香病毒分析过程
  12. 读书笔记:《过程咨询 II》
  13. prometheus如何评估告警策略以及如何推送告警消息到alertmanager?
  14. 量化研究-恐慌和贪婪指数
  15. 流年祭.掩埋一场与青春有关的荒芜
  16. 网上下载的PPT模板总是会自动切换、自动播放动画,怎么取消自动播放
  17. 《数字逻辑设计与计算机组成》一练习
  18. speedoffice表格中如何自动求和
  19. TexStudio内容字体格式设置+公式编写及排版心得
  20. 图片服务器项目编写设计

热门文章

  1. 【中级02】Java Class字节码文件底层逻辑详解
  2. C++之左值引用与右值引用
  3. C语言之结构体嵌套调用(十八)
  4. FFmpeg之YUV420排列原理(二十三)
  5. 访问:source.android.com和developer.android.com
  6. 最常见的Linux用户程序异常----Segment Fault
  7. Android之 震动(Vibrator)如何贯通Android系统 (从硬件设计 -- 驱动 -- HAL -- JNI -- Framework -- Application)
  8. Android 系统开发系列二
  9. 光猫gpon和epon的区别
  10. ubuntu常用状态查看命令