朴素贝叶斯 python 实现

本文提供了一个关于朴素贝叶斯分类器的实现案例,通过具体的Python代码解释了如何计算先验概率及条件概率,并最终应用于分类任务。示例中使用了一组天气数据来预测是否适合进行户外活动。

百度文库
文库2

机器学习实战的朴素贝叶斯的代码太复杂

"""
Created on Thu Aug 10 15:08:59 2017

@author: luogan
"""

#coding=gbk

#Naive Bayes

#Calculate the Prob. of class:cls
def P(data,cls_val,cls_name="class"):
    cnt = 0.0
    for e in data:
        if e[cls_name] == cls_val:
            cnt += 1

    return cnt/len(data)

#Calculate the Prob(attr|cls)
def PT(data,cls_val,attr_name,attr_val,cls_name="class"):
    cnt1 = 0.0
    cnt2 = 0.0
    for e in data:
        if e[cls_name] == cls_val:
            cnt1 += 1
            if e[attr_name] == attr_val:
                cnt2 += 1

    return cnt2/cnt1

#Calculate the NB
def NB(data,test,cls_y,cls_n):
    PY = P(data,cls_y)
    PN = P(data,cls_n)
    for key,val in test.items():
        print (key,val)
        PY *= PT(data,cls_y,key,val)
        PN *= PT(data,cls_n,key,val)
    return {cls_y:PY,cls_n:PN}


if __name__ == "__main__":

    #data
    data = [
        {"outlook":"sunny", "temp":"hot", "humidity":"high", "wind":"weak", "class":"no" },
        {"outlook":"sunny", "temp":"hot", "humidity":"high", "wind":"strong", "class":"no" },
        {"outlook":"overcast", "temp":"hot", "humidity":"high", "wind":"weak", "class":"yes" },
        {"outlook":"rain", "temp":"mild", "humidity":"high", "wind":"weak", "class":"yes" },
        {"outlook":"rain", "temp":"cool", "humidity":"normal", "wind":"weak", "class":"yes" },
        {"outlook":"rain", "temp":"cool", "humidity":"normal", "wind":"strong", "class":"no" },
        {"outlook":"overcast", "temp":"cool", "humidity":"normal", "wind":"strong", "class":"yes" },
        {"outlook":"sunny", "temp":"mild", "humidity":"high", "wind":"weak", "class":"no" },
        {"outlook":"sunny", "temp":"cool", "humidity":"normal", "wind":"weak", "class":"yes" },
        {"outlook":"rain", "temp":"mild", "humidity":"normal", "wind":"weak", "class":"yes" },
        {"outlook":"sunny", "temp":"mild", "humidity":"normal", "wind":"strong", "class":"yes" },
        {"outlook":"overcast", "temp":"mild", "humidity":"high", "wind":"strong", "class":"yes" },
        {"outlook":"overcast", "temp":"hot", "humidity":"normal", "wind":"weak", "class":"yes" },
        {"outlook":"rain", "temp":"mild", "humidity":"high", "wind":"strong", "class":"no" },
        ]

    #calculate
    print (NB(data,{"outlook":"sunny","temp":"cool","humidity":"high","wind":"strong"},"yes","no"))
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值