jeudi 25 avril 2019

How To Set Global Random Seed in Python

Like in R, I would like to set a random seed globally for the entire script/session, instead of having to call the random seed function every time I execute a function or run a model. I am aware that sci-kit learn uses the numpy RNG, but also could not find a way to set it globally.

I have read several posts here on this topic, such as this one: Differences between numpy.random and random.random in Python

It explains the difference between the two RNG classes, but not how to set it globally.

Is there no way of doing this except for calling the random seed EVERY time I want the output to be the same?

## Random Library

import random
##### Random seed given
random.seed(42)
print(random.random()) #will generate a random number 

##### No seed given
print(random.random()) #will generate a random number 

##### Random seed given
random.seed(42)
print(random.random()) #will generate a random number 


#############################

## Numpy Library

import numpy as np

##### Random seed given
np.random.seed(42)
print(np.random.random())

##### No seed given
print(np.random.random())

##### Same seed given
np.random.seed(42)
print(np.random.random())




Aucun commentaire:

Enregistrer un commentaire