python 朴素贝叶斯简单实现

来源:互联网 发布:c语言开发游戏 编辑:程序博客网 时间:2024/06/05 07:06
import reimport maths=['this is yes','that is no']r=[0,1]def tokenize(message):    '''分割单词'''    message=message.lower()    all_words = re.findall('[a-z0-9]+', message)    print(all_words)    return set(all_words)word_set = tokenize(' '.join(s))print(word_set)def count_words(training_set):    '''记录单词分别在不同类中出现的次数'''    counts={}    for message,is_spam in zip(s,r):        print(message,is_spam)        for word in tokenize(message):            if word not in counts.keys():                counts[word]=[0,0]            counts[word][0 if is_spam else 1]+=1    return countscounts=count_words(s)print(counts)def word_probablities(counts, total_spams, total_non_spams, k=0.5):    '''通过统计各单词在不同类中出现的次数计算出概率'''    result=[]    for w,(spam, non_spam) in dict(counts).items():        result.append((w, (spam+k)/(total_spams+2*k), (non_spam+k)/(total_non_spams+2*k) ))    return resultword_prob=word_probablities(counts, 1,1)print(word_prob)def spam_message(word_prob, message):    '''计算新数据概率'''    message_words = tokenize(message)    log_prob_spam=0    log_prob_non_spam=0    for word, prob_spam, prob_non_spam in word_prob:        if word in message_words:            # 如果新单词在字典中出现            log_prob_spam+=math.log(prob_spam)            log_prob_non_spam+=math.log(prob_non_spam)        else:            # 如果新单词没有在字典中出现            log_prob_spam+=math.log(1.0-prob_spam)            log_prob_non_spam+=math.log(1.0-prob_non_spam)    prob_is_spam=math.exp(log_prob_spam)    prob_is_non_spam=math.exp(log_prob_non_spam)    return prob_is_spam/(prob_is_spam+prob_is_non_spam)print(spam_message(word_prob, "no is ns"))
阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 高进写的歌 李宗盛写的歌 手机写歌软件自动编曲 写歌软件 手机写歌软件 写作业听什么歌 写语文作业适合听什么歌 三分钟学会写歌 为你写歌 歌笔顺怎么写 怎么写歌 为你写首歌 歌怎么写 写作业听什么歌写得快 汉字歌 姚谦写的歌 李宗盛用13首歌写尽人生 高进为什么给大壮写歌 写法 数字写法 拼音写法 捺的写法 草书写法 a写法 8的写法 8写法 a的写法 数字5的写法 拼音u的写法 拼音u写法 火笔顺写法 0的写法 0写法 弯钩的写法 拼音f的写法 字写法 字母写法 数字的写法 m写法 9写法 4写法