标签:python machine-learning bayes 机器学习 算法
概率是许多机器学习算法的基础,在前面生成决策树的过程中使用了一小部分关于概率的知识,即统计特征在数据集中取某个特定值的次数,然后除以数据集的实例总数,得到特征取该值的概率。
之前的基础实验中简单实现了朴素贝叶斯分类器,并正确执行了文本分类,这一节将贝叶斯运用到实际场景,垃圾邮件过滤这一实际应用。
实例:使用朴素贝叶斯过滤垃圾邮件
在上一节:http://blog.csdn.net/liyuefeilong/article/details/48383175中,使用了简单的文本文件,并从中提取了字符串列表。这个例子中,我们将了解朴素贝叶斯的一个最著名的应用:电子邮件垃圾过滤。首先看一下如何使用通用框架来解决问题:
收集数据:提供文本文件,下载地址:http://download.csdn.net/detail/liyuefeilong/9106481,放在工程目录下并解压即可;
准备数据:将文本文件解析成词条向量;
分析数据:检查词条确保解析的正确性;
训练算法:使用我们之前建立的trainNaiveBayes(trainMatrix, classLabel)函数;
测试算法:使用函数naiveBayesClassify(vec2Classify, p0, p1, pBase),并且构建一个新的测试函数来计算文档集的错误率;
使用算法:构建一个完整的程序对一组文档进行分类,将错分的文档输出到屏幕上。
1.生成贝叶斯分类器
在上一节已实现,在实现朴素贝叶斯的两个应用前,需要用到之前的分类器训练函数,完整的代码如下:
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 08 16:12:55 2015
@author: Administrator
"""
from numpy import *
# 创建实验样本,可能需要对真实样本做一些处理,如去除标点符号
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‘]]
listClass = [0, 1, 0, 1, 0, 1] # 1代表存在侮辱性的文字,0代表不存在
return postingList, listClass
# 将所有文档所有词都存到一个列表中,用set()函数去除重复出现的词
def createNonRepeatedList(data):
vocList = set([])
for doc in data:
vocList = vocList | set(doc) # 两集合的并集
return list(vocList)
def detectInput(vocList, inputStream):
returnVec = [0]*len(vocList) # 创建和vocabList一样长度的全0列表
for word in inputStream:
if word in vocList: # 针对某段words进行处理
returnVec[vocList.index(word)] = 1 # ?
else:
print "The word :%s is not in the vocabulary!" % word
return returnVec
# 贝叶斯分类器训练函数
def trainNaiveBayes(trainMatrix, classLabel):
numTrainDocs = len(trainMatrix)
numWords = len(trainMatrix[0])
pBase = sum(classLabel) / float(numTrainDocs)
# The following Settings aim at avoiding the probability of 0
p0Num = ones(numWords)
p1Num = ones(numWords)
p0Denom = 2.0
p1Denom = 2.0
for i in range(numTrainDocs):
if classLabel[i] == 1:
p1Num += trainMatrix[i]
p1Denom += sum(trainMatrix[i])
else:
p0Num += trainMatrix[i]
p0Denom += sum(trainMatrix[i])
p0 = log(p0Num / p0Denom)
p1 = log(p1Num / p1Denom)
return p0, p1, pBase
def trainNaiveBayes(trainMatrix, classLabel):
numTrainDocs = len(trainMatrix)
numWords = len(trainMatrix[0])
pBase = sum(classLabel) / float(numTrainDocs)
# The following Settings aim at avoiding the probability of 0
p0Num = ones(numWords)
p1Num = ones(numWords)
p0Denom = 2.0
p1Denom = 2.0
for i in range(numTrainDocs):
if classLabel[i] == 1:
p1Num += trainMatrix[i]
p1Denom += sum(trainMatrix[i])
else:
p0Num += trainMatrix[i]
p0Denom += sum(trainMatrix[i])
p0 = log(p0Num / p0Denom)
p1 = log(p1Num / p1Denom)
return p0, p1, pBase
trainMat = []
for doc in loadData:
trainMat.append(detectInput(vocList, doc))
p0,p1,pBase = trainNaiveBayes(trainMat, dataLabel)
#print "trainMat : "
#print trainMat
# test the algorithm
def naiveBayesClassify(vec2Classify, p0, p1, pBase):
p0res = sum(vec2Classify * p0) + log(1 - pBase)
p1res = sum(vec2Classify * p1) + log(pBase)
if p1res > p0res:
return 1
else:
return 0
def testNaiveBayes():
loadData, classLabel = loadDataSet()
vocList = createNonRepeatedList(loadData)
trainMat = []
for doc in loadData:
trainMat.append(detectInput(vocList, doc))
p0, p1, pBase = trainNaiveBayes(array(trainMat), array(classLabel))
testInput = [‘love‘, ‘my‘, ‘dalmation‘]
thisDoc = array(detectInput(vocList, testInput))
print testInput, ‘the classified as: ‘, naiveBayesClassify(thisDoc, p0, p1, pBase)
testInput = [‘stupid‘, ‘garbage‘]
thisDoc = array(detectInput(vocList, testInput))
print testInput, ‘the classified as: ‘, naiveBayesClassify(thisDoc, p0, p1, pBase)
2.准备数据:切分文本
首先,编写一个Python函数textSplit(),用来对所有的email文件进行解析并把一篇文章分解为一个个的单词,这里将邮件分为两种,正常的邮件放在路径/email/ham/下,垃圾邮件放在/email/spam/下。以下的代码就是读入文本数据,然后切分,得到词向量,然后将词向量中的词都转换成小写,并把长度大于2的字符串提取出来,写入到文本文件中去,在切分文本的过程中使用了一些技巧,包括正则表达式、将所有字符串转换成小写(.lower())等等。
def textParse(bigString) : # 正则表达式进行文本解析
import re
listOfTokens = re.split(r‘\W*‘, bigString)
return[tok.lower() for tok in listOfTokens if len(tok) > 2]
3.测试算法:使用朴素贝叶斯进行交叉验证
该部分将文本解析器集成到一个完整分类器中,
# 过滤垃圾邮件
def spamTest() :
docList = []; classList = []; fullText = []
for i in range(1, 26) : # 导入并解析文本文件,25个普通邮件和25个垃圾邮件
wordList = textParse(open(‘email/spam/%d.txt‘ % i).read())
docList.append(wordList)
fullText.extend(wordList)
classList.append(1)
wordList = textParse(open(‘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) : # 随机构建训练集,包含10个样本
randIndex = int(random.uniform(0, len(trainingSet)))
testSet.append(trainingSet[randIndex])
del(trainingSet[randIndex])
trainMat = []; trainClasses = []
for docIndex in trainingSet :
trainMat.append(setOfWords2Vec(vocabList, docList[docIndex]))
trainClasses.append(classList[docIndex])
p0V, p1V, pSpam = trainNB0(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 ‘the error rate is: ‘, float(errorCount) / len(testSet)
4.小结
以上代码会对10封随机选择的电子邮件进行分类,并统计分类的错误率。经过多次的运算,平均错误率为6%,这里的错误是指将垃圾邮件误判为正常邮件。相比之下,将垃圾邮件误判为正常邮件要好过将正常邮件误判为垃圾邮件,同时,若提高训练样本个数,可以进一步降低错误率。
算法训练测试的方法是从总的数据集中随机选择数字,将其添加到测试集中,同时将其从训练集中剔除。这种随机选择数据的一部分作为训练集,而剩余部分作为测试集的过程为留存交叉验证(hold-out cross validation)。有时为了更精确地估计分类器的错误率,就应该进行多次迭代后求出平均错误率。
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:python machine-learning bayes 机器学习 算法
原文地址:http://blog.csdn.net/liyuefeilong/article/details/48448991