问题
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())
回答1:
Your question looks contrary to whole idea of random number generator(valid in case for getting deterministic results).Generally, you want to seed your random number generator with some value that will change each execution (or different number eg. set some cookie no for a session) of the program. For instance, the current time is a frequently-used seed. The reason why this doesn't happen automatically is so that if you want, you can provide a specific seed to get a deterministic sequence.
Coming back to your question, if you want to have global seed and wanted to generate random with that seed. Then you can have a function to club both things and call whenever you want.
def same_seed_random()
np.random.seed(42)
print(np.random.random())
I would encourage you to check this for more on random seed@ https://pynative.com/python-random-seed/
来源:https://stackoverflow.com/questions/55846128/how-to-set-global-random-seed-in-python