β二项式分布和β分布的α和β估计



我正在尝试将我的数据拟合为β二项式分布,并估计α和β形状参数。对于这个分布,先验是从贝塔分布中获取的。Python没有适用于beta二项式的拟合函数,但它适用于beta。pythonβ-拟合和Rβ-二项式拟合很接近,但系统性地偏离

R:

library("VGAM")
x = c(222,909,918,814,970,346,746,419,610,737,201,865,573,188,450,229,629,708,250,508)
y = c(2,18,45,11,41,38,22,7,40,24,34,21,49,35,31,44,20,28,39,17)
fit=vglm(cbind(y, x) ~ 1, betabinomialff, trace = TRUE)
Coef(fit)
   shape1    shape2 
  1.736093 26.870768

python:

import scipy.stats
import numpy as np
x = np.array([222,909,918,814,970,346,746,419,610,737,201,865,573,188,450,229,629,708,250,508], dtype=float)
y = np.array([2,18,45,11,41,38,22,7,40,24,34,21,49,35,31,44,20,28,39,17])
scipy.stats.beta.fit((y)/(x+y), floc=0, fscale=1)
    (1.5806623978910086, 24.031893492546242, 0, 1)

我已经做了很多次了,看起来python系统地比R结果低一点。我想知道这是我的输入错误,还是只是计算方式的差异?

您的问题是,拟合贝塔二项式模型与拟合值等于比率的贝塔模型不同。我将在这里用bbmle包进行说明,它将适用于与VGAM类似的模型(但我更熟悉它)。

准备工作:

library("VGAM")  ## for dbetabinom.ab
x <- c(222,909,918,814,970,346,746,419,610,737,
       201,865,573,188,450,229,629,708,250,508)
y <- c(2,18,45,11,41,38,22,7,40,24,34,21,49,35,31,44,20,28,39,17)
library("bbmle")

拟合贝塔二项式模型:

mle2(y~dbetabinom.ab(size=x+y,shape1,shape2),
     data=data.frame(x,y),
     start=list(shape1=2,shape2=30))
## Coefficients:
##    shape1    shape2 
##  1.736046 26.871526 

这或多或少与您引用的VGAM结果完全一致。

现在使用相同的框架来适应Beta模型:

mle2(y/(x+y) ~ dbeta(shape1,shape2),
     data=data.frame(x,y),
     start=list(shape1=2,shape2=30))
## Coefficients:
##    shape1    shape2 
## 1.582021 24.060570 

这适合您的Python测试版结果。(我敢肯定,如果你使用VGAM来适应Beta,你也会得到同样的答案。)

您可以将conjugate_prior包用于python

请参阅硬币翻转示例的代码:

from conjugate_prior import BetaBinomial
heads = 95
tails = 105
prior_model = BetaBinomial() #Uninformative prior
updated_model = prior_model.update(heads, tails)
credible_interval = updated_model.posterior(0.45, 0.55)
print ("There's {p:.2f}% chance that the coin is fair".format(p=credible_interval*100))
predictive = updated_model.predict(50, 50)
print ("The chance of flipping 50 Heads and 50 Tails in 100 trials is {p:.2f}%".format(p=predictive*100))

代码取自此处

相关内容

  • 没有找到相关文章

最新更新