贝叶斯公式
已知某条件概率,如何得到两个条件交换之后的该概率呢?也就是说如何在知道p(a|b)的情况下得到p(b|a)的概率呢?下面我盟诶出贝叶斯公式,然后来看看贝叶斯工时对应的实际物理意义是什么。
看到这里。我们会看到我们上文说道的两个概率在这里都出现了,哈哈,那么具体的来讲,这里的每一个表达式都是什么具体的含义呢?我们来举一个例子看看。著名的贝叶斯在垃圾邮件的过滤这里有着很重要的应用,这里的应用应该是属于监督学习算法:给出一些文本,我们在标记这些文本的属性之后,把这些标签类中最明显,最具有代表性的term列举出来(出现概率最大的term),然后,再给出一个新的文本的时候,我们看看这些文本中是否出现了标签类对应的term,计算出现的概率,从大到小排序之后,最大的概率对应的那个标签就是训练文本的类别。
举一个简单例子,在百度的拼写错误(error)检查中,当你输入一些错误的(不常见)的词语,他会立即的在下面显示你真正想输入的语句(true)。想想这种情况,就是计算p(true|error)的概率是多少吧,哈哈,我们来看看,p(error)的概率是已经发生的敞亮,也就是你有多大的概率拼写错误,既然是常量我们就不要理会他。p(true)呢?就是说你实际想拼写的单词的概率有多大,但是有了这个还是不够的,必须还知道p(error|true)的概率,这里我们可以认为这个概率计算的是拼写正确和拼写错误的相似度是多少,因为在实际情况下我们只能知道p(error|true)的概率,这些数据应该存在后台的数据库中。也就对应于每个类别标签下经常出现的单词的频率p(term|label)。我们计算每个标签出现的概率,找到那个最大的就可以啦,明吧了吧。在计算的时候不用理会p(b)就可以啦。
python实现垃圾邮件
__author__ = 'Administrator'
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]
return postingList, classVec
class NBayes(object):
def __init__(self):
self.vocabulary=[]
self.idf=0
self.tf=0
self.tdm=0
self.pcates={}
self.labels=[]
self.docLenght=0
self.vocabLen=0
self.testSet=[]
def cate_prob(self, classVec):
self.labels = classVec
labelSet= set(self.labels)
for labelItem in labelSet:
self.pcates[labelItem]=float(self.labels.count(labelItem))/float(len(self.labels))
def calc_wordFewq(self,trainSet):
self.idf=np.zeros([1,self.vocabLen])
self.tf=np.ones([self.docLength,self.vocabLen])
for indexLine in xrange(self.docLength):
for word in trainSet[indexLine]:
self.tf[indexLine,self.vocabulary.index(word)]+=1
for singleWord in set(trainSet[indexLine]):
self.idf[0,self.vocabulary.index(singleWord)]+=1
def calc_tdm(self):
self.tdm=np.zeros([len(self.pcates),self.vocabLen])
sumList=np.zeros([len(self.pcates),1])
for indexLine in xrange(self.docLength):
self.tdm[self.labels[indexLine]]+=self.tf[indexLine]
sumList[self.labels[indexLine]]=np.sum(self.tdm[self.labels[indexLine]])
self.tdm=self.tdm/sumList
def map2Vocab(self,testData):
self.testSet=np.zeros([1,self.vocabLen])
for word in testData:
self.testSet[0,self.vocabulary.index(word)]+=1
def train_Set(self,trainSet,classVec):
self.cate_prob(classVec)
self.docLength=len(trainSet)
tempSet=set()
[tempSet.add(word) for line in trainSet for word in line]
self.vocabulary=list(tempSet)
self.vocabLen=len(self.vocabulary)
self.calc_wordFewq(trainSet)
self.calc_tdm()
def predict(self,testSet):
if np.shape(testSet)[1]!=self.vocabLen:
print "the inputData exits error"
exit(0)
predValue=0
predClass=""
for tdm_vect,keyClass in zip(self.tdm,self.pcates):
temp=np.sum(testSet*tdm_vect*self.pcates[keyClass])
if temp>predValue:
predValue=temp
predClass=keyClass
return predClass