朴素贝叶斯代码实现(超详细)

想详细了解贝叶斯算法的,可点击笔者的另一篇文章案列分析带你彻底了解贝叶斯​​​​​​​

在这里我将写一个简单的贝叶斯代码实现。

首先先导入库

import pandas as pd

为了可以帮助更好地理解模型的性能,找出模型可能存在的问题,我们要创建一个混淆矩阵的可视

def cm_plot(y, yp):
    from sklearn.metrics import confusion_matrix
    import matplotlib.pyplot as plt

    cm = confusion_matrix(y, yp)
    plt.matshow(cm, cmap=plt.cm.Blues)
    plt.colorbar()
    for x in range(len(cm)):
        for y in range(len(cm)):
            plt.annotate(cm[x, y], xy=(y, x), horizontalalignment='center',
                         verticalalignment='center')
            plt.ylabel('True label')
            plt.xlabel('Predicted label')
    return plt

进行数据预处理,将数据读入,并删除第一行序列
数据获取

部分数据展示

data = pd.read_csv("iris.csv", encoding='utf8', engine='python', header=None)
data = data.drop(0, axis=1)  # 把第1列删除,
data.head()

对原始数据集进行切分

X_whole = data.drop(5, axis=1)  
y_whole = data[5]  

在切分数据集

from sklearn.model_selection import train_test_split

x_train_w, x_test_w, y_train_w, y_test_w = \
    train_test_split(X_whole, y_whole, test_size=0.2, random_state=0)

导入朴素贝叶斯分类器,实例化贝叶斯分类器分类。

from sklearn.naive_bayes import MultinomialNB

ml = MultinomialNB(alpha=1)

传入·训练集数据

ml.fit(x_train, y_train)

训练集与测试集预测,绘制混淆矩阵

train_pred = classifier.predict(x_train_w)
cm_plot(y_train_w, train_pred).show()


test_pred = classifier.predict(x_test_w)
cm_plot(y_test_w, test_pred).show()

图像如下

进行预测,并打印出分类报告。

from sklearn import metrics
pre = ml.predict(x_test)
print(metrics.classification_report(y_test, pre))
plt.show()

显示结果:

 

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值