我可以创建一个本地 numpy 随机种子吗? [英] Can I create a local numpy random seed?
本文介绍了我可以创建一个本地 numpy 随机种子吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个函数,foo
,它使用了np.random
功能.我想控制 foo
使用的种子,但不实际更改函数本身.我该怎么做?
基本上我想要这样的东西:
bar() # 应该有正常的种子with np.random.seed(0): # 不起作用富()bar() # 应该有正常的种子
<小时>
解决方案如这个:
rng = random.Random(42)数字 = rng.randint(10, 20)
在这种情况下不起作用,因为我无法访问 foo
的内部工作原理(或者我错过了什么??).
解决方案
你可以将全局随机状态保存在一个临时变量中,并在你的函数完成后重置它:
导入上下文库将 numpy 导入为 np@contextlib.contextmanagerdef temp_seed(种子):状态 = np.random.get_state()np.random.seed(种子)尝试:屈服最后:np.random.set_state(状态)
演示:
<预><代码>>>>np.random.seed(0)>>>np.random.randn(3)数组([1.76405235,0.40015721,0.97873798])>>>np.random.randn(3)数组([2.2408932,1.86755799,-0.97727788])>>>np.random.seed(0)>>>np.random.randn(3)数组([1.76405235,0.40015721,0.97873798])>>>使用 temp_seed(5):... np.random.randn(3)数组([0.44122749,-0.33087015,2.43077119])>>>np.random.randn(3)数组([2.2408932,1.86755799,-0.97727788])There is a function, foo
, that uses the np.random
functionality.
I want to control the seed that foo
uses, but without actually changing the function itself.
How do I do this?
Essentially I want something like this:
bar() # should have normal seed
with np.random.seed(0): # Doesn't work
foo()
bar() # should have normal seed
Solutions like this:
rng = random.Random(42)
number = rng.randint(10, 20)
doesn't work in this case, as I don't have access to the inner workings of foo
(or am I missing something??).
解决方案
You could keep the global random state in a temporary variable and reset it once your function is done:
import contextlib
import numpy as np
@contextlib.contextmanager
def temp_seed(seed):
state = np.random.get_state()
np.random.seed(seed)
try:
yield
finally:
np.random.set_state(state)
Demo:
>>> np.random.seed(0)
>>> np.random.randn(3)
array([1.76405235, 0.40015721, 0.97873798])
>>> np.random.randn(3)
array([ 2.2408932 , 1.86755799, -0.97727788])
>>> np.random.seed(0)
>>> np.random.randn(3)
array([1.76405235, 0.40015721, 0.97873798])
>>> with temp_seed(5):
... np.random.randn(3)
array([ 0.44122749, -0.33087015, 2.43077119])
>>> np.random.randn(3)
array([ 2.2408932 , 1.86755799, -0.97727788])
这篇关于我可以创建一个本地 numpy 随机种子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文