ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python – 在等高线内集成2D核密度估计

2019-07-06 01:59:25  阅读:243  来源: 互联网

标签:python kde contour


我想绘制核密度估计的等高线图,其中KDE集成在每个等高线图填充区域内.

举个例子,假设我计算了2D数据的KDE:

data = np.random.multivariate_normal((0, 0), [[1, 1], [2, 0.7]], 100)
x = data[:, 0]
y = data[:, 1]
xmin, xmax = min(x), max(x)
ymin, ymax = min(y), max(y)
xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
positions = np.vstack([xx.ravel(), yy.ravel()])
values = np.vstack([x, y])
kernel = st.gaussian_kde(values)
f = np.reshape(kernel(positions).T, xx.shape)

我知道如何绘制KDE的等高线图.

fig = plt.figure()
ax = fig.gca()
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
cfset = ax.contourf(xx, yy, f, cmap='Blues')
cset = ax.contour(xx, yy, f, colors='k')
plt.show()

但是,此等值线图显示了每个填充区域内的概率密度.相反,我希望该图表示每个填充区域内的总概率.

解决方法:

请注意,只有您的轮廓是“单调的”时,以下内容才是正确的,即在轮廓线内,您只能找到高于相应轮廓等级的像素值.另请注意,如果您的密度是多峰的,则将单独峰中的相应区域集中在一起.

如果这是真的/可接受的,则可以通过按值排序像素来解决问题.

我不知道您的绘图程序选择其轮廓级别的哪种启发式方法,但假设您将它们(按升序排列,比如说)存储在一个名为“级别”的变量中,您可以尝试类似

ff = f.ravel()
order = np.argsort(ff)
fsorted = ff[order]
F = np.cumsum(fsorted)
# depending on how your density is normalised next line may be superfluous
# also note that this is only correct for equal bins
# and, finally, to be unimpeachably rigorous, this disregards the probability
# mass outside the field of view, so it calculates probability condtional
# on being in the field of view
F /= F[-1]
boundaries = fsorted.searchsorted(levels)
new_levels = F[boundaries]

现在,为了能够使用它,您的绘图程序必须允许您自由选择轮廓标签或至少选择放置轮廓的级别.在后一种情况下,假设有一个kwarg’级别’

# make a copy to avoid problems with in-place shuffling
# i.e. overwriting positions whose original values are still to be read out
F[order] = F.copy()
F.shape = f.shape
cset = ax.contour(xx, yy, F, levels=new_levels, colors='k')

我已经从您的一条评论中复制了以下内容,以使其更加清晰可见

Finally, if one wants to really have the probability within each filled area, this is a workaround that works: cb = fig.colorbar(cfset, ax = ax) values = cb.values.copy() values[1:] -= values[:-1].copy() cb.set_ticklabels(values) – Laura

标签:python,kde,contour
来源: https://codeday.me/bug/20190706/1392665.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有