from numpy import *

import time
starttime = time.time() 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]
return postingList, classVec def createVocabList(dataSet): # dataSet = postingList
vocabSet = set([]) # vocabSet = set(dataSet)
for document in dataSet:
vocabSet = vocabSet | set(document) #
return list(vocabSet) # createVocabList = list(set(dataSet)) def setOfWords2Vec(vocabList, inputSet):
returnVec = [0] * len(vocabList) # [0, 0 , 0 ,0,..] len(vocabList) 0
for word in vocabList:
if word in inputSet:
returnVec[vocabList.index(word)] = 1 + 1.0
else:
returnVec[vocabList.index(word)] = 1.0
print "the word: %s is not in my Vocabulary!" % word
return returnVec def txt2trainxy(filename1, filename2):
import re
reg = re.compile(r'\W*') #
# step 1: loading data...
print "stet 1: loading data..."
from os import listdir
ld1 = listdir('email/' + filename1); ld2 = listdir('email/' + filename2)
filelist = ld1 + ld2
trainy = ((filename1 + '\t') * len(ld1) + (filename2 + '\t') * len(ld2)).split() trainx = []; fulltext = []; i = 0
for File in filelist:
if i < len(ld1):
fr = reg.split(open('email/' + filename1 + '/' + File).readlines()[0].lower())
else:
fr = reg.split(open('email/' + filename2 + '/' + File).readlines()[0].lower())
trainx.append([f for f in fr if len(f) > 2]) #
fulltext.extend([f for f in fr if len(f) > 2]) #
i += 1
fulltext = list(set(fulltext))
# set of words
trainxws = [[list(set(item)).count(strg) + 1.0 for strg in fulltext] for item in trainx]
# bag of words
trainxwb = [[item.count(strg) + 1.0 for strg in fulltext] for item in trainx] return trainxws, trainxwb, trainy, trainx, fulltext def testx2vec(testx, fulltext):
# set of words
testxws = [list(set(testx)).count(strg) + 1.0 for strg in fulltext] #
# bag of words
testxwb = [testx.count(strg) + 1.0 for strg in fulltext] #
for word in testx:
if word not in fulltext:
print "the word: %s is not in my fulltext!" % word
return testxws, testxwb def bayes(testx, trainx, trainy, fulltext):
print "---Getting Prob..."
s = set(trainy); l = len(trainy); r = len(trainx[0])
IDs = [[id for id in range(l) if trainy[id] == item] for item in s]
logproby = [log(array(trainy.count(item)) / float(l)) for item in s]
numbxv = [sum([trainx[id] for id in ids], 0) for ids in IDs]
numbx = [sum([trainx[id] for id in ids]) + 2.0 for ids in IDs] #
probx = [numbxv[i] / float(numbx[i]) for i in range(len(s))]
logprobx = [[log(p[i]) for i in range(r)] for p in probx]
print "---Printing Prob..."
#print probx
print [fulltext[i] for i in (-array(probx)).argsort()[:,: 5][0]] # argsort() small to big
print trainy[IDs[0][0]]
print [fulltext[i] for i in (-array(probx)).argsort()[:,: 5][1]]
print trainy[IDs[1][0]]
"""
print IDs
print numbxv
print logprobx
""" # step 4: showing the result...
print "---Showing the result..."
# set of words
sumlogpxws = sum(array(logprobx) * testx, 1)
sumlogpxyws = array(sumlogpxws) + array(logproby)
#print logprobx
print sumlogpxws
print sum(array(probx) * testx, 1)
bestyws = trainy[IDs[sumlogpxyws.argmax()][0]]
print "---From set of words: ", bestyws
"""
# bag of words
sumlogpxwb = sum(array(logprobx) * testxwb, 1)
sumlogpxywb = array(sumlogpxwb) + array(logproby)
bestywb = trainy[IDs[sumlogpxywb.argmax()][0]]
print "---From bag of words: ", bestywb
"""
return bestyws def main():
# step 1: loading data...
trainxws, trainxwb, trainy, trainx, fulltext = txt2trainxy('spam','ham')
print fulltext # step 2: training...
print "step 2: training..."
pass # step 3: testing...
print "step 3: testing..."
print "---Preparing testdata..."
import random
l = len(trainy)
testid = random.sample(range(l), 20)
testxxx = [trainxws[i] for i in testid]
testyyy = [trainy[i] for i in testid]
testtrainxws = [trainxws[i] for i in range(l) if i not in testid]
testtrainy = [trainy[i] for i in range(l) if i not in testid]
print "---Testing now..."
errorcount = 0; p = len(testid)
for i in range(p):
if bayes(testxxx[i], testtrainxws, testtrainy, fulltext) != testyyy[i]:
errorcount += 1
print errorcount
print p
print "---Errorrate is: ", (errorcount / float(p)) # step 4: showing the result
print "step 4: using..."
testx = ['love', 'my', 'dalmation']
print "the testx is: ", testx
print "---Changing testx into vector..."
testxws, testxwb = testx2vec(testx, fulltext)
#print testxws
bayes(testxws, testtrainxws, testtrainy, fulltext) main() """
trainx, trainy = loadDataSet()
fulltext = createVocabList(trainx)
print fulltext
print setOfWords2Vec(fulltext, trainx[0])
trainxws = []
for t in trainx:
trainxws.append(setOfWords2Vec(fulltext, t))
testEntry1 = ['love', 'my', 'dalmation']
testEntry2 = ['stupid', 'garbage']
bayes(testEntry1, trainxws, trainy, fulltext) """

