当前位置: 首页 > 编程日记 > 正文

朴素贝叶斯算法的python实现

朴素贝叶斯

算法优缺点

  • 优点:在数据较少的情况下依然有效,可以处理多类别问题

  • 缺点:对输入数据的准备方式敏感

  • 适用数据类型:标称型数据

算法思想:

朴素贝叶斯
比如我们想判断一个邮件是不是垃圾邮件,那么我们知道的是这个邮件中的词的分布,那么我们还要知道:垃圾邮件中某些词的出现是多少,就可以利用贝叶斯定理得到。
朴素贝叶斯分类器中的一个假设是:每个特征同等重要

函数

loadDataSet()

创建数据集,这里的数据集是已经拆分好的单词组成的句子,表示的是某论坛的用户评论,标签1表示这个是骂人的

createVocabList(dataSet)

找出这些句子中总共有多少单词,以确定我们词向量的大小

setOfWords2Vec(vocabList, inputSet)

将句子根据其中的单词转成向量,这里用的是伯努利模型,即只考虑这个单词是否存在

bagOfWords2VecMN(vocabList, inputSet)

这个是将句子转成向量的另一种模型,多项式模型,考虑某个词的出现次数

trainNB0(trainMatrix,trainCatergory)

计算P(i)和P(w[i]|C[1])和P(w[i]|C[0]),这里有两个技巧,一个是开始的分子分母没有全部初始化为0是为了防止其中一个的概率为0导致整体为0,另一个是后面乘用对数防止因为精度问题结果为0

classifyNB(vec2Classify, p0Vec, p1Vec, pClass1)

根据贝叶斯公式计算这个向量属于两个集合中哪个的概率高

  1.  1 #coding=utf-8
     2 from numpy import *
     3 def loadDataSet():
     4     postingList=[['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'],
     5                  ['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],
     6                  ['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him'],
     7                  ['stop', 'posting', 'stupid', 'worthless', 'garbage'],
     8                  ['mr', 'licks', 'ate', 'my', 'steak', 'how', 'to', 'stop', 'him'],
     9                  ['quit', 'buying', 'worthless', 'dog', 'food', 'stupid']]
    10     classVec = [0,1,0,1,0,1]    #1 is abusive, 0 not
    11     return postingList,classVec
    12 
    13 #创建一个带有所有单词的列表
    14 def createVocabList(dataSet):
    15     vocabSet = set([])
    16     for document in dataSet:
    17         vocabSet = vocabSet | set(document)
    18     return list(vocabSet)
    19     
    20 def setOfWords2Vec(vocabList, inputSet):
    21     retVocabList = [0] * len(vocabList)
    22     for word in inputSet:
    23         if word in vocabList:
    24             retVocabList[vocabList.index(word)] = 1
    25         else:
    26             print 'word ',word ,'not in dict'
    27     return retVocabList
    28 
    29 #另一种模型    
    30 def bagOfWords2VecMN(vocabList, inputSet):
    31     returnVec = [0]*len(vocabList)
    32     for word in inputSet:
    33         if word in vocabList:
    34             returnVec[vocabList.index(word)] += 1
    35     return returnVec
    36 
    37 def trainNB0(trainMatrix,trainCatergory):
    38     numTrainDoc = len(trainMatrix)
    39     numWords = len(trainMatrix[0])
    40     pAbusive = sum(trainCatergory)/float(numTrainDoc)
    41     #防止多个概率的成绩当中的一个为0
    42     p0Num = ones(numWords)
    43     p1Num = ones(numWords)
    44     p0Denom = 2.0
    45     p1Denom = 2.0
    46     for i in range(numTrainDoc):
    47         if trainCatergory[i] == 1:
    48             p1Num +=trainMatrix[i]
    49             p1Denom += sum(trainMatrix[i])
    50         else:
    51             p0Num +=trainMatrix[i]
    52             p0Denom += sum(trainMatrix[i])
    53     p1Vect = log(p1Num/p1Denom)#处于精度的考虑,否则很可能到限归零
    54     p0Vect = log(p0Num/p0Denom)
    55     return p0Vect,p1Vect,pAbusive
    56     
    57 def classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):
    58     p1 = sum(vec2Classify * p1Vec) + log(pClass1)    #element-wise mult
    59     p0 = sum(vec2Classify * p0Vec) + log(1.0 - pClass1)
    60     if p1 > p0:
    61         return 1
    62     else: 
    63         return 0
    64         
    65 def testingNB():
    66     listOPosts,listClasses = loadDataSet()
    67     myVocabList = createVocabList(listOPosts)
    68     trainMat=[]
    69     for postinDoc in listOPosts:
    70         trainMat.append(setOfWords2Vec(myVocabList, postinDoc))
    71     p0V,p1V,pAb = trainNB0(array(trainMat),array(listClasses))
    72     testEntry = ['love', 'my', 'dalmation']
    73     thisDoc = array(setOfWords2Vec(myVocabList, testEntry))
    74     print testEntry,'classified as: ',classifyNB(thisDoc,p0V,p1V,pAb)
    75     testEntry = ['stupid', 'garbage']
    76     thisDoc = array(setOfWords2Vec(myVocabList, testEntry))
    77     print testEntry,'classified as: ',classifyNB(thisDoc,p0V,p1V,pAb)
    78     
    79     
    80 def main():
    81     testingNB()
    82     
    83 if __name__ == '__main__':
    84     main()

    机器学习笔记索引

