问题
How do I simulate a 6-side Dice roll using Pymc3? Also, what is I know that different sides of the dice have different distributions?
回答1:
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!
回答2:
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)
来源:https://stackoverflow.com/questions/46454814/how-to-simulate-a-biased-6-sided-dice-using-pymc3