【问题标题】:numpy random not working with seednumpy random 不使用种子
【发布时间】:2014-12-13 03:52:37
【问题描述】:
import random
seed = random.random()
random_seed  = random.Random(seed)
random_vec = [ random_seed.random() for i in range(10)]

以上实质是:

np.random.randn(10)

但我不知道如何设置种子?

【问题讨论】:

  • 你为什么想要设置种子?尤其是随机数?

标签: python numpy


【解决方案1】:

我不知道你为什么想要设置种子——尤其是随机数,尤其是随机浮点数(注意random.seed 需要一个大整数)。 p>

但如果你这样做,很简单:调用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 的数组),生成相同的随机数。

【讨论】:

  • 您在这里只分配给s 一次,因此s 将始终相同,与第二次设置种子无关。
  • 您忘记分配第二次s = np.random.randn(10),但是最终结果应该是一样的。
【解决方案2】:

简单地说,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]

【讨论】:

    猜你喜欢
    • 2016-04-02
    • 1970-01-01
    • 2014-09-14
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 2014-08-07
    • 1970-01-01
    相关资源
    最近更新 更多