朴素贝叶斯法是基于贝叶斯定理与特征条件独立假设的分类方法。对于给定的训练数据集 ,首先基于特征条件独立假设学习输入输出的联合概率分布;然后基于此模型,对给定的输入x,利用贝叶斯定理求出后验概率最大的输出y。
使用高斯bayes对Iris数据集进行分类
import numpy as np
import pandas as pd
import random
dataSet =pd.read_csv('iris.txt',header = None)
dataSet.head()
def randSplit(dataSet, rate):
l = list(dataSet.index) #提取出索引
random.shuffle(l) #随机打乱索引
dataSet.index = l #将打乱后的索引重新赋值给原数据集
n = dataSet.shape[0] #总行数
m = int(n * rate) #训练集的数量
train = dataSet.loc[range(m), :] #提取前m个记录作为训练集
test = dataSet.loc[range(m, n), :] #剩下的作为测试集
dataSet.index = range(dataSet.shape[0]) #更新原数据集的索引
test.index = range(test.shape[0]) #更新测试集的索引
return train, test
def gnb_classify(train,test):
labels = train.iloc[:,-1].value_counts().index #提取训练集的标签种类
mean =[] #存放每个类别的均值
std =[] #存放每个类别的方差
result = [] #存放测试集的预测结果
for i in labels:
item = train.loc[train.iloc[:,-1]==i,:] #分别提取出每一种类别
m = item.iloc[:,:-1].mean() #当前类别的平均值 对每个特征计算均值
s = np.sum((item.iloc[:,:-1]-m)**2)/(item.shape[0]) #当前类别的方差
mean.append(m) #将当前类别的平均值追加至列表
std.append(s) #将当前类别的方差追加至列表
means = pd.DataFrame(mean,index=labels) #变成DF格式,索引为类标签
stds = pd.DataFrame(std,index=labels) #变成DF格式,索引为类标签
for j in range(test.shape[0]):
iset = test.iloc[j,:-1].tolist() #当前测试实例
iprob = np.exp(-1*(iset-means)**2/(stds*2))/(np.sqrt(2*np.pi*stds)) #正态分布公式
prob = 1 #初始化当前实例总概率
for k in range(test.shape[1]-1): #遍历每个特征
prob *= iprob[k] #特征概率之积即为当前实例概率
cla = prob.index[np.argmax(prob.values)] #返回最大概率的类别
result.append(cla)
test['predict']=result
acc = (test.iloc[:,-1]==test.iloc[:,-2]).mean() #计算预测准确率
print('模型预测准确率为:',acc)
return test
train , test = randSplit(dataSet,0.8)
pre = gnb_classify(train,test)
print(pre)
def trainNB(trainMat,classVec):
n = len(trainMat) #计算训练的文档数目
m = len(trainMat[0]) #计算每篇文档的词条数
pAb = sum(classVec)/n #文档属于侮辱类的概率
p0Num = np.ones(m) #词条出现数初始化为1
p1Num = np.ones(m) #词条出现数初始化为1
p0Denom = 2 #分母初始化为2
p1Denom = 2 #分母初始化为2
for i in range(n): #遍历每一个文档
if classVec[i] == 1: #统计属于侮辱类的条件概率所需的数据
p1Num += trainMat[i]
p1Denom += sum(trainMat[i])
else: #统计属于非侮辱类的条件概率所需的数据
p0Num += trainMat[i]
p0Denom += sum(trainMat[i])
p1V = np.log(p1Num/p1Denom)
p0V = np.log(p0Num/p0Denom)
return p0V,p1V,pAb #返回属于非侮辱类,侮辱类和文档属于侮辱类的概率
def classifyNB(vec2Classify, p0V, p1V, pAb):
p1 = sum(vec2Classify * p1V) + np.log(pAb) #对应元素相乘
p0 = sum(vec2Classify * p0V) + np.log(1- pAb) #对应元素相乘
if p1 > p0:
return 1
else:
return 0
————————————————
版权声明:本文为CSDN博主「小杰.」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_44285710/article/details/104626689