python - 我可以创建本地 numpy 随机种子吗?

标签 python numpy random scope

有一个函数 foo,它使用 np.random 功能。 我想控制 foo 使用的种子,但实际上不更改函数本身。 我该怎么做?

本质上我想要这样的东西:

bar() # should have normal seed
with np.random.seed(0): # Doesn't work
    foo()
bar() # should have normal seed
<小时/>

类似的解决方案 this :

rng = random.Random(42)
number = rng.randint(10, 20)

在这种情况下不起作用,因为我无权访问 foo 的内部运作(或者我错过了什么??)。

最佳答案

您可以将全局随机状态保存在临时变量中,并在函数完成后重置它:

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)

演示:

>>> 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])

关于python - 我可以创建本地 numpy 随机种子吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49555991/

相关文章:

python - 我如何解决这个错误 : TypeError: argument 1 must be pygame. Surface, not PngImageFile

python - Django:具有完全相同角色的属性和查询集的 DRY 代码?

c - 如何在c中生成设定范围内具有均匀间隔的随机值

ruby - 递归和 Kernel#rand 的奇怪行为 (Ruby)

python - 在 XMLRPC 中处理 unicode 数据

python - 使用谷歌应用程序引擎渲染动态图像

python - 在 SymPy 中使用 Lambdify 消除公共(public)子表达式的最佳实践

java - 25个奇偶随机数生成器

python - 如何在二维数组中索引给定的范围之间选择元素? NumPy

python - 如何使用索引向量从矩阵中提取元素?