吴裕雄--天生自然python机器学习:使用朴素贝叶斯过滤垃圾邮件
使用朴素贝叶斯解决一些现实生活中
的问题时,需要先从文本内容得到字符串列表,然后生成词向量。
准备数据:切分文本
测试算法:使用朴素贝叶斯进行交叉验证
文件解析及完整的垃圾邮件测试函数
def createVocabList(dataSet):
vocabSet = set([]) #create empty set
for document in dataSet:
vocabSet = vocabSet | set(document) #union of the two sets
return list(vocabSet) def setOfWords2Vec(vocabList, inputSet):
returnVec = [0]*len(vocabList)
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 def bagOfWords2VecMN(vocabList, inputSet):
returnVec = [0]*len(vocabList)
for word in inputSet:
if word in vocabList:
returnVec[vocabList.index(word)] += 1
return returnVec def textParse(bigString): #input is big string, #output is word list
import re
listOfTokens = re.split(r'\W*', bigString)
return [tok.lower() for tok in listOfTokens if len(tok) > 2] def trainNB0(trainMatrix,trainCategory):
numTrainDocs = len(trainMatrix)
numWords = len(trainMatrix[0])
pAbusive = sum(trainCategory)/float(numTrainDocs)
p0Num = ones(numWords)
p1Num = ones(numWords) #change to ones()
p0Denom = 2.0
p1Denom = 2.0 #change to 2.0
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) #change to log()
p0Vect = log(p0Num/p0Denom) #change to log()
return p0Vect,p1Vect,pAbusive def aloneIndex(datasetLen):
a = []
while(True):
randIndex = int(random.uniform(0,len(trainingSet)))
a.append(randIndex)
if(len(set(a))==10):
break
return a def spamTest():
docList=[]
classList = []
fullText =[]
for i in range(1,26):
wordList = textParse(open('F:\\machinelearninginaction\\Ch04\\email\\spam\\%d.txt' % i).read())
docList.append(wordList)
fullText.extend(wordList)
classList.append(1)
wordList = textParse(open('F:\\machinelearninginaction\\Ch04\\email\\ham\\%d.txt' % i).read())
docList.append(wordList)
fullText.extend(wordList)
classList.append(0)
vocabList = createVocabList(docList)#create vocabulary
trainingSet = range(50)
testSet = aloneIndex(trainingSet) #create test set
trainingSetT = []
for i in range(len(trainingSet)):
for j in range(len(testSet)):
if(testSet[j] != trainingSet[i]):
trainingSetT.append(trainingSet[i])
trainingSet = trainingSetT
trainMat=[]
trainClasses = []
for docIndex in trainingSet:#train the classifier (get probs) trainNB0
trainMat.append(bagOfWords2VecMN(vocabList, docList[docIndex]))
trainClasses.append(classList[docIndex])
p0V,p1V,pSpam = trainNB0(array(trainMat),array(trainClasses))
errorCount = 0
for docIndex in testSet: #classify the remaining items
wordVector = bagOfWords2VecMN(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)) spamTest()

