贝叶斯分类器
1.基本的概率论知识
先验概率:由以往的数据得到的
后验概率:得到信息后再重新加以修正的概率
对于每个样本 选择能使后验概率 最大的类别标记
基于贝叶斯定理, 可以写成
先对联合概率分布 进行建模,再求后验概率
2.后验概率的最大化
对于类先验概率(prior),
,是样本空间中各类样本所占的比例,根据大数定律,当样本足够充足且独立同分布时,可以用样本出现的频率来拟合概率.
类条件概率 可能会出现属性组合爆炸的情况,一般不能使用简单的频率估计.(朴素贝叶斯分类器,就是直接使用)
利用极大似然估计
表示训练集 中第 类样本组成的集合,假设这些样本独立同分布.则参数 对于数据集 的似然是:
解决实际问题时,还需要考虑,连乘操作会导致数值的下溢 可以考虑使用对数似然的方法
3.naive bayes classifier 朴素贝叶斯分类器
属性条件独立性假设:
属性之间相互独立,基于这个假设,可以重新得到公式
其中d 是属性的数目, 是 在第i个属性上的取值
朴素分类器的训练过程就是基于训练数据集D来估计类先验概率 ,并为每个属性估计条件概率
训练过程
1.类先验概率
:
表示训练集D中第c类样本组成的集合
2.类条件概率 :
2.1对于离散属性而言:
表示
在i个属性上取值为
样本集合
则条件概率为:
2.2对于连续属性考虑概率密度函数. 假定
考虑均值和方差,则条件概率为:
上述训练过程需要注意的一点是:
若某个属性值咋训练集中没有与某个类同时出现过.基于上式进行计算,会让连乘式中出现概率值为零的情况.
一般进行拉普拉斯修正,平滑处理:
4.编程实现拉普拉斯修正的朴素贝叶斯分类器
朴素贝叶斯算法(naive bayes algorithm):
输入:训练数据集 T={
} 其中
,
是i个样本的第j个特征,
,
是第j个特征可能的取的第l个值;
实例 x
输出:实例 x 的分类.
(1) 计算先验概率及条件概率
(2)对于给定的实例
,计算:
(3)确定实例x的分类
根据上述算法进行编程
上面只是算法的思路,要考虑到拉普拉斯修正进行编程
# input watermelon csv file and process easy data cleaning
import pandas as pd
def in_put():
"""
@ return df.data
"""
with open("/home/dengshuo/GithubCode/ML/CH04/ID3watermelon3.csv") as f:
df=pd.read_csv(f)
return df
# too many thing need consider
# i need help
两个解决的方法,一步一步编程法;或者直接调用Sklearn库中的函数来进行
一步一步编程法: 需要强大的编程能力
调用Sklearn : 可能对数据的处理要求较高,对数据量较少的结果可能不是很好
先对 按步骤编程进行代码实现:
一个总结,当要去实现一个特定函数功能时候,可先将输入假设为所需要的数据结构和类型,读输入数据的处理放到后面
将每个函数进行结合.
也可以先使用一个函数,然后再去定义(在知道函数功能的前提下)
# date&time : 2018.05.07
# @author : dengshuo
# input excel or csv data
# define class
class LaplacianNB():
"""
Laplacian naive bayes for binary classification problem.
"""
def __init__(self):
"""
no parameter init
"""
def train(self,X,y):
"""
Training laplacian naive bayes classifier with training set(X,y)
Input:X,list of instances
y,list of labels
"""
N=len(y)
self.class=self.count_list(y)
self.class_num=len(self.class)
# calc prior probability
self.class_p={}
for c,n in self.class.items():
self.class_p[c]=float(n+1)/(N+self.class_num)
#print(self.class_p)
# calc conditional probability
self.discrete_attr_good_p=[]
self.diacrete_attr_bad_p=[]
for i in range(6):
attr_with_good=[]
attr_with_bad=[]
for j in range(N):
if y[j]==1: # it can replace with : if y[i]=="是"
attr_with_good.append(X[j][i])
else:
attr_with_bad.append(X[j][i])
unique_with_good=self.count_list(attr_with_good)
unique_with_bad=self.count_list(attr_with_bad)
self.discrete_attr_good_p.append(self.discrete_p(unique_with_good,self.class[1]))
self.discrete_attr_bad_p.append(self.discrete_p(unique_with_bad,self.class[0]))
# calc the continuous variable conditional probability
self.good_mus=[]
self.good_vars=[]
self.bad_mus=[]
self.bad_vars=[]
for i in range(6,8):
attr_with_good=[]
attr_with_bad=[]
for j in range(N):
if y[j]==1:
attr_with_good.append(X[j][i])
else:
attr_with_bad.append(X[j][i])
good_mu,good_var=self.mu_var_of_list(attr_with_good)
bad_mu,bad_var=self.mu_var_of_list(attr_with_bad)
self.good_mus.append(good_mu)
self.good_vars.append(good_var)
self.bad_mus.append(bad_mu)
self.bad_vars.append(bad_var)
def predict(self,x):
"""
x:the testset need calculate
@return: return the label class 0 or 1
"""
p_good=self.class_p[1]
p_bad=self.class_p[0]
for i in range(6):
p_good*=self.discrete_attar_with_good_p[i][x[i]]
p_bad*=self.discrete_attr_with_good_p[i][x[i]]
for i in range(6,8):
p_good*=self.continuous_p([x[i]],self.good_mus[i],self.good_vars[i])
p_bad*=self.continuous_p([x[i]],self.bad_mus[i],self.bad_vars[i])
if p_good>=p_bad:
return p_good,p_bad,1
else:
return p_good,p_bad,0
def count_list(self,List):
"""
List : input data
@return : count unique elements in list with dictionary
"""
unique_dict={}
for i in set(List):
unique_dict[i]=List.count(e)
return unique_dict
def discrete_p(self,d,N_class):
"""
d:attribute of dictionary
n_class: the number of label class
@return:the probaility of each feature with dictionary
"""
new_d={}
for a,n in d.items():
new_d[a]=float(n+1)/(N_class+len(d)) # n_class: means good or bad feature (amount)=class[1]
return new_d
def mu_var_of_list(self,l):
"""
l:list of feature
@return:
"""
mu=sum(l)/float(len(l))
var=0
for i in range(len(l)):
var+=(l[i]-mu)**2
var=var/float(len(l))
return mu,var
def continuous_p(self,x,mu,var):
"""
x: the input testset
mu: the meanvalue
var: the variance
@return the testset probaility
"""
import math
p=1.0/(math.sqrt(2*math.pi)*math.sqrt(var)*math.exp(-(x-mu)**2/(2*var)))
return p
import xlrd
if __name__=="__main__":
lnb=laplacianNB()
# read excel dataset ,of course can use pandas read csv_file
workbook=xlrd.open_workbook('the dataset.xlsx')
sheet=workbook.sheet_by_name("Sheet1")
X=[]
for i in range(17):
x=sheet.col_values(i)
for j in range(6):
x[j]=int(x[j])
x.pop()
X.append(x)
y=sheet.row_values(8)
y=[int(i) for i in y]
lnb.trian(X,y)
label=lnb.predict([1,1,1,1,1,1,0.697,0.460])
print("predict result {}".format(label))
调用Sklearn 库来实现
数据的读取,数据的处理,(数据的可视化处理),库函数的调用
最重要,可能也是最难的就是:如何将数据处理成函数可以直接使用的类型(先不管数据的输入类型,定义函数)
# read csv_file dataset
import pandas as pd
def in_put():
"""
@ return df.data
"""
with open("/home/dengshuo/GithubCode/ML/CH04/ID3watermelon3.csv") as f:
df=pd.read_csv(f)
return df
# not fully comprehension how to cleaning df_dataset
# data,expecially cleaning df.data
# import library
from sklearn.naive_bayes import GaussianNB
# assumed have X(predictor) and y(target) for training data
clf=GaussianNB()
clf.fit(X,y)
print(clf.predict([[1,1,1,1,1,1,0.697,0.460]]))
# python test console
import pandas as pd
import numpy as np
with open('/home/dengshuo/GithubCode/ML/CH06/watermelon_3a.csv') as f:
df=pd.read_csv(f,header=None,)
with open('/home/dengshuo/GithubCode/ML/CH06/watermelon_test.csv') as p:
df_test=pd.read_csv(p,header=None,)
#df=df.rename(columns={'编号':'numbers'})
df.columns=['id','density','sugar_index','label']
df_test.columns=['id','density','sugar_index','label']
df.set_index(['id'])
# print(df)
X=df[['density','sugar_index']].values
x_test=df_test[['density','sugar_index']].values
# this is a np.array
y=df[['label']].values
# import scikit learn library
from sklearn.naive_bayes import GaussianNB
gnb=GaussianNB()
gnb.fit(X,y)
predict=gnb.predict(x_test)
print(predict)
predict=[1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 0 0]
数据太少,导致贝叶斯分类器训练的不是很好
重点是学习,这个函数需要什么样的的数据
处理数据的结构 对pandas 处理数据的分析
总结
推导,为什么可以用条件概率来表达 后验概率的值 重要的是公式的推导
对于朴素贝叶斯函数计算的整个流程的掌握
自身还要加强就是 调用函数库时,如何对数据进行处理 将数据表达成 库函数所需要的数据类型