Tok*_*rby 3 python random scope numpy
有一个功能,foo它使用该np.random功能.我想控制使用的种子foo,但实际上没有改变函数本身.我该怎么做呢?
基本上我想要这样的东西:
bar() # should have normal seed
with np.random.seed(0): # Doesn't work
foo()
bar() # should have normal seed
Run Code Online (Sandbox Code Playgroud)
解决方案像 这样:
rng = random.Random(42)
number = rng.randint(10, 20)
Run Code Online (Sandbox Code Playgroud)
在这种情况下不起作用,因为我无法访问内部工作foo(或者我错过了什么?).
Pau*_*zer 10
您可以将全局随机状态保存在临时变量中,并在完成功能后重置它:
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)
Run Code Online (Sandbox Code Playgroud)
演示:
>>> 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])
Run Code Online (Sandbox Code Playgroud)