来自为知笔记(Wiz)



转载于:https://www.cnblogs.com/MrLJC/p/4102737.html

相关文章:

iOS 加载本地和网络gif 图片类扩展

https://github.com/AlexanderYeah/GifKuoZhan [self.meiXueImgView showGifImageWithData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:"美" ofType:"gif"]]];

arkit与现实世界距离比_如何使用ARKit和Pusher构建实时增强现实测量应用程序

arkit与现实世界距离比by Esteban Herrera由Esteban Herrera 如何使用ARKit和Pusher构建实时增强现实测量应用程序 (How to Build a Real-Time Augmented Reality Measuring App with ARKit and Pusher) Augmented reality (AR) is all about modifying our perception of the…

Servlet 3.0 新特性概述

Servlet 3.0 新特性概述 Servlet 3.0 作为 Java EE 6 规范体系中一员,随着 Java EE 6 规范一起发布。该版本在前一版本(Servlet 2.5)的基础上提供了若干新特性用于简化 Web 应用的开发和部署。其中有几项特性的引入让开发者感到非常兴奋&…

MVC、MVP、MVVM

MVC、MVP、MVVM这些模式是为了解决开发过程中的实际问题而提出来的,目前作为主流的几种架构模式而被广泛使用。 一、MVC(Model-View-Controller) MVC是比较直观的架构模式,用户操作->View(负责接收用户的输入操作&a…

iOS 计算两个日期之间的差值

NSDateFormatter *dateFomatter [[NSDateFormatter alloc] init];dateFomatter.dateFormat "yyyy-MM-dd HH:mm";// 当前时间字符串格式NSDate *planDate [dateFomatter dateFromString:[model.PlanTime substringToIndex:16]];// 当前日历NSCalendar *calendar […

unity水管工_我是如何从30岁的管道工转变为32岁的Web开发人员的

unity水管工by Rick West由里克韦斯特(Rick West) 我是如何从30岁的管道工转变为32岁的Web开发人员的 (How I transformed from a 30-year-old plumber into a 32-year-old web developer) Friends often ask me why I decided to give up a solid, well-paying job like plum…

netty集成ssl完整参考指南(含完整源码)

虽然我们在内部rpc通信中使用的是基于认证和报文头加密的方式实现安全性,但是有些时候仍然需要使用SSL加密,可能是因为对接的三方系统需要,也可能是由于open的考虑。中午特地测了下netty下集成ssl的功能,关于ssl的握手过程以及jav…

呼叫中心的服务水平管理

对企业来讲,呼叫中心是企业的窗口,呼叫中心为客户提供服务,是企业提升品牌形象、建立客户忠诚度的最佳通道。因此,呼叫中心的服务水平对于企业来说意义重大,相应的服务水平管理更是企业必不可少的管理之一。 “客户至上…

iOS 数组中的模型去重

NSMutableDictionary *mutableDic [NSMutableDictionary dictionary];for (HomeRectProductModel *model in self.modelArr) {[mutableDic setValue:model forKey:model.Id];}[self.modelArr removeAllObjects];self.modelArr [[mutableDic allValues] mutableCopy];// 方法…

软件可读性和效率取舍_网络通信设计中的一些限制和取舍:摘要

软件可读性和效率取舍by Shubheksha通过Shubheksha 网络通信设计中的一些约束和折衷:摘要 (Some Constraints and Trade-offs In The Design of Network Communications: A Summary) This article distills the content presented in the paper “Some Constraints…

浅析对象访问属性的.和[]方法区别

原文链接:http://www.cnblogs.com/bigboyLin/p/4967820.html 简明版:请问js对象属性值为什么用数组也可以访问 在JavaScript中通常使用”."运算符来存取对象的属性的值。或者使用[]作为一个关联数组来存取对象的属性。但是这两种方式有什么区别了&a…

iOS 关闭页面侧滑手势

-(void)popGestureChange:(UIViewController *)vc enable:(BOOL)enable{if ([vc.navigationController respondsToSelector:selector(interactivePopGestureRecognizer)]) {//遍历所有的手势for (UIGestureRecognizer *popGesture in vc.navigationController.interactivePopGe…

CSS与HTML结合

CSS与HTML结合的4中方式&#xff1a; 1、每个HTML标签都有style属性 2、当页面中有多个标签具有相同样式时&#xff0c;可定义style标签封装样式以复用 <style type”text/css”>css代码</style> 3、当多个页面使用相同样式时&#xff0c;可将样式单独封装为CSS文件…

硬件断点反跳似乎_高性能应用程序:多路复用,反跳,系统字体和其他技巧

硬件断点反跳似乎by Atila Fassina通过阿蒂拉法西纳(Atila Fassina) 高性能应用程序&#xff1a;多路复用&#xff0c;反跳&#xff0c;系统字体和其他技巧 (High Performance Apps: Multiplexing, Debouncing, System Fonts, and other tricks) Here are some performance ti…

jquery仿邮箱文本输入框自动加载邮箱后缀

jquery仿邮箱文本输入框自动加载邮箱后缀 在像百度这样的网站注册时&#xff0c;你会看到输入邮箱会出现自动给用户输入补全主流邮箱。这种对于增加用户体验的小例子已司空见惯。正好看到人家写的这种js功能。还挺不错,使用起来很方便&#xff0c;几乎不用写神呢代码。"傻…

Maven最佳实践:划分模块

所有用Maven管理的真实的项目都应该是分模块的&#xff0c;每个模块都对应着一个pom.xml。它们之间通过继承和聚合&#xff08;也称作多模块&#xff0c;multi-module&#xff09;相互关联。那么&#xff0c;为什么要这么做呢&#xff1f;我们明明在开发一个项目&#xff0c;划…

facebook 直播_什么时候是在Facebook Live上直播的最佳时间? 我分析了5,000个Facebook帖子以找出答案。...

facebook 直播by Ofir Chakon由Ofir Chakon 什么时候是在Facebook Live上直播的最佳时间&#xff1f; 我分析了5,000个Facebook帖子以找出答案。 (When is the best time to stream on Facebook Live? I analyzed 5,000 Facebook posts to find out.) Streaming on Facebook …

解决keepalived脑裂问题

检测思路&#xff1a;正常情况下keepalived的VIP地址是在主节点上的&#xff0c;如果在从节点发现了VIP&#xff0c;就设置报警信息 脚本如下&#xff1a; #!/bin/bash # 检查脑裂的脚本&#xff0c;在备节点上进行部署 LB01_VIP10.10.10.229 LB01_IP10.10.10.129 LB02_IP10.10…

iOS 根据中文字符串排序出字母索引

// 传入字符串数组 返回索引字典 - (NSDictionary *)createCharacter:(NSMutableArray *)strArr {NSMutableDictionary *dict [NSMutableDictionary dictionary];for (NSString *stringdict in strArr) {NSString *string stringdict;if ([string length]) {NSMutableString …

devops开发运维训练营_嗨,网络开发人员训练营的毕业生:这是您第一份工作需要了解的内容。...

devops开发运维训练营by Rachel Bird雷切尔伯德(Rachel Bird) 嗨&#xff0c;网络开发人员训练营的毕业生&#xff1a;这是您第一份工作需要了解的内容。 (Hey web dev bootcamp grads: Here’s what you need to know for your first job.) You worked your butt off and gai…

[bzoj1042][HAOI2008]硬币购物

有三种硬币&#xff0c;每种有自己的币值。 然后有n次询问&#xff0c;每次都给出每种硬币的数量和要付的钱s&#xff0c;求有多少种付法。n<1000 s<100000 ------ 不考虑限制&#xff0c;就是个简单dp.... 有限制的时候&#xff0c;我们可以考虑反过来用总的方案数量剪掉…

Windows netstat 查看端口、进程占用

目标&#xff1a;在Windows环境下&#xff0c;用netstat命令查看某个端口号是否占用&#xff0c;为哪个进程所占用. 操作&#xff1a;操作分为两步&#xff1a;&#xff08;1&#xff09;查看该端口被那个PID所占用;方法一&#xff1a;有针对性的查看端口&#xff0c;使用命令 …

iOS Named colors do not work prior to iOS 11.0问题解决

原文链接 https://stackoverflow.com/questions/48014246/named-colors-do-not-work-prior-to-ios-11-0-error-referring-to-a-storyboard/52967313#52967313 1 打开对应文件source code 2 粘贴查找 使用正则表达式 color key(.*) name.* 3 用以下代码覆盖 color key$1 …

如何在StackOverflow上获得第一个标签徽章-以及为什么它很重要。

by Angelos Chalaris通过安吉洛斯查拉利斯(Angelos Chalaris) 如何在StackOverflow上获得第一个标签徽章-以及为什么它很重要。 (How to get your first tag badge on StackOverflow — and why it’s important.) Every developer uses StackOverflow in different ways. Som…

int数据类型

1 a 18862 # 取商和余数3 print(a.__divmod__(10)) 4 5 # r反转,想当于 10-18866 print(a.__rsub__(10)) 7 8 # 取绝对值9 print(a.__abs__(), abs(a)) 10 11 #商取整 12 print(a.__floordiv__(10), a // 10) 转载于:https://www.cnblogs.com/xh4528/p/6497629.html

使用Google 官方的控件SwipeRefreshLayout实现下拉刷新功能

之前做东西的时候&#xff0c;经常会用到下拉刷新的功能&#xff0c;之前大家都在使用Github上的一个很著名的开源项目 PullToRefresh 但是&#xff0c;现在好消息来了&#xff0c;google在19.1版本的support-v4兼容包下面正式提供了官方的下拉刷新组件——SwipeRefreshLayout…

iOS 没到年底NSDate 时间出错问题

NSDate *currentDate [NSDate date];//获取当前时间&#xff0c;日期 NSDateFormatter *dateFormatter [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:"yyyy-MM-dd HH:mm:ss"]; // [dateFormatter setDateFormat:"YYYY-MM…

react 统一字段验证_如何使用React的受控输入进行即时表单字段验证

react 统一字段验证by Gosha Arinich通过Gosha Arinich 如何使用React的受控输入进行即时表单字段验证 (How to use React’s controlled inputs for instant form field validation) Controlled inputs enable simple things, like disabling the Submit button when some fi…

UISearchBar和 UISearchDisplayController的使用

感觉好多文章不是很全面&#xff0c;所以本文收集整合了网上的几篇文章&#xff0c;感觉有互相补充的效果。 如果想下载源码来看&#xff1a;http://code4app.com/search/searchbar 。本源码与本文无关 1、searchBar 本例子实现布局&#xff1a;上面是一个navigationController…

iOS 获取指定时间的前后N个月

https://www.cnblogs.com/SUPER-F/p/7298548.html 正数为后 负数为前 -(NSDate *)getPriousorLaterDateFromDate:(NSDate *)date withMonth:(NSInteger)month { NSDateComponents *comps [[NSDateComponents alloc] init]; [comps setMonth:month]; NSCalendar *calender …