这是我为了更好地理解 pymc3 而进行的一个实验。我有三个有偏见的硬币,我进行了以下实验:
1. Toss Coin1. If head choose Coin2 else choose Coin3
2. Randomly choose a number n (between 1 and 10) that implies coin tosses to perform
3. Toss Coin2/3 (as per 1. above) n times and observe number of heads.
4. Perform 1,2,3 above multiple times
问题是从上面的实验中给出的数据,我们可以对这三个硬币进行建模吗?
代码:数据生成器:
coin1 = 0.4
coin2 = 0.9
coin3 = 0.1
numberOfDataPoints = 20000
maxTosses = 10
percentOfmaxTosses = 0.65
headTosses = []
totalTosses = []
for i in range(numberOfDataPoints):
heads = 0
total = 0
isCoint2 = random() < coin1
for rater in range(maxTosses):
if random() <= percentOfmaxTosses:
total = total + 1
if isCoint2:
if random() < coin2:
heads += 1
else:
if random() < coin3:
heads += 1
if total > 5:
headTosses.append(heads)
totalTosses.append(total)
型号代码:
with pm.Model() as coins:
coin1 = pm.Beta('coin1',2,2)
coin2 = pm.Beta('coin2',5,2)
coin3 = pm.Beta('coin3',2,5)
first_toss = pm.Bernoulli('first_toss', coin1)
p = pm.math.switch(first_toss > 0.5, coin2, coin3)
output = pm.Binomial('output', n=totalTosses, p=p,observed=headTosses)
exp = pm.sample(10000, tune = 5000)
结果:
- 发现coin1的模型很好
- coin2 似乎接近原始值
- coin3 很遥远
疑点:
- 上面的实验有什么问题吗?
- 有没有更好的方法来模拟这个实验?