scipy.stats.gaussian_kdestatsmodels.nonparametric.kde
の代わりにモジュールを使用すると、速度が大幅に向上する可能性があることを読みました。
現在計算している単純なコード ブロック (4 行のコード) があり、実際に速度が向上するかどうかを確認するscipy.stats.gaussian_kde
ために、それらを同等のものに置き換えたいと考えています。statsmodels
これは MWE です。
import numpy as np
from scipy import stats
# Generate random two-dimensional data.
def measure(n):
m1 = np.random.normal(size=n)
m2 = np.random.normal(scale=0.5, size=n)
return m1+m2, m1-m2
m1, m2 = measure(20000)
# Define data limits.
xmin, xmax = m1.min(), m1.max()
ymin, ymax = m2.min(), m2.max()
# Format data correctly.
values = np.vstack([m1, m2])
# Define a certain point value.
x1, y1 = 0.5, 0.5
##############
# Replace with calls to statsmodels.nonparametric.kde from here on.
# 1- Perform a kernel density estimate on the data.
kernel = stats.gaussian_kde(values)
# 2- Get kernel value for the point.
iso = kernel((x1,y1))
# 3- Take a random sample from KDE distribution.
sample = kernel.resample(size=1000)
# 4- Filter the sample to keep only values for which
# the kernel evaluates to less than what it does in the
# point (x1,y1). This is the most important step to be replaced.
insample = kernel(sample) < iso
ご覧のとおり、置き換える必要があるのはわずか 4 行のコードです。残念ながら、 のドキュメントstatsmodels.nonparametric.kde
はやや貧弱で、そのような置換を行う方法がわかりません。
最後の行は、ほとんどの計算時間がここで費やされるため、最も重要な行です (ここで説明されているように、カーネル推定のサンプリングを高速化します)。