python 中的多处理空间内核密度估计

multiprocessing spatial Kernel Dencity Estimate in python

我正在使用 scipy.stats.kde.gaussian kde 计算空间 KDE。然而,它的评估需要相当多的时间——占我脚本时间的 70%,即 10000 行需要 26 秒。我想让它更快。这是我的原始代码:

from scipy.stats import kde
kernel = kd.gausian_kde(values, bw_method=.05)
result = kernel(positions)

基于Speed up sampling of kernel estimate,我实现了多处理:

SKERNEL = None

# sets global kernel function 
# - multiprocessing requires my function to be top-level module function
setKernel()

def calc_kernel(sample):
    return SKERNEL(sample)

def genKernel(elements):

    cores = mp.cp_count()
    torun = np.array_split(elements, cores, axis=1)

    pool = mp.Pool(processes = cores)
    r = pool.map(calc_kernel, torun)
    return np.concatenate(r)

但是,在同一数据集上,此实现需要 36 秒才能 运行。 使用 cProfiler,我可以看到大部分时间需要 "wait" 个过程。我做错了什么以及如何修改它以更快地工作?

在每个位置评估内核的成本取决于该位置附近值数组的密度。也就是说,将要划分的点拆分为大小相等的数组不会导致这些子问题的评估时间相等;这对于我曾经处理过的每个 KDE 类型的问题都是非常正确的。