def probability(A,a):
n=A.shape[0]
nm = np.cumproduct(np.array(A.shape))[0]
return (A==a).T.dot(np.ones(n))/n
def set_conditions(data,*conditions):
PAVector = [probability(data,conditions[i])[i] for i in range(len(conditions))]
return np.array(PAVector)
‘
def bayes(data,*conditions,**cond):
'''
data 输入数据矩阵
*conditions 输入条件列
**cond 输入判定条件
返回贝叶斯推断概率
'''
m,n = data.shape
conditions_lenght = len(conditions)
ybool = data[:,-1]==cond['cond']
result = 0
for i in range((conditions_lenght)):
tmp = ((data[:,i]==conditions[i])&ybool)[ybool].sum()/m
result+=tmp
return result
def naive_bayes(data,*conditions,**conds):
'''
data 输入数据矩阵
*conditions 输入条件列
**cond 输入判定条件
返回:分类结果 ,贝叶斯推断概率向量
'''
conds = np.array(conds['conds'])
expr = np.array([bayes(data,*conditions,cond=cond) for cond in conds])
return conds[expr==expr.max()][0],expr
朴素贝叶斯分类
最新推荐文章于 2021-02-07 13:57:31 发布