How to Simulate a Biased 6-sided Dice using Pymc3?

大憨熊 提交于 2019-12-06 07:49:21

The easiest way to simulate 1000 rolls of a fair 6-sided die in PyMC3 is

import pymc3 as pm

with pm.Model():
    rolls = pm.DiscreteUniform('rolls', lower=1, upper=6)
    trace = pm.sample(1000)
trace['rolls']  # shows you the result of 1000 rolls

Note that this is slower, but equivalent, to just calling np.random.randint(1, 7, size=1000).

For 1000 rolls of an unfair die

probs = np.array([0.1, 0.2, 0.3, 0.2, 0.1, 0.1])

with pm.Model():
    rolls = pm.Multinomial('rolls', n=1000, p=probs, shape=6)
    trace = pm.sample(1)

Which is again equivalent, but slower, than np.random.multinomial(1000, pval=probs).

The situtation in which you would want to use PyMC3 is if you observe, say, 50 rolls of an unfair die, have some prior expectation that it is a fair die, and want to evaluate the posterior of that expectation. Here's an example of that:

observations = np.array([20, 6, 6, 6, 6, 6])
with pm.Model():
    probs = pm.Dirichlet('probs', a=np.ones(6))  # flat prior
    rolls = pm.Multinomial('rolls', n=50, p=probs, observed=observations)
    trace = pm.sample(1000)
trace['probs']  # posterior samples of how fair the die are

You can use the built-in traceplot to see how the samples look:

Note that we correctly work out that one of the sides comes up more often than the others!

You can use the random module to generate pseudo-random numbers. Below is my working example.

import random

def roll_dice(num_sides=6):
    return random.randint(0,num_sides-1) + 1

if __name__ == '__main__':

    result = roll_dice(num_sides=2)
    print(result)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!