朴素贝叶斯分类中特征值的快速计数

2024-05-16 20:26:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python实现一个naivebayes分类器(作为大学作业的一部分,因此Python是一个需求)。我让它工作,它产生的结果与sklearn.naive_bayes.MultinomialNB差不多。但是,与sklearn实现相比,它确实很慢。你知道吗

假设特征值是0到max\i范围内的整数,类标签也是0到max\y范围内的整数。示例数据集如下所示:

>>> X = np.array([2,1 1,2 2,2 0,2]).reshape(4,2) # design matrix
>>> print(X)
[[2 1]
 [1 2]
 [2 2]
 [0 2]]
>>> y = np.array([0,  1,  2,  0  ]) # class labels
>>> print(y)
[0 1 2 0]

现在,作为处理联合对数似然之前的中间步骤,我需要计算类条件似然(即P(x_ij | y),使得矩阵ccl包含给定类c的特征j中的值k的概率。对于上述示例,这样的矩阵的输出将是:

>>> print(ccl)
[[[0.5 0.  0.5]
  [0.  0.5 0.5]]

 [[0.  1.  0. ]
  [0.  0.  1. ]]

 [[0.  0.  1. ]
  [0.  0.  1. ]]]
>>> print(ccl[0][1][1]) # prob. of value 1 in feature 1 given class 0
0.5

我实现的代码如下所示:

N, D = X.shape
K = np.max(X)+1
C = np.max(y)+1
ccl = np.zeros((C,D,K))
# ccl = ccl + alpha - 1 # disregard the dirichlet prior for this question
# Count occurences of feature values given class c
for i in range(N):
    for d in range(D):
        ccl[y[i]][d][X[i][d]] += 1
# Renormalize so it becomes a probability distribution again
for c in range(C):
    for d in range(D):
        cls[c][d] = np.divide(cls[c][d], np.sum(cls[c][d]))

因此,由于Python循环很慢,这也变得很慢。 我试图通过对每个特征值进行一次热编码来缓解这个问题(因此,如果特征值在[0,1,2]范围内,则2变为:[0,0,1],以此类推)。虽然,我认为调用了太多的np函数,所以计算时间仍然太长:

ccl = np.zeros((C,D,K))
for c in range(C):
    x = np.eye(K)[X[np.where(y==c)]] # one hot encoding
    ccl[c] += np.sum(x, axis=0) # summing up
    ccl[c] /= ccl[c].sum(axis=1)[:, numpy.newaxis] # renormalization

这将产生与上述相同的输出。有什么关于如何加快速度的提示吗?我认为np.eye(一个热编码)是不必要的,并杀死它,但我想不出一个方法来摆脱它。我考虑过的最后一件事是使用np.unique()collections.Counter进行计数,但还没有弄清楚。你知道吗


Tags: in示例fornprange整数sklearnarray
1条回答
网友
1楼 · 发布于 2024-05-16 20:26:18

所以这是一个非常巧妙的问题(我有一个similar problem not that long ago)。处理这个问题的最快方法通常是使用算术运算构造一个索引数组,然后用np.bincount对其进行堆积和整形。你知道吗

N, D = X.shape
K = np.max(X) + 1
C = np.max(y) + 1
ccl = np.tile(y, D) * D * K + (X +  np.tile(K * range(D), (N,1))).T.flatten()
ccl = np.bincount(ccl, minlength=C*D*K).reshape(C, D, K)
ccl = np.divide(ccl, np.sum(ccl, axis=2)[:, :, np.newaxis])

>>> ccl
array([[[0.5, 0. , 0.5],
        [0. , 0.5, 0.5]],

       [[0. , 1. , 0. ],
        [0. , 0. , 1. ]],

       [[0. , 0. , 1. ],
        [0. , 0. , 1. ]]])

作为速度比较,funca是第一个基于循环的方法,funcb是第二个基于numpy函数的方法,funcc是使用bincount的方法。你知道吗

X = np.random.randint(3, size=(10000,2))
y = np.random.randint(3, size=(10000))
>>> timeit.timeit('funca(X,y)', number=100, setup="from __main__ import funca, X, y")
2.632569645998956
>>> timeit.timeit('funcb(X,y)', number=100, setup="from __main__ import funcb, X, y")
0.10547748399949342
>>> timeit.timeit('funcc(X,y)', number=100, setup="from __main__ import funcc, X, y")
0.03524605900020106

也许可以进一步完善这一点,但我没有更多的好主意。你知道吗

相关问题 更多 >