利用朴素贝叶斯和多线程做垃圾邮件分类

2024-02-17 13:18

本文主要是介绍利用朴素贝叶斯和多线程做垃圾邮件分类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

数据来源:http://www2.aueb.gr/users/ion/data/enron-spam/
利用网站提供的三万多封邮件做一个分类,训练参数,利用个人电脑4核8G训练数据样本5000个,利用交叉验证得出的训练误差为1.63%,当数据样本上升为30000利用个人电脑训练老是被Linux给kill掉,后用了8个线程还是没能解决好,只是当做学习之用,后期就不在优化了,附上个人渣代码

#~/usr/bin/python
# coding:utf-8
import random
import os
import re
import numpy
import math
import profile
import threading
import timedef textParse(bigString):listOfTokens = re.split(r'\W*', bigString)return [tok.lower() for tok in listOfTokens if len(tok) > 2]def createVocabList(docList):vocabSet = set([])for document in docList:vocabSet = vocabSet | set(document)return list(vocabSet)def getFullTestVec():print 'starting get full test Vec ......'docList = []classList = []basepath = os.getcwd()hampath = basepath + '/ham/'filesNameList = os.listdir(hampath)for eachFile in filesNameList:with open(hampath + eachFile, 'r') as f:docList.append(textParse(f.read()))classList.append(0)spampath = basepath + '/spam/'filesNameList = os.listdir(spampath)for eachFile in filesNameList:with open(spampath + eachFile, 'r') as f:docList.append(textParse(f.read()))classList.append(1)vocabList = createVocabList(docList)print 'over geting full text!!!'return docList, vocabList, classListdef setOfWords2Vec(vocabList, inputSet):returnVec = [0] * len(vocabList)for word in inputSet:if word in vocabList:returnVec[vocabList.index(word)] = 1return returnVecdef trainNB0(trainMatrix, trainCategory):  # 训练参数,得到一个参数矩阵,对应着各个单词对应分类的出现频率numTrainDocs = len(trainMatrix)numWords = len(trainMatrix[0])pAbusive = sum(trainCategory) / float(numTrainDocs)p0Num = numpy.ones(numWords)p1Num = numpy.ones(numWords)p0Denom = 2p1Denom = 2for i in range(numTrainDocs):if trainCategory[i] == 1:p1Num += trainMatrix[i]p1Denom += sum(trainMatrix[i])else:p0Num += trainMatrix[i]p0Denom += sum(trainMatrix[i])p1Vec = numpy.log(p1Num / p1Denom)p0Vec = numpy.log(p0Num / p0Denom)return p0Vec, p1Vec, pAbusivedef classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):p1 = sum(vec2Classify * p1Vec) + numpy.log(pClass1)  # element-wise multp0 = sum(vec2Classify * p0Vec) + numpy.log(1.0 - pClass1)if p1 > p0:return 1else:return 0def holdOutCrossValidation(docList, vocabList, classList):testList = []testClass = []trainList = docList[:]trainClass = classList[:]lenOfTestList = len(docList) / 5lenOfDocList = len(docList)print 'start geting train words vec and test words vec......'for index in range(lenOfTestList):randomIndex = int(random.uniform(0, lenOfDocList))lenOfDocList -= 1testList.append(docList[randomIndex])testClass.append(classList[randomIndex])del(trainList[randomIndex])del(trainClass[randomIndex])print 'start calc args......'tmpCnt = 0sumCnt = len(docList)trainMat = []for eachDoc in trainList:trainMat.append(setOfWords2Vec(vocabList, eachDoc))tmpCnt += 1print tmpCnt, ' / ', sumCntp0Vec, p1Vec, pSpam = trainNB0(numpy.array(trainMat), numpy.array(trainClass))print 'p0: ', p0VecerrorCnt = 0print 'start calc cross validation......'for indexOfTestList in range(0, len(testList)):eachDocMat = setOfWords2Vec(vocabList, testList[indexOfTestList])if classifyNB(numpy.array(eachDocMat), p0Vec, p1Vec, pSpam) != testClass[indexOfTestList]:errorCnt += 1print 'len: ', len(trainList)return float(errorCnt) / len(testList)class Test(threading.Thread):def __init__(self):threading.Thread.__init__(self)# self._run_num = numdef run(self):global mutex, docList_G, vocabList_G, classList_Gthreadname = threading.currentThread().getName()# for x in xrange(0, int(self._run_num)):print 'thread name: ', threadnamemutex.acquire()holdOutCrossValidation(docList_G, vocabList_G, classList_G)mutex.release()global docList_G, vocabList_G, classList_G, mutex
docList_G, vocabList_G, classList_G = getFullTestVec()threads = []
num = 8
mutex = threading.Lock()for x in xrange(0, num):threads.append(Test())for t in threads:t.start()for t in threads:t.join()

