整合2D核密度估计

Gab*_*iel 6 python integration kernel-density probability-density

我有一个x,y点的分布,我KDE通过scipy.stats.gaussian_kde得到了.这是我的代码以及输出的外观(x,y数据可以从这里获得):

import numpy as np
from scipy import stats

# Obtain data from file.
data = np.loadtxt('data.dat', unpack=True)
m1, m2 = data[0], data[1]
xmin, xmax = min(m1), max(m1)
ymin, ymax = min(m2), max(m2)

# Perform a kernel density estimate (KDE) on the data
x, y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
positions = np.vstack([x.ravel(), y.ravel()])
values = np.vstack([m1, m2])
kernel = stats.gaussian_kde(values)
f = np.reshape(kernel(positions).T, x.shape)

# Define the number that will determine the integration limits
x1, y1 = 2.5, 1.5

# Perform integration?

# Plot the results:
import matplotlib.pyplot as plt
# Set limits
plt.xlim(xmin,xmax)
plt.ylim(ymin,ymax)
# KDE density plot
plt.imshow(np.rot90(f), cmap=plt.cm.gist_earth_r, extent=[xmin, xmax, ymin, ymax])
# Draw contour lines
cset = plt.contour(x,y,f)
plt.clabel(cset, inline=1, fontsize=10)
plt.colorbar()
# Plot point
plt.scatter(x1, y1, c='r', s=35)
plt.show()
Run Code Online (Sandbox Code Playgroud)

结果

带坐标的红点(x1, y1)(与2D图中的每个点一样)由f(内核或KDE)在0和0.42之间给出的相关值.我们这样说吧f(x1, y1) = 0.08.

我需要整合f与集成的限制x,并y通过其中这些区域给出f的计算结果为f(x1, y1),即:f(x, y)<0.08.

对于我所看到的python可以通过数值积分执行函数和一维数组的集成,但我还没有看到任何可以让我在2D数组(f内核)上执行数值积分的事情.此外,我不知道如何我甚至会认识到该特定条件给出的区域(即:f(x, y)小于给定值)

这可以完成吗?

jcr*_*udy 6

这是使用蒙特卡罗集成的方法.它有点慢,并且解决方案中存在随机性.误差与样本大小的平方根成反比,而运行时间与样本大小成正比(样本大小是指monte carlo样本(在我的示例中为10000),而不是数据集的大小).这是一些使用您的kernel对象的简单代码.

#Compute the point below which to integrate
iso = kernel((x1,y1))

#Sample from your KDE distribution
sample = kernel.resample(size=10000)

#Filter the sample
insample = kernel(sample) < iso

#The integral you want is equivalent to the probability of drawing a point 
#that gets through the filter
integral = insample.sum() / float(insample.shape[0])
print integral
Run Code Online (Sandbox Code Playgroud)

我得到大约0.2作为您的数据集的答案.