利用已有的简单词表材料判断所给的测试记录的分类,词条非常的简单,作为笔记
主要步骤:
- 加载数据 loadDataSet()
- 得到词向量 createVocabList(listOPosts)
- 生成训练数据集的矩阵
- 得到训练数据的参数矩阵 trainNB0(trainMat, listClasses)
- 生成测试数据并且得到测试数据的矩阵 array(setOfWords2Vec(myVocabList, testEntry))
- 分类
#!/usr/bin/python
# coding:utf-8
from numpy import *
from math 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']]
classVec = [0, 1, 0, 1, 0, 1] # 1代表侮辱性文字 0代表正常的言论
return postingList, classVec
def createVocabList(dataSet): # 给定一个数据集,创建一个不含重复单词的词向量
vocabList = set([])
for document in dataSet:
vocabList = vocabList | set(document)
return list(vocabList)
def setOfWords2Vec(vocabList, inputSet): #给定一个词向量和一条单词构成的记录,生成次条记录的向量
returnVec = [0] * len(vocabList)
for word in inputSet:
if word in vocabList:
returnVec[vocabList.index(word)] = 1
return returnVec
def trainNB0(trainMatrix, trainCategory): # 训练参数,得到一个参数矩阵,对应着各个单词对应分类的出现频率
numTrainDocs = len(trainMatrix)
numWords = len(trainMatrix[0])
pAbusive = sum(trainCategory) / float(numTrainDocs)
p0Num = ones(numWords)
p1Num = ones(numWords)
p0Denom = 2
p1Denom = 2
for i in range(numTrainDocs):
if trainCategory[i] == 1:
p1Num += trainMatrix[i]
p1Denom += sum(trainMatrix[i])
else:
p0Num += trainMatrix[i]
p0Denom += sum(trainMatrix[i])
p1Vec = p1Num / p1Denom
p0Vec = p0Num / p0Denom
return p0Vec, p1Vec, pAbusive
def classifyNB(vec2Classify, p0Vec, p1Vec, pClass1): # 计算分类
p1 = sum(vec2Classify * p1Vec) + log(pClass1) # array相乘并且加上类别个数的对数上
p0 = sum(vec2Classify * p0Vec) + log(1.0 - pClass1)
if p1 > p0:
return 1
else:
return 0
def testNB(): # 测试贝叶斯
listOPosts, listClasses = loadDataSet() #加载数据集
myVocabList = createVocabList(listOPosts) # 得到词向量
trainMat = []
for postinDoc in listOPosts: # 生成训练数据集的向量
vecOfWord = setOfWords2Vec(myVocabList, postinDoc)
trainMat.append(vecOfWord)
p0v, p1v, pAb = trainNB0(trainMat, listClasses) # 根据已有的数据训练出的参数p0 p1为矩阵
testEntry = ['stupid'] # 测试数据
testMatrix = array(setOfWords2Vec(myVocabList, testEntry)) # 得到测试数据的array
return classifyNB(testMatrix, p0v, p1v, pAb) # 分类
print testNB() #测试主函数