python - 在Python中返回给定x和y的二维PDF的值?

标签 python pdf indexing histogram

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

enter image description here

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))

结果:

result of interpolation

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

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/

相关文章:

python - 如何在odoo中通过many2one字段设置默认值?

python - BTS 正在抓取带有 utf8 错误的文本,但在原始网页上看起来不错

python - kwargs/args 错误。将参数传递给 apscheduler 处理函数

c# - 等效于 FileOutputStream

"not equal"搜索的 SQL 索引

oracle - Hive 查询语言中的主键和索引是否可行?

python - 如何在Python动画函数中返回未知数量的对象

c# - 不使用第 3 方工具从头开始开发 Word 到 PDF 转换器

iphone - 在照片库中保存 pdf

Python Pandas 索引位置的值