估计python

时间:2016-02-14 16:55:01

标签: python numpy statistics distribution montecarlo

我有两个随机变量X和Y,它们均匀分布在单纯形:simplex

我想评估其总和的密度:

enter image description here

在评估上述积分后,我的最终目标是计算以下积分: enter image description here

为了计算第一个积分,我在单纯形中生成均匀分布的点,然后检查它们是否属于上述积分中的所需区域,并采用点的分数来评估上述密度。

一旦我计算出上述密度,我就按照类似的程序计算上面的对数积分来计算它的值。然而,这是非常低效的,并花了很多时间这样3-4个小时。任何人都可以建议我在Python中解决这个问题的有效方法吗?我正在使用Numpy包。

这是代码

import numpy as np
import math
import random
import numpy.random as nprnd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
#This function checks if the point x lies the simplex and the negative simplex shifted by z
def InreqSumSimplex(x,z):
    dim=len(x)
    testShiftSimpl= all(z[i]-1 <= x[i] <= z[i] for i in range(0,dim)) and (sum(x) >= sum(z)-1)
    return int(testShiftSimpl)

def InreqDiffSimplex(x,z):
    dim=len(x)
    testShiftSimpl= all(z[i] <= x[i] <= z[i]+1 for i in range(0,dim)) and (sum(x) <= sum(z)+1)
    return int(testShiftSimpl)
#This is for the density X+Y
def DensityEvalSum(z,UniformCube):
    dim=len(z)
    Sum=0
    for gen in UniformCube:
        Exponential=[-math.log(i) for i in gen] #This is exponentially distributed
        x=[i/sum(Exponential) for i in Exponential[0:dim]] #x is now uniformly distributed on simplex

        Sum+=InreqSumSimplex(x,z)

    Sum=Sum/numsample

    FunVal=(math.factorial(dim))*Sum;
    if FunVal<0.00001:
        return 0.0
    else:
        return -math.log(FunVal)
#This is for the density X-Y
def DensityEvalDiff(z,UniformCube):
    dim=len(z)
    Sum=0
    for gen in UniformCube:
        Exponential=[-math.log(i) for i in gen]
        x=[i/sum(Exponential) for i in Exponential[0:dim]]

    Sum+=InreqDiffSimplex(x,z)

    Sum=Sum/numsample

    FunVal=(math.factorial(dim))*Sum;
    if FunVal<0.00001:
        return 0.0
    else:
        return -math.log(FunVal)
def EntropyRatio(dim):    
    UniformCube1=np.random.random((numsample,dim+1)); 
    UniformCube2=np.random.random((numsample,dim+1))

    IntegralSum=0; IntegralDiff=0

    for gen1,gen2 in zip(UniformCube1,UniformCube2):

        Expo1=[-math.log(i) for i in gen1];        Expo2=[-math.log(i) for i in gen2]

        Sumz=[ (i/sum(Expo1)) + j/sum(Expo2) for i,j in zip(Expo1[0:dim],Expo2[0:dim])] #Sumz is now disbtributed as X+Y

        Diffz=[ (i/sum(Expo1)) - j/sum(Expo2) for i,j in zip(Expo1[0:dim],Expo2[0:dim])] #Diffz is now distributed as X-Y

    UniformCube=np.random.random((numsample,dim+1))

    IntegralSum+=DensityEvalSum(Sumz,UniformCube) ; IntegralDiff+=DensityEvalDiff(Diffz,UniformCube)

    IntegralSum= IntegralSum/numsample; IntegralDiff=IntegralDiff/numsample

    return ( (IntegralDiff +math.log(math.factorial(dim)))/ ((IntegralSum +math.log(math.factorial(dim)))) )

Maxdim=11
dimlist=range(2,Maxdim)
Ratio=len(dimlist)*[0]
numsample=10000

for i in range(len(dimlist)):
    Ratio[i]=EntropyRatio(dimlist[i])

1 个答案:

答案 0 :(得分:1)

不确定这是您问题的答案,但让我们开始

首先,这里有一些代码示例和讨论如何正确地从Dirichlet(n)(也就是单纯形式),通过gammavariate()或通过-log(U)进行采样,但是对于潜在的角落情况有适当的处理,link

我可以看到您的代码问题,例如,对于dimension = 2 simplex的采样 你得到三个(!)统一号码,但在对x进行列表理解时跳过一个。这是错的。要对n维Dirichlet进行采样,您应该得到n U(0,1)并然后转换(或n来自gammavariate的样本。)

但是,最佳解决方案可能只是使用numpy.random.dirichlet(),它是用C编写的,可能是最快的,请参阅link

最后一个,根据我的拙见,你没有正确估算log(PDF(X+Z))。好的,你发现有些是,但此时PDF(X+Z)是什么?

这是

吗?
testShiftSimpl= all(z[i]-1 <= x[i] <= z[i] for i in range(0,dim)) and (sum(x) >= sum(z)-1)
return int(testShiftSimpl)

看起来像PDF?你是怎么设法得到它的?

简单测试:将PDF(X+Z)整合到整个X+Z区域。它产生了1吗?

更新

看起来我们可能会有不同的想法,我们称之为simplex,Dirichlet等。我几乎与this definition一起,在d昏暗的空间中我们有d个点和d-1单形是连接顶点的凸包。单面维度始终如一 由于坐标之间的关系,比空间少一个。在最简单的情况下,d = 2,1-simplex是连接点(1,0)和(0,1)的一个段,而从Dirichlet分布我得到了图片

enter image description here

d = 3和2-simplex的情况下,我们有三角形连接点(1,0,0),(0,1,0)和(0,0,1)

enter image description here

Code,Python

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

import math
import random

def simplex_sampling(d):
    """
    Sample one d-dim point from Dirichet distribution
    """
    r = []
    sum = 0.0

    for k in range(0, d):
        x = random.random()
        if x == 0.0:
            return make_corner_sample(d, k)

        t = -math.log(x)
        r.append(t)
        sum += t

    norm = 1.0 / sum

    for k in range(0, d):
        r[k] *= norm

    return r

def make_corner_sample(d, k):
    """
    U(0,1) number k is zero, it is a corner point in simplex
    """
    r = []
    for i in range(0, d):
        if i == k:
            r.append(1.0)
        else:
            r.append(0.0)

    return r

N = 500 # numer of points to plot
d = 3   # dimension of the space, 2 or 3

x = []
y = []
z = []

for k in range(0, N):
    pt = simplex_sampling(d)

    x.append(pt[0])
    y.append(pt[1])
    if d > 2:
        z.append(pt[2])

if d == 2:
    plt.scatter(x, y, alpha=0.1)
else:
    fig = plt.figure()
    ax  = fig.add_subplot(111, projection='3d')
    ax.scatter(x, y, z, alpha=0.1)

    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')
    ax.set_zlabel('Z Label')

plt.show()