Return 在 Python 中给定 x 和 y 的二维 PDF 的值?

Return the value of a 2D PDF given x and y in Python?

我有一些数据是我使用 matplotlib 的 hist2D 函数绘制的 PDF。 结果如下所示:

hist2d 函数returns 数组的三元组:H、xedges、yedges。 H是二维直方图值。 现在我想将这个离散的 H 矩阵转换成一个函数,即 returns 任何给定 (x,y) 输入的 H 值。 换句话说,我想将我的 2D 直方图变成 2D 阶跃函数。是否有我可以用于该目的的计算成本低的特定函数?

这看起来是一个非常简单的操作(通常用于图像处理,但使用像素索引而不是实数)但我找不到任何相关信息,你能帮我吗?

您可以从这样的计数构建一个插值器:

from numpy import random, histogram2d, diff
import matplotlib.pyplot as plt
from scipy.interpolate import interp2d

# Generate sample data
n = 10000
x = random.randn(n)
y = -x + random.randn(n)

# bin
nbins = 100
H, xedges, yedges = histogram2d(x, y, bins=nbins)

# Figure out centers of bins
def centers(edges):
    return edges[:-1] + diff(edges[:2])/2

xcenters = centers(xedges)
ycenters = centers(yedges)

# Construct interpolator
pdf = interp2d(xcenters, ycenters, H)

# test
plt.pcolor(xedges, yedges, pdf(xedges, yedges))

结果:

请注意,这将是线性插值而不是 step-wise。对于采用规则网格的更快版本,这也适用:

from numpy import meshgrid, vectorize

def position(edges, value):
    return int((value - edges[0])/diff(edges[:2]))

@vectorize
def pdf2(x, y):
    return H[position(yedges, y), position(xedges, x)]

# test - note we need the meshgrid here to get the right shapes
xx, yy = meshgrid(xcenters, ycenters)
plt.pcolor(xedges, yedges, pdf2(xx, yy))