Should I use np.random.seed or random.seed?
That depends on whether in your code you are using numpy's random number generator or the one in random
.
The random number generators in numpy.random
and random
have totally separate internal states, so numpy.random.seed()
will not affect the random sequences produced by random.random()
, and likewise random.seed()
will not affect numpy.random.randn()
etc. If you are using both random
and numpy.random
in your code then you will need to separately set the seeds for both.
Update
Your question seems to be specifically about scikit-learn's random number generators. As far as I can tell, scikit-learn uses numpy.random
throughout, so you should use np.random.seed()
rather than random.seed()
.
One important caveat is that np.random
is not threadsafe - if you set a global seed, then launch several subprocesses and generate random numbers within them using np.random
, each subprocess will inherit the RNG state from its parent, meaning that you will get identical random variates in each subprocess. The usual way around this problem is to pass a different seed (or numpy.random.Random
instance) to each subprocess, such that each one has a separate local RNG state.
Since some parts of scikit-learn can run in parallel using joblib, you will see that some classes and functions have an option to pass either a seed or an np.random.RandomState
instance (e.g. the random_state=
parameter to sklearn.decomposition.MiniBatchSparsePCA
). I tend to use a single global seed for a script, then generate new random seeds based on the global seed for any parallel functions.
np.random.seed()
you won't need to import anything, but for usingrandom.seed()
you will need to import therandom
moduleRandom
object and set its seed instead. Read the last comment by Muhammad Alkarouri in this question for a safer workaround: stackoverflow.com/a/3717456/1524913color_rnd
as per that example. If I runcolor_rnd.seed(1234)
, will functions likesklearn.cross_validation.KFold
"know" to use it instead of whatever RNG it normally uses?random
directly sadly. My point was, at least then. whenever you type code, avoid to userandom
itself directly. I'm not sure what to do in your scenario, that's a bit of a bummer. Maybe a decorator but I think you'd have to tinker with the function context but I'm not 100% sure, I'd have to have a deeper look at it to be sure.