[英]What is the working range of `numpy.random.seed()`?
在 python 控制台中,如果要保持輸出相同,則必須在每次運行時設置種子。
In[0]: import numpy as np
In[1]: np.random.seed(1); np.random.randint(1, 10, 5)
Out[0]: array([6, 9, 6, 1, 1])
In[2]: np.random.seed(1); np.random.randint(1, 10, 5)
Out[1]: array([6, 9, 6, 1, 1])
In[3]: np.random.randint(1, 10, 5)
Out[2]: array([2, 8, 7, 3, 5]) # Different output if the seed was not set
但是,當涉及到運行多個文件的代碼時,一個文件中的隨機函數會受到另一個導入模塊中設置的種子的影響,這可能會導致一些意想不到的問題。
說,我有兩個文件
# main.py
from myfunc import *
import numpy as np
myfunc()
print('main.py:', np.random.randint(1, 10, 5))
和
# myfunc.py
import numpy as np
def myfunc():
np.random.seed(2019)
numbers = np.random.randint(1, 10, 5)
print('myfunc:', numbers)
如果我運行main
兩次,我會得到相同的結果
myfunc.py: [9 3 6 9 7]
main.py: [9 1 1 8 9]
和
myfunc.py: [9 3 6 9 7]
main.py: [9 1 1 8 9]
這意味着即使沒有在main.py
設置randint
也已播種。 看到這一點,我想那是因為np.random.seed()
有點全局性。 我應該小心使用它,特別是當我只想讓它在本地工作時。
到目前為止,我的解決方案是在我使用完種子時重置種子。 喜歡
np.random.seed(2019)
numbers = np.random.randint(1, 10, 5)
np.random.seed()
我不確定np.random.seed()
的工作范圍是np.random.seed()
。 還有其他方法可以避免全局設置問題嗎?
您可以創建numpy.random.RandomState
的本地實例以絕對確保種子是本地的:
>>> import numpy as np
>>> first_state = np.random.RandomState(seed=1)
>>> first_state.rand()
0.417022004702574
>>> first_state.rand()
0.7203244934421581
>>> second_state = np.random.RandomState(seed=1)
>>> second_state.rand()
0.417022004702574
>>> second_state.rand()
0.7203244934421581
然后,您可以調用從該本地對象的不同分布中繪制數字的所有函數,例如: state.rand()
、 state.normal()
、 state.uniform()
等。
使用np.random.seed()
您將播種全局numpy.random.RandomState
。 作為旁注,可以像這樣訪問全局(默認) RandomState
:
numpy_default_rng = numpy.random.random.__self__
要僅在本地為您的RandomState
您可以創建自己的實例並使用其方法繪制數字。 (另見此處)
例如:
random_state = numpy.random.RandomState(seed=2)
random_state.randint(10)
將始終返回相同的結果,而無需對 np.random 進行其他調用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.