bayes的更多相关文章

  1. 【十大经典数据挖掘算法】Naïve Bayes

    [十大经典数据挖掘算法]系列 C4.5 K-Means SVM Apriori EM PageRank AdaBoost kNN Naïve Bayes CART 朴素贝叶斯(Naïve Bayes) ...

  2. 最大似然判别法和Bayes公式判别法

    最大似然判别法 Bayes公式判别法

  3. [Machine Learning & Algorithm] 朴素贝叶斯算法(Naive Bayes)

    生活中很多场合需要用到分类,比如新闻分类.病人分类等等. 本文介绍朴素贝叶斯分类器(Naive Bayes classifier),它是一种简单有效的常用分类算法. 一.病人分类的例子 让我从一个例子 ...

  4. Spark MLlib 之 Naive Bayes

    1.前言: Naive Bayes(朴素贝叶斯)是一个简单的多类分类算法,该算法的前提是假设各特征之间是相互独立的.Naive Bayes 训练主要是为每一个特征,在给定的标签的条件下,计算每个特征在 ...

  5. 基于Bayes和KNN的newsgroup 18828文本分类器的Python实现

    向@yangliuy大牛学习NLP,这篇博客是数据挖掘-基于贝叶斯算法及KNN算法的newsgroup18828文本分类器的JAVA实现(上)的Python实现.入门为主,没有太多自己的东西. 1. ...

  6. Microsoft Naive Bayes 算法——三国人物身份划分

    Microsoft朴素贝叶斯是SSAS中最简单的算法,通常用作理解数据基本分组的起点.这类处理的一般特征就是分类.这个算法之所以称为“朴素”,是因为所有属性的重要性是一样的,没有谁比谁更高.贝叶斯之名 ...

  7. Naive Bayes理论与实践

    Naive Bayes: 简单有效的常用分类算法,典型用途:垃圾邮件分类 假设:给定目标值时属性之间相互条件独立 同样,先验概率的贝叶斯估计是 优点: 1. 无监督学习的一种,实现简单,没有迭代,学习 ...

  8. [ML] Naive Bayes for Text Classification

    TF-IDF Algorithm From http://www.ruanyifeng.com/blog/2013/03/tf-idf.html Chapter 1, 知道了"词频" ...

  9. 朴素贝叶斯方法(Naive Bayes Method)

        朴素贝叶斯是一种很简单的分类方法,之所以称之为朴素,是因为它有着非常强的前提条件-其所有特征都是相互独立的,是一种典型的生成学习算法.所谓生成学习算法,是指由训练数据学习联合概率分布P(X,Y ...

  10. 数据挖掘十大经典算法(9) 朴素贝叶斯分类器 Naive Bayes

    贝叶斯分类器 贝叶斯分类器的分类原理是通过某对象的先验概率,利用贝叶斯公式计算出其后验概率,即该对象属于某一类的概率,选择具有最大后验概率的类作为该对象所属的类.眼下研究较多的贝叶斯分类器主要有四种, ...

随机推荐

  1. yum nfs

    linux下3大文件共享方法 1.NFS NFS服务器配置 编辑/etc/exports,在文件中列出,要共享的目录.书写规则是:共享目录主机(参数).并且每条规则占据一行.例如: /mnt/mp3 ...

  2. CloudFoundry云环境中应用的特殊设计

    常规的应用,大多数可以不经过任何修改即可部署于CloudFoundry云平台之上,但是在一些特殊情况下,总是不可避免地会出现一些细小的问题,如果在应用设计之初,就考虑到针对云平台的一些特殊情况,遵守云 ...

  3. python爬虫__第一个爬虫程序

    前言 机缘巧合,最近在学习机器学习实战, 本来要用python来做实验和开发环境 得到一个需求,要爬取大众点评中的一些商户信息, 于是开启了我的第一个爬虫的编写,里面有好多心酸,主要是第一次. 我的文 ...

  4. localStorage存储JSON对象的小方法

    有时候,我们需要将数据存储到sessionStorage和localStorage中,这样做的好处有: 1 缓存数据 2 减少对内存的占用 但是,storage只能存储字符串的数据,对于JS中常用的数 ...

  5. Android Framework 记录之二

    接着上次的记录,续写. 23.services文件夹 文件 描写叙述 class AlarmManagerService extends IAlarmManager.Stub { //定时管理服务 p ...

  6. Android ExpandableListView BaseExpandableListAdapter (类似QQ分组列表)

    分组列表视图(ExpandableListView) 和ListView不同的是它是一个两级的滚动列表视图,每一个组可以展开,显示一些子项,类似于QQ列表,这些项目来至于ExpandableListA ...

  7. COM编程入门第一部分——什么是COM,如何使用COM

    本文的目的是为刚刚接触COM的程序员提供编程指南,并帮助他们理解COM的基本概念.内容包括COM规范简介,重要的COM术语以及如何重用现有的COM组件.本文不包括如何编写自己的COM对象和接口. CO ...

  8. 关于lower_bound()的用法--NYOJ 201作业题

    lower_bound它有三个参数, 第一个和第二个是给定区间起点和终点的指针,第三个参数是要查找的数,它的作用原理是在给定的区间中进行二分查找,这个二分区间是前开后闭的,他返回第一个大于等于它的函数 ...

  9. Python迭代--笔记

    <python3 程序开发指南> 迭代子.迭代操作 迭代子是一个对象,该对象可提供_next_()方法,该方法依次返回每个相继的数据项,并在没有数据项时产生StopIteration()异 ...

  10. Java多线程——多线程的基本概念和使用

    一.进程和线程的基础知识 1.进程和线程的概念 进程:运行中的应用程序称为进程,拥有系统资源(cpu.内存) 线程:进程中的一段代码,一个进程中可以有多段代码.本身不拥有资源(共享所在进程的资源) 在 ...