Génération de nombres pseudo-aléatoires

L’échantillonnage en Python

James Chapman

Curriculum Manager, DataCamp

Que signifie « aléatoire » ?

adjectif fait, effectué, survenant ou choisi sans méthode ni décision consciente.

1 Oxford Languages
L’échantillonnage en Python

Vrais nombres aléatoires

  • Générés par des processus physiques, comme lancer une pièce
  • Hotbits utilise la désintégration radioactive
  • RANDOM.ORG utilise le bruit atmosphérique
  • Le vrai hasard est coûteux
1 https://www.fourmilab.ch/hotbits 2 https://www.random.org
L’échantillonnage en Python

Génération pseudo-aléatoire

  • La génération pseudo-aléatoire est économique et rapide
  • Le prochain « nombre aléatoire » est calculé à partir du précédent
  • Le premier « nombre aléatoire » est calculé depuis une graine
  • La même graine produit les mêmes nombres
L’échantillonnage en Python

Exemple de génération pseudo-aléatoire

seed = 1
calc_next_random(seed)
3
calc_next_random(3)
2
calc_next_random(2)
6
L’échantillonnage en Python

Fonctions de génération aléatoire

  • Préfixer par numpy.random, par ex. numpy.random.beta()
function distribution function distribution
.beta Bêta .hypergeometric Hypergéométrique
.binomial Binomiale .lognormal Log-normale
.chisquare Khi-deux .negative_binomial Binomiale négative
.exponential Exponentielle .normal Normale
.f F .poisson Poisson
.gamma Gamma .standard_t t
.geometric Géométrique .uniform Uniforme
L’échantillonnage en Python

Visualiser des nombres aléatoires

randoms = np.random.beta(a=2, b=2, size=5000)
randoms
array([0.6208281 , 0.73216171, 0.44298403, ..., 
       0.13411873, 0.52198411, 0.72355098])
plt.hist(randoms, bins=np.arange(0, 1, 0.05))
plt.show()

hist-beta.png

L’échantillonnage en Python

Graine (seed) des nombres aléatoires

np.random.seed(20000229)
np.random.normal(loc=2, scale=1.5, size=2)
array([-0.59030264, 1.87821258])
np.random.normal(loc=2, scale=1.5, size=2)
array([2.52619561, 4.9684949 ])
np.random.seed(20000229)
np.random.normal(loc=2, scale=1.5, size=2)
array([-0.59030264, 1.87821258])
np.random.normal(loc=2, scale=1.5, size=2)
array([2.52619561, 4.9684949 ])
L’échantillonnage en Python

Utiliser une autre graine

np.random.seed(20000229)
np.random.normal(loc=2, scale=1.5, size=2)
array([-0.59030264, 1.87821258])
np.random.normal(loc=2, scale=1.5, size=2)
array([2.52619561, 4.9684949 ])
np.random.seed(20041004)
np.random.normal(loc=2, scale=1.5, size=2)
array([1.09364337, 4.55285159])
np.random.normal(loc=2, scale=1.5, size=2)
array([2.67038916, 2.36677492])
L’échantillonnage en Python

Passons à la pratique !

L’échantillonnage en Python

Preparing Video For Download...