朴素贝叶斯P(Y | X)分布建模

时间:2017-04-05 17:44:26

标签: python matrix naivebayes bernoulli-probability probability-distribution

我的任务是编写函数,返回每个类的P(y | x)分布(使用朴素贝叶斯分类器)。结果是N×M矩阵。

输入数据

`p_y` -> a prior probabilities for labels 1 x M  
`p_x_1_y` -> probability distribution P(x = 1|y), matrix M x D  
`X` -> data for which we make distribution, (True of False in each cell) matrix N x D  
`return` -> Probability distribution P(y|x), matrix N x M  

当前代码

我的尝试到目前为止,如果有人可以试用数学逻辑,因为我必须丢失一些东西,因为测试没有通过。

p_y_x_matrix = np.zeros([X.shape[0], len(p_y)])
p_x = np.sum(X, axis=0) / X.shape[0]
for i in range(len(p_y)):
    x_temp = np.zeros(X.shape)
    for j in range(X.shape[0]):
        for k in range(X.shape[1]):
            if X[j, k]:
               x_temp[j, k] += p_x_1_y[i, k]
            elif X[j, k] is not True:
               x_temp[j, k] = (1 - p_x_1_y[i, k])
    x_temp *= p_y[i]
    for j in range(p_x.shape[1]):
        x_temp[:, j] /= p_x[0, j]
        p_y_x_matrix[:, i] = x_temp.sum(axis=1) / x_temp.shape[1]

return p_y_x_matrix

我尽了最大努力,但我的数学逻辑肯定存在一些错误。

0 个答案:

没有答案