我需要计算两个函数重叠的面积。在这个特殊的简化示例中,我使用正态分布,但我需要一个更通用的过程,它也适用于其他函数。在
请参见下图,了解我的意思,红色区域是我要追求的:
这是我目前掌握的MWE:import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
# Generate random data uniformly distributed.
a = np.random.normal(1., 0.1, 1000)
b = np.random.normal(1., 0.1, 1000)
# Obtain KDE estimates foe each set of data.
xmin, xmax = -1., 2.
x_pts = np.mgrid[xmin:xmax:1000j]
# Kernels.
ker_a = stats.gaussian_kde(a)
ker_b = stats.gaussian_kde(b)
# KDEs for plotting.
kde_a = np.reshape(ker_a(x_pts).T, x_pts.shape)
kde_b = np.reshape(ker_b(x_pts).T, x_pts.shape)
# Random sample from a KDE distribution.
sample = ker_a.resample(size=1000)
# Compute the points below which to integrate.
iso = ker_b(sample)
# Filter the sample.
insample = ker_a(sample) < iso
# As per Monte Carlo, the integral is equivalent to the
# probability of drawing a point that gets through the
# filter.
integral = insample.sum() / float(insample.shape[0])
print integral
plt.xlim(0.4,1.9)
plt.plot(x_pts, kde_a)
plt.plot(x_pts, kde_b)
plt.show()
这里我应用Monte Carlo来得到积分。在
这种方法的问题是,当我用ker_b(sample)(或ker_a(sample))计算任一分布中的采样点时,我得到的值直接放在KDE线的上。因此,即使是明显重叠的分布,也应返回非常接近1的公共/重叠面积值。返回较小的值(任一曲线的总面积为1。因为它们是概率密度估计)。在
如何修复此代码以获得预期结果?在
这就是我如何应用珍雅的答案
^{pr2}$