【发布时间】:2018-12-27 17:19:39
【问题描述】:
我在 Jupyter Lab 笔记本上使用来自 numpy.random 的函数,我正在尝试使用 numpy.random.seed(333) 设置种子。仅当种子设置与代码位于同一笔记本单元格中时,这才能按预期工作。例如,如果我有这样的脚本:
import numpy as np
np.random.seed(44)
ll = [3.2,77,4535,123,4]
print(np.random.choice(ll))
print(np.random.choice(ll))
np.random.choice(ll) 的输出将相同,因为设置了种子:
# python seed.py
4.0
123.0
# python seed.py
4.0
123.0
现在,如果我尝试在 Jupyter 笔记本上做同样的事情,我会得到不同的结果:
# in [11]
import numpy as np
# even if I set the seed here the other cells don't see it
np.random.seed(333)
# in [12]
np.random.choice([1,23,44,3,2])
23
# gets the same numbers
# in [13]
np.random.choice([1,23,44,3,2])
44
# gets different numbers every time I run this cell again
有没有办法在 Jupyter 实验室笔记本中全局设置 numpy 随机种子?
【问题讨论】:
-
但是你反复调用
randint所以它会在后续的单元格中给你一个不同的数字,你必须在调用 randint 之前设置种子以获得一致性这没有什么不同如果您在 python 终端中并进行了相同的后续调用 -
更改了代码以反映我的意思。
-
你似乎还是不明白,一旦你调用了
seed,然后你反复调用choice,除非你重置种子,否则你会得到一个不同的值,我不知道为什么这不清楚 -
如果您问是否有可能在不明确设置种子的情况下获得相同的结果,我认为这是不可能的
-
我相信 OP 是说如果你运行种子单元,然后立即在另一个单元中调用 choice(),你会得到一些值 X,但 即使在你重新运行种子单元之后 重新运行 choice() 单元格会给出不同的 Y 值。
标签: python numpy jupyter-notebook