gpt4 book ai didi

Python绘制概率分布的百分等高线

转载 作者:太空狗 更新时间:2023-10-30 02:41:58 25 4
gpt4 key购买 nike

给定具有未知函数形式的概率分布(如下示例),我喜欢绘制“基于百分位数”的等高线,即那些对应于积分为 10%、20%、...、90 的区域的等高线%等

## example of an "arbitrary" probability distribution ##
from matplotlib.mlab import bivariate_normal
import matplotlib.pyplot as plt
import numpy as np

X, Y = np.mgrid[-3:3:100j, -3:3:100j]
z1 = bivariate_normal(X, Y, .5, .5, 0., 0.)
z2 = bivariate_normal(X, Y, .4, .4, .5, .5)
z3 = bivariate_normal(X, Y, .6, .2, -1.5, 0.)
z = z1+z2+z3
plt.imshow(np.reshape(z.T, (100,-1)), origin='lower', extent=[-3,3,-3,3])
plt.show()

enter image description here我研究了多种方法,从使用 matplotlib 中的默认轮廓函数,到 scipy 中涉及 stats.gaussian_kde 的方法,甚至可能从分布中生成随机点样本并随后估计内核。他们似乎都没有提供解决方案。

最佳答案

看p(x)在等高线p(x)≥t内的积分,求出想要的t值:

import matplotlib
from matplotlib.mlab import bivariate_normal
import matplotlib.pyplot as plt
import numpy as np

X, Y = np.mgrid[-3:3:100j, -3:3:100j]
z1 = bivariate_normal(X, Y, .5, .5, 0., 0.)
z2 = bivariate_normal(X, Y, .4, .4, .5, .5)
z3 = bivariate_normal(X, Y, .6, .2, -1.5, 0.)
z = z1 + z2 + z3
z = z / z.sum()

n = 1000
t = np.linspace(0, z.max(), n)
integral = ((z >= t[:, None, None]) * z).sum(axis=(1,2))

from scipy import interpolate
f = interpolate.interp1d(integral, t)
t_contours = f(np.array([0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1]))
plt.imshow(z.T, origin='lower', extent=[-3,3,-3,3], cmap="gray")
plt.contour(z.T, t_contours, extent=[-3,3,-3,3])
plt.show()

enter image description here

关于Python绘制概率分布的百分等高线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37890550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com