我有一些使用 matplotlib 的 hist2D 函数绘制 PDF 的数据。 结果如下所示:
hist2d 函数返回三个数组:H、xedges、yedges。 H 是二维直方图值。 现在我想将这个离散 H 矩阵转换为一个函数,该函数返回任何给定 (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))
结果:
请注意,这将是线性插值而不是逐步插值。对于采用常规网格的更快版本,这也适用:
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))
关于python - 在Python中返回给定x和y的二维PDF的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31430390/