这篇关于利用朴素贝叶斯和多线程做垃圾邮件分类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/717872

相关文章

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

Python多线程实现大文件快速下载的代码实现

《Python多线程实现大文件快速下载的代码实现》在互联网时代,文件下载是日常操作之一,尤其是大文件,然而,网络条件不稳定或带宽有限时,下载速度会变得很慢,本文将介绍如何使用Python实现多线程下载... 目录引言一、多线程下载原理二、python实现多线程下载代码说明:三、实战案例四、注意事项五、总结引

Python多线程应用中的卡死问题优化方案指南

《Python多线程应用中的卡死问题优化方案指南》在利用Python语言开发某查询软件时,遇到了点击搜索按钮后软件卡死的问题,本文将简单分析一下出现的原因以及对应的优化方案,希望对大家有所帮助... 目录问题描述优化方案1. 网络请求优化2. 多线程架构优化3. 全局异常处理4. 配置管理优化优化效果1.

Qt中实现多线程导出数据功能的四种方式小结

《Qt中实现多线程导出数据功能的四种方式小结》在以往的项目开发中,在很多地方用到了多线程,本文将记录下在Qt开发中用到的多线程技术实现方法,以导出指定范围的数字到txt文件为例,展示多线程不同的实现方... 目录前言导出文件的示例工具类QThreadQObject的moveToThread方法实现多线程QC

RabbitMQ消费端单线程与多线程案例讲解

《RabbitMQ消费端单线程与多线程案例讲解》文章解析RabbitMQ消费端单线程与多线程处理机制,说明concurrency控制消费者数量,max-concurrency控制最大线程数,prefe... 目录 一、基础概念详细解释:举个例子:✅ 单消费者 + 单线程消费❌ 单消费者 + 多线程消费❌ 多

Javaee多线程之进程和线程之间的区别和联系(最新整理)

《Javaee多线程之进程和线程之间的区别和联系(最新整理)》进程是资源分配单位,线程是调度执行单位,共享资源更高效,创建线程五种方式:继承Thread、Runnable接口、匿名类、lambda,r... 目录进程和线程进程线程进程和线程的区别创建线程的五种写法继承Thread,重写run实现Runnab

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

MySQL中的索引结构和分类实战案例详解

《MySQL中的索引结构和分类实战案例详解》本文详解MySQL索引结构与分类,涵盖B树、B+树、哈希及全文索引,分析其原理与优劣势,并结合实战案例探讨创建、管理及优化技巧,助力提升查询性能,感兴趣的朋... 目录一、索引概述1.1 索引的定义与作用1.2 索引的基本原理二、索引结构详解2.1 B树索引2.2

python多线程并发测试过程

《python多线程并发测试过程》:本文主要介绍python多线程并发测试过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、并发与并行?二、同步与异步的概念?三、线程与进程的区别?需求1:多线程执行不同任务需求2:多线程执行相同任务总结一、并发与并行?1、

Python多进程、多线程、协程典型示例解析(最新推荐)

《Python多进程、多线程、协程典型示例解析(最新推荐)》:本文主要介绍Python多进程、多线程、协程典型示例解析(最新推荐),本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定... 目录一、multiprocessing(多进程)1. 模块简介2. 案例详解:并行计算平方和3. 实现逻