Python 用n>;1000

Python 用n>;1000,python,numpy,scipy,statistics,sympy,Python,Numpy,Scipy,Statistics,Sympy,在计算贝塔二项式可能性时,我正在努力解决一个数值精度问题。我的目标是估计某个数字d的概率y mod 10=d,假设y是二项式(n,p),p是Beta(a,b)。我正试图找到一个大n的快速解决方案,我的意思是至少1000。有一件事似乎给了我合理的答案,那就是使用模拟 def npliketest_exact(n,digit,a,b): #draw 1000 values of p probs = np.array(beta.rvs(a,b,size=1000)) #cre

在计算贝塔二项式可能性时,我正在努力解决一个数值精度问题。我的目标是估计某个数字d的概率y mod 10=d,假设y是二项式(n,p),p是Beta(a,b)。我正试图找到一个大n的快速解决方案,我的意思是至少1000。有一件事似乎给了我合理的答案,那就是使用模拟

def npliketest_exact(n,digit,a,b):
    #draw 1000 values of p 
    probs = np.array(beta.rvs(a,b,size=1000))
    #create an array of numbers whose last digit is digit 
    digits = np.arange(digit,n+1,10)
    #create a function that calculates the pmf at x given p
    exact_func = lambda x,p: binom(n,p).pmf(x)
    #given p, the likeklihood of last digit "digit" is the sum over all entries in digits
    likelihood = lambda p: exact_func(digits,p).sum()
    #return the average of that likelihood over all the draws
    return np.vectorize(likelihood)(probs).mean()

np.random.seed(1)
print npliketest_exact(1000,9,1,1) #0.0992310195195
这也许可以,但我担心这个策略的准确性。特别是,如果有更好/更精确的方法进行计算,我很想知道如何进行计算

我已经开始尝试使用对数似然来得出这个答案,但即使这样,我也遇到了数值稳定性问题

def llike(n,k,a,b):
    out = gammaln(n+1) + gammaln(k+a) + gammaln(n-k+b) + gammaln(a+b) - \
            ( gammaln(k+1) + gammaln(n-k+1) + gammaln(a) + gammaln(b) + gammaln(n+a+b) )
    return out

 print exp(llike(1000,9,1,1)) #.000999000999001
 print exp(llike(1000,500,1,1)) #.000999000999001
由于β1,1的平均值为0.5,从β二项式(n=1000)得到y=500的概率应该比得到9的概率高得多,但上述计算显示了一个可疑的常量值

我尝试过的另一件事是使用一些聪明的技巧来支持数值稳定性,这显然隐藏在scipy的betaln公式中

def binomln(n, k): #log of the binomial coefficient 
    # Assumes binom(n, k) >= 0
    return -betaln(1 + n - k, 1 + k) - log(n + 1)

def log_betabinom_exact(n,k,a,b):
    return binomln(n,k) + betaln(k+a,n-k+b) - betaln(a,b)

print exp(log_betabinom_exact(1000,9,1,1)) #.000999000999001
print exp(log_betabinom_exact(1000,500,1,1)) #0.000999000999001
同样,同样可疑的常数。如有任何建议,我将不胜感激。在这方面使用sympy会有帮助吗

****后续行动


对不起,伙计们,我犯了一个愚蠢的错误,Beta(1,1)是统一的,所以我得到的结果是有意义的。尝试不同的参数会使k的不同值看起来不同。

gammaln(n+1)-gammaln(betaln(k+a,n-k+b)-beta(a,b))的意思。?对不起,那是垃圾,让我编辑一下好吧,我刚开始查找。如果你发现了什么,给我打个电话。。。