python实现朴素贝叶斯

参考:《机器学习实战》- Machine Learning in Action

一、 基本思想

 简单的说,用概率的高低来决定数据属于哪一类别,这就是贝叶斯决策理论的核心思想,即选择具有最高概率的决策。朴素贝叶斯,则是在贝叶斯基础上做了一些最原始、最简单的假设。在朴素贝叶斯中,假设特征之间是相互独立的,比如假设a这个单词出现在am后的概率和出现在am前的概率是一样的。另外的一个假设是,每个特征同等重要

二、 代码

背景:对文档进行贝叶斯分类,判断其是否属于侮辱性文档。

#-*- coding:utf8 -*-
from numpy import *

#原始数据,训练样本
def loadDataSet():
	postingList = [
		['my', 'dog', 'has', 'flea', 'problem', '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

#得到所有词的列表
def createVocabList(dataSet):
	vocabSet = set([])
	for document in dataSet:
		vocabSet = vocabSet | set(document)
	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

#训练函数0
def trainNB0(trainMatrix, trainCategory):
	numTrainDocs = len(trainMatrix)
	numWords = len(trainMatrix[0])
	pAbusive = sum(trainCategory)/float(numTrainDocs)
	p0Num = zeros(numWords)
	p1Num = zeros(numWords)
	p0Denom = 0.0
	p1Denom = 0.0
	for i in range(numTrainDocs):
		if trainCategory[i] == 1:
			plNum += trainMatrix[i]
			plDenom += sum(trainMatrix)
		else:
			p0Num += trainMatrix[i]
			p0Denom += sum(trainMatrix)
	p0Vect = p0Num/p0Denom
	p1Vect = p1Num/p1Denom
	return p0Vect, p1Vect, pAbusive 

posted @ 2017-09-04 21:17  va_chester  阅读(763)  评论(0编辑  收藏  举报