吴裕雄--天生自然python机器学习:使用朴素贝叶斯过滤垃圾邮件的更多相关文章
- 吴裕雄--天生自然python机器学习:朴素贝叶斯算法
分类器有时会产生错误结果,这时可以要求分类器给出一个最优的类别猜测结果,同 时给出这个猜测的概率估计值. 概率论是许多机器学习算法的基础 在计算 特征值取某个值的概率时涉及了一些概率知识,在那里我们先 ...
- 吴裕雄--天生自然python机器学习实战:K-NN算法约会网站好友喜好预测以及手写数字预测分类实验
实验设备与软件环境 硬件环境:内存ddr3 4G及以上的x86架构主机一部 系统环境:windows 软件环境:Anaconda2(64位),python3.5,jupyter 内核版本:window ...
- 吴裕雄--天生自然python机器学习:决策树算法
我们经常使用决策树处理分类问题’近来的调查表明决策树也是最经常使用的数据挖掘算法. 它之所以如此流行,一个很重要的原因就是使用者基本上不用了解机器学习算法,也不用深究它 是如何工作的. K-近邻算法可 ...
- 吴裕雄--天生自然python机器学习:机器学习简介
除却一些无关紧要的情况,人们很难直接从原始数据本身获得所需信息.例如 ,对于垃圾邮 件的检测,侦测一个单词是否存在并没有太大的作用,然而当某几个特定单词同时出现时,再辅 以考察邮件长度及其他因素,人们 ...
- 吴裕雄--天生自然python机器学习:支持向量机SVM
基于最大间隔分隔数据 import matplotlib import matplotlib.pyplot as plt from numpy import * xcord0 = [] ycord0 ...
- 吴裕雄--天生自然python机器学习:使用K-近邻算法改进约会网站的配对效果
在约会网站使用K-近邻算法 准备数据:从文本文件中解析数据 海伦收集约会数据巳经有了一段时间,她把这些数据存放在文本文件(1如1^及抓 比加 中,每 个样本数据占据一行,总共有1000行.海伦的样本主 ...
- 吴裕雄--天生自然python机器学习:基于支持向量机SVM的手写数字识别
from numpy import * def img2vector(filename): returnVect = zeros((1,1024)) fr = open(filename) for i ...
- 吴裕雄--天生自然python机器学习:使用Logistic回归从疝气病症预测病马的死亡率
,除了部分指标主观和难以测量外,该数据还存在一个问题,数据集中有 30%的值是缺失的.下面将首先介绍如何处理数据集中的数据缺失问题,然 后 再 利 用 Logistic回 归 和随机梯度上升算法来预测 ...
- 吴裕雄--天生自然python机器学习:Logistic回归
假设现在有一些数据点,我们用 一条直线对这些点进行拟合(该线称为最佳拟合直线),这个拟合过程就称作回归.利用Logistic回归进行分类的主要思想是:根据现有数据对分类边界线建立回归公式,以此进行分类 ...
随机推荐
- 利用libpcap抓取数据包
转载自:http://blog.csdn.net/tennysonsky/article/details/44811899 概述 libpcap是一个网络数据包捕获函数库,tcpdump就是以libp ...
- 简单makefile示例
Makefile cmd: - g++ 相信在linux下编程的没有不知道makefile的,刚开始学习linux平台下的东西,了解了下makefile的制作,觉得有点东西可以记录下. 下面是一个极其 ...
- [DDCTF 2019]homebrew event loop
0x00 知识点 逻辑漏洞: 异步处理导致可以先调用增加钻石,再调用计算价钱的.也就是先货后款. eval函数存在注入,可以通过#注释,我们可以传入路由action:eval#;arg1#arg2#a ...
- 报错:Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
1.问题 写了一个简单的单层神经网络跑mnist手写数字集,结果每次fit都会出现dead kernel 很多dead kernel首先不要急着去网上搜dead kernel怎么解决,因为大家出现的原 ...
- 编写检测深度模型测试程序python
参考:https://blog.csdn.net/haoji007/article/details/81035565?utm_source=blogxgwz9 首先从网上下载imagenet训练好的模 ...
- iOS 修改默认 UserAgent
User-Agent(用户代理)字符串是Web浏览器用于声明自身型号版本并随HTTP请求发送给Web服务器的字符串,在Web服务器上可以获取到该字符串. UIWebView修改UserAgent UI ...
- zabbix中文乱码解决
问题现象: zabbix字体修改成中文后监控显示乱码 原因: 该问题是由于zabbix默认使用的是“DejaVuSans.ttf”(zabbix3.2.7默认使用的是“graphfont.ttf”), ...
- 浅copy
person=['aaa',['a',bbb'] p1=copy.copy(person) p2=person[:] p3=list(person) p4=person.copy() print(ty ...
- 选择排序&冒泡排序
//直接选择排序 #include<stdio.h> void SelectionSort(int arr[],int len) { int i,j; int k,min; int tem ...
- PAT Basic 1070 结绳(25) [排序,贪⼼]
题目 给定⼀段⼀段的绳⼦,你需要把它们串成⼀条绳.每次串连的时候,是把两段绳⼦对折,再如下图所示套接在⼀起.这样得到的绳⼦⼜被当成是另⼀段绳⼦,可以再次对折去跟另⼀段绳⼦串连.每次串 连后,原来两段绳 ...