Numpy random seed valid for entire jupyter notebook

旧巷老猫 提交于 2020-01-03 16:54:33

问题


I'm using functions from numpy.random on a Jupyter Lab notebook and I'm trying to set the seed using numpy.random.seed(333). This works as expected only when the seed setting is in the same notebook cell as the code. For example, if I have a script like this:

import numpy as np

np.random.seed(44)

ll = [3.2,77,4535,123,4]

print(np.random.choice(ll))
print(np.random.choice(ll))

The output from both np.random.choice(ll) will be same, because the seed is set:

# python seed.py
4.0 
123.0
# python seed.py
4.0
123.0

Now, if I try to do the same on the Jupyter notebook, I get different results:

# in [11]
import numpy as np
# even if I set the seed here the other cells don't see it
np.random.seed(333)

# in [12]
np.random.choice([1,23,44,3,2])
23
# gets the same numbers

# in [13]
np.random.choice([1,23,44,3,2])
44
# gets different numbers every time I run this cell again

Is there a way to set the numpy random seed globally in a Jupyter lab notebook?


回答1:


Because you're repeatedly calling randint, it generates different numbers each time. It's important to note that seed does not make the function consistently return the same number, but rather makes it such that the same sequence of numbers will be produced if you repeatedly run randint the same amount of times. Therefore, you're getting the same sequence of numbers every time you re-run the random.randint, rather than it always producing the same number.

Re-seeding in that specific cell, before each random.randint call, should work, if you want the same random number every single time. Otherwise, you can expect to consistently get the same sequence of numbers, but not to get the same number every time.




回答2:


Because you run np.random.choice() in the cells different from np.random.seed(). Try to run np.random.seed() and np.random.choice() in the same cell, you'll get same number.

# in [11]
import numpy as np
# even if I set the seed here the other cells don't see it
np.random.seed(333)
np.random.choice([1,23,44,3,2])
2
# gets the same numbers

# in [12]
import numpy as np
# even if I set the seed here the other cells don't see it
np.random.seed(333)
np.random.choice([1,23,44,3,2])
2
# gets the same numbers


来源:https://stackoverflow.com/questions/51424857/numpy-random-seed-valid-for-entire-jupyter-notebook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!