Let’s flip a coin in Python

Foundations of Probability in Python

Alexander A. Ramírez M.

CEO @ Synergy Vision

Probability

  • Foundation of Data Science
  • Allows to produce data from models
  • Study regularities in random phenomena
Foundations of Probability in Python

Gain intuition

...with coin flips

Coin flip

Foundations of Probability in Python

Only two outcomes

Heads or Tails

One cent head and tail

Foundations of Probability in Python

Flipping a coin in Python

Bernoulli random experiment

from scipy.stats import bernoulli
bernoulli.rvs(p=0.5, size=1)
array([0])

Another draw

bernoulli.rvs(p=0.5, size=1)
array([1])
Foundations of Probability in Python

Flipping multiple coins

Change size parameter to flip more...

bernoulli.rvs(p=0.5, size=10)
array([0, 0, 0, 0, 0, 0, 1, 1, 0, 0])

How many heads?

sum(bernoulli.rvs(p=0.5, size=10))
5
Foundations of Probability in Python

Flipping multiple coins (Cont.)

Another draw...

sum(bernoulli.rvs(p=0.5, size=10))
2
Foundations of Probability in Python

Flipping multiple coins (Cont.)

Binomial random variable

from scipy.stats import binom
binom.rvs(n=10, p=0.5, size=1)
array([7])

Many draws

binom.rvs(n=10, p=0.5, size=10)
array([6, 2, 3, 5, 5, 5, 5, 4, 6, 6])
Foundations of Probability in Python

Flipping multiple coins (Cont.)

Biased coin draws

binom.rvs(n=10, p=0.3, size=10)
array([3, 4, 3, 3, 2, 2, 2, 2, 3, 6])
Foundations of Probability in Python

Random generator seed

  • Use the random_state parameter of the rvs() function
from scipy.stats import binom
binom.rvs(n=10, p=0.5, size=1, random_state=42)
  • Use numpy.random.seed()
import numpy as np
np.random.seed(42)
Foundations of Probability in Python

Random generator seed (Cont.)

Flipping 10 fair coins with a random seed

from scipy.stats import binom
import numpy as np

np.random.seed(42)
binom.rvs(n=10, p=0.5, size=1)
array([4])
Foundations of Probability in Python

Let's practice flipping coins in Python

Foundations of Probability in Python

Preparing Video For Download...