欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

基于python的留一法+朴素贝叶斯分类2021-05-13

程序员文章站 2022-05-04 16:39:49
...

用python进行简单的朴素贝叶斯分类,这里是用性别、体重两个特征预测性别。新手,仅记录,欢迎指导。

import pandas as pd    #  导入Python的数据处理库pandas,相当于Python里的excel
import numpy as np    
data = pd.read_csv('biyelunwen.csv',encoding='gbk')

# 把data转成一个个的数组,不做这一步直接输data[:,0:2],就会报错
A=np.array(data)
X=A[:,0:2]
y=A[:,2]

# 导入朴素高斯贝叶斯、LOO模块
from sklearn import naive_bayes
from sklearn.model_selection import LeaveOneOut
loo=LeaveOneOut()
clf=naive_bayes.GaussianNB()

right=0
for train_index,test_index in loo.split(data):
    X_train,X_test=X[train_index],X[test_index]
    y_train,y_test=y[train_index],y[test_index]
    
    clf.fit(X_train,y_train)
    y_test_pred = clf.predict(X_test)
    if y_test_pred==y_test:
        right=right+1
    else:
        right=right+0

# 用X.shape[0]输出X的行数,用X.shape[1]输出X的列数
acc=right/X.shape[0]
print('准确率={:.2f}%'.format(acc*100))

 最后结果:

准确率=80.00%