07 机器学习 - 朴素贝叶斯分类算法(案例二)
2021/7/8 11:11:54
本文主要是介绍07 机器学习 - 朴素贝叶斯分类算法(案例二),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
利用大量邮件先验数据,使用朴素贝叶斯分类算法来自动识别垃圾邮件。
python实现:
#过滤垃圾邮件 def textParse(bigString): #正则表达式进行文本解析 import re listOfTokens = re.split(r'\W*',bigString) return [tok.lower() for tok in listOfTokens if len(tok) > 2] def spamTest(): docList = []; classList = []; fullText = [] for i in range(1,26): #导入并解析文本文件 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): #随机构建训练集 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)
这篇关于07 机器学习 - 朴素贝叶斯分类算法(案例二)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-13机器学习教程:初学者指南
- 2024-08-07从入门到精通:全面解析机器学习基础与实践
- 2024-01-24手把手教你使用MDK仿真调试
- 2024-01-10基于“小数据”的机器学习
- 2024-01-08扩展卡尔曼滤波:提高机器学习性能的利器
- 2023-12-26各种二端口滤波器网络仿真遇到的问题
- 2023-12-14机器学习-搜索技术:从技术发展到应用实战的全面指南
- 2023-12-12机器学习 - 决策树:技术全解与案例实战
- 2023-12-05机器学习-学习率:从理论到实战,探索学习率的调整策略
- 2023-12-04解锁机器学习-梯度下降:从技术到实战的全面指南