编程语言
首页 > 编程语言> > Python绘制概率分布的百分比轮廓线

Python绘制概率分布的百分比轮廓线

作者:互联网

给定具有未知函数形式的概率分布(下面的示例),我喜欢绘制“基于百分位数”的轮廓线,即那些对应于积分为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)≥t内的p(x)的积分,求出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

标签:contour,kernel-density,matplotlib,probability,python
来源: https://codeday.me/bug/20191026/1940467.html