Python np.random.seed() 和 np.random.RandomState() 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22994423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between np.random.seed() and np.random.RandomState()
提问by eran
I know that to seed the randomness of numpy.random, and be able to reproduce it, I should us:
我知道要播种 numpy.random 的随机性并能够重现它,我应该:
import numpy as np
np.random.seed(1234)
but what does
np.random.RandomState()
do?
但是有什么作用
np.random.RandomState()
呢?
采纳答案by askewchan
If you want to set the seed that calls to np.random...
will use, use np.random.seed
:
如果要设置调用np.random...
将使用的种子,请使用np.random.seed
:
np.random.seed(1234)
np.random.uniform(0, 10, 5)
#array([ 1.9151945 , 6.22108771, 4.37727739, 7.85358584, 7.79975808])
np.random.rand(2,3)
#array([[ 0.27259261, 0.27646426, 0.80187218],
# [ 0.95813935, 0.87593263, 0.35781727]])
Use the class to avoid impacting the global numpy state:
使用该类避免影响全局 numpy 状态:
r = np.random.RandomState(1234)
r.uniform(0, 10, 5)
#array([ 1.9151945 , 6.22108771, 4.37727739, 7.85358584, 7.79975808])
And it maintains the state just as before:
它像以前一样保持状态:
r.rand(2,3)
#array([[ 0.27259261, 0.27646426, 0.80187218],
# [ 0.95813935, 0.87593263, 0.35781727]])
You can see the state of the sort of 'global' class with:
您可以使用以下命令查看“全局”类的状态:
np.random.get_state()
and of your own class instance with:
和你自己的类实例:
r.get_state()
回答by Bruno Gelb
random.seedis a method to fill random.RandomStatecontainer.
random.seed是一种填充random.RandomState容器的方法。
from numpy docs:
来自 numpy 文档:
numpy.random.seed(seed=None)
Seed the generator.
This method is called when RandomState is initialized. It can be called again to re-seed the generator. For details, see RandomState.
播种发电机。
该方法在 RandomState 初始化时调用。可以再次调用以重新播种生成器。有关详细信息,请参阅 RandomState。
class numpy.random.RandomState
Container for the Mersenne Twister pseudo-random number generator.
Mersenne Twister 伪随机数生成器的容器。
回答by Fred Foo
np.random.RandomState()
constructs a random number generator. It does not have any effect on the freestanding functions in np.random
, but must be used explicitly:
np.random.RandomState()
构造一个随机数生成器。它对 中的独立函数没有任何影响np.random
,但必须明确使用:
>>> rng = np.random.RandomState(42)
>>> rng.randn(4)
array([ 0.49671415, -0.1382643 , 0.64768854, 1.52302986])
>>> rng2 = np.random.RandomState(42)
>>> rng2.randn(4)
array([ 0.49671415, -0.1382643 , 0.64768854, 1.52302986])