[英]numpy random not working with seed
import random
seed = random.random()
random_seed = random.Random(seed)
random_vec = [ random_seed.random() for i in range(10)]
以上內容主要是:
np.random.randn(10)
但我不知道如何設置種子?
我不知道你為什么要設置種子——尤其是一個隨機數,尤其是一個隨機浮點數(注意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
的數組),生成相同的隨機數。
簡單地說, 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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.