#-*-coding:utf-8-*-
from numpy import *
def loadDataSet():    #创建实验样本
postingLsit = [['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'],
sortedlist
['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 postingLsit, classVec
def createVocabList(dataSet):  #创建一个包含在所有文档中出现的不重复词的列表
vocabSet = set([])
for document in dataSet:
vocabSet = vocabSet | set(document)    #  操作符|用于求两个集合的并集
return list(vocabSet)
#inputSet表示某个文档,输出的是文档向量,向量的每个元素为0或1,分别表示词汇表中的单词在输入文档中是否出现
def setOfWords2Vec(vocabList, inputSet):    #词集模型
returnVec = [0]*len(vocabList)    #创建一个和vocabList等长,元素为0的向量
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 bagOfWordsVecMN(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)  #类别1的概率
p0Num = ones(numWords); p1Num = ones(numWords)
p0Denom = 2.0; p1Denom = 2.0
for i in range(numTrainDocs):
if trainCategory[i] == 1:
p1Num += trainMatrix[i]      #将类别为1的文档向量加入p1Num中
p1Denom += sum(trainMatrix[i])    #计算文档中出现1的次数
else:
p0Num += trainMatrix[i]
p0Denom += sum(trainMatrix[i])
#    p1Vec = p1Num/p1Denom    #p1Denom:类别1出现侮辱性词条的个数
#    p0Vec = p0Num/p0Denom    #p0Denom:类别0出现侮辱性词条的个数
p1Vec = log(p1Num/p1Denom)
p0Vec = log(p0Num/p0Denom)    #log防止下溢出
return p0Vec, p1Vec, pAbusive
# 朴素贝叶斯分类函数
def classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):
p1 = sum(vec2Classify * p1Vec) + log(pClass1)
p0 = sum(vec2Classify * p0Vec) + log(1.0 - pClass1)
if p1 > p0:
return 1
else:
return 0
def testingNB():
listOPosts, listClasses = loadDataSet()
myVocabList = crea
teVocabList(listOPosts)
trainMat = []
for postinDoc in listOPosts:
trainMat.append(setOfWords2Vec(myVocabList, postinDoc))
p0V, p1V, pAb = trainNB0(array(trainMat), array(listClasses))
testEntry = ['love', 'my', 'dalmation']
thisDoc = array(setOfWords2Vec(myVocabList, testEntry))
print testEntry, 'classified as: ', classifyNB(thisDoc, p0V, p1V, pAb)
testEntry = ['stupid', 'garbage']
thisDoc = array(setOfWords2Vec(myVocabList, testEntry))
print testEntry, 'classified as: ', classifyNB(thisDoc, p0V, p1V, pAb)
#文件解析及完整的垃圾邮件测试函数
def textParse(bigString):
import re
listOfTokens = re.split(r'\W*', bigString)
return [tok.lower() for tok in listOfTokens if len(tok) > 0]
def spamTest():
docList = []; classList = []; fullText = []
for i in range(1, 26):
wordList = textParse(open('email/spam/%d.txt' % i).read())
docList.append(wordList)
classList.append(1)
wordList = textParse(open('email/ham/%d.txt' % i).read())
docList.append(wordList)
classList.append(0)
vocabList = createVocabList(docList)
trainingSet = range(50); testSet = []
for i in range(10):
randIndex = int(random.uniform(0, len(trainingSet)))
testSet.append(trainingSet[randIndex])
del(trainingSet[randIndex])
trainMat = []; trainClasses = []
print testSet
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)
#RSS源分类器及高频词去除数
def calcMostFreq(vocabList, fullText):
import operator
freqDict = {}
for token in vocabList:
freqDict[token] = unt(token)    #unt(token):计算token在fullText中出现的次数
sortedFreq = sorted(freqDict.iteritems(), key=operator.itemgetter(1), reverse=True)
return sortedFreq[:30]
def localWords(feed1, feed0):
import feedparser
docList = []; classList = []; fullText = []
minLen = min(len(feed1['entries']), len(feed0['entries']))
for i in range(minLen):
wordList = textParse(feed1['entries'][i]['summary'])
docList.append(wordList)
classList.append(1)
wordList = textParse(feed0['entries'][i]['summary'])
docList.append(wordList)
classList.append(0)
vocabList = createVocabList(docList)
top30Words
= calcMostFreq(vocabList, fullText)
for pairW in top30Words:
if pairW[0] in vocabList:
trainingSet = range(2 * minLen); testSet = []
for i in range(20):
randIndex = int(random.uniform(0, len(trainingSet)))
testSet.append(trainingSet[randIndex])
del(trainingSet[randIndex])
trainMat = []; trainClasses = []
for docIndex in trainingSet:
trainMat.append(bagOfWordsVecMN(vocabList, docList[docIndex]))
trainClasses.append(classList[docIndex])
p0V, p1V, pSpam = trainNB0(array(trainMat), array(trainClasses))
errorCount = 0
for docIndex in testSet:
wordVector = bagOfWordsVecMN(vocabList, docList[docIndex])
if classifyNB(array(wordVector), p0V, p1V, pSpam) != classList[docIndex]:
errorCount += 1
print 'the error rate is: ', float(errorCount)/len(testSet)
return vocabList, p0V, p1V
def getTopWords(ny, sf):    #最具表征性的词汇显示函数
import operator
vocabList, p0V, p1V = localWords(ny, sf)
topNY = []; topSF = []
for i in range(len(p0V)):
if p0V[i] > -6.0:
topSF.append((vocabList, p0V[i]))
if p1V[i] > -6.0:
topNY.append((vocabList, p1V[i]))
sortedSF = sorted(topSF, key=lambda pair: pair[1], reverse=True)
print len(sortedSF)
print "SF**SF**SF**SF**SF**SF**SF**SF**"
#for item in sortedSF:
#print item[0]
sortedNY = sorted(topNY, key=lambda pair: pair[1], reverse=True)
print "NY**NY**NY**NY**NY**NY**NY**NY**"
#for item in sortedNY:
#print item[0]

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。