numpy随机不使用种子

时间:2014-12-13 03:52:37

标签: python numpy

import random
seed = random.random()
random_seed  = random.Random(seed)
random_vec = [ random_seed.random() for i in range(10)]

以上基本上是:

np.random.randn(10)

但我无法弄清楚如何设置种子?

2 个答案:

答案 0 :(得分:5)

我不确定为什么你希望设置种子 - 特别是设置一个随机数,尤其是随机浮点数(注意random.seed想要一个大整数)。

但如果你这样做,那很简单:调用numpy.random.seed函数。

请注意,NumPy的种子是32位整数的数组,而Python的种子是单个任意大小的整数(尽管请参阅文档,了解传递其他类型时会发生什么)。

所以,例如:

In [1]: np.random.seed(0)    
In [2]: s = np.random.randn(10)
In [3]: s
Out[3]:
array([ 1.76405235,  0.40015721,  0.97873798,  2.2408932 ,  1.86755799,
       -0.97727788,  0.95008842, -0.15135721, -0.10321885,  0.4105985 ])
In [4]: np.random.seed(0)
In [5]: s = np.random.randn(10)
In [6]: s
Out[6]:
array([ 1.76405235,  0.40015721,  0.97873798,  2.2408932 ,  1.86755799,
       -0.97727788,  0.95008842, -0.15135721, -0.10321885,  0.4105985 ])

使用相同的种子两次(我采用传递单个int的快捷方式,NumPy将在内部转换为1 int32的数组),生成相同的随机数。

答案 1 :(得分:0)

简单地说,random.seed(value) 不适用于 numpy 数组。 例如,

import random
import numpy as np
random.seed(10)
print( np.random.randint(1,10,10)) #generates 10 random integer of values from 1~10

[4 1 5 7 9 2 9 5 2 4]

random.seed(10)
print( np.random.randint(1,10,10))

[7 6 4 7 2 5 3 7 8 9]

但是,如果要为 numpy 生成的值设置种子,则必须使用 np.random.seed(value)。 如果我重温上面的例子,

import numpy as np

np.random.seed(10)
print( np.random.randint(1,10,10))

[5 1 2 1 2 9 1 9 7 5]

np.random.seed(10)
print( np.random.randint(1,10,10))

[5 1 2 1 2 9 1 9 7 5]
相关问题