【问题标题】:Scipy: Speed up kernel density estimation's score_sample method?Scipy:加快核密度估计的 score_sample 方法?
【发布时间】:2015-12-12 23:28:43
【问题描述】:

我正在尝试使用核密度估计来获得观察到的概率密度。这就是我使用 kde 的方式:

from sklearn.neighbors import KernelDensity
kde = KernelDensity().fit(sample)

问题是,当我尝试获取每个点的概率密度时

kde_result = kde.score_samples(sample)

速度很慢。如何加快速度?

样本由300,000 (x,y) 个点组成。

【问题讨论】:

  • 为什么要获取每个点的密度?
  • 您可以尝试使用atol 和/或rtol 的非默认值初始化KernelDensity()
  • @cel,我正在使用一种方法来创建predict model,它需要计算probabiltiy density functionmean square error。所以我用kde估计observed pdf,然后做(predict - observed)**2
  • @Chris,init(创建kde)速度还可以。麻烦的是查询大数据集时的score_sample方法。
  • 所以你的预测模型也输出一个 pdf 文件?我在理解 calculate the mean square error of a probability density function 时遇到问题 - 从数学上讲,这听起来有些错误。

标签: python statistics scipy scikit-learn


【解决方案1】:

万一有人正在寻找这个问题的答案,它已解决here。那里描述了您可以通过使用multiprocessing 并行计算来轻松加快执行速度。

这段代码可以完成这项工作(也来自同一个answer):

import numpy as np
import multiprocessing
from sklearn.neighbors import KernelDensity

def parrallel_score_samples(kde, samples, thread_count=int(0.875 * multiprocessing.cpu_count())):
    with multiprocessing.Pool(thread_count) as p:
        return np.concatenate(p.map(kde.score_samples, np.array_split(samples, thread_count)))

kde = KernelDensity(bandwidth=2.0,atol=0.0005,rtol=0.01).fit(sample) 
kde_result = parrallel_score_samples(kde, sample)

【讨论】:

  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
  • 我刚刚编辑了答案
猜你喜欢
  • 2016-06-06
  • 1970-01-01
  • 2017-09-05
  • 2021-12-16
  • 2017-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-18
相关资源
最近更新 更多