我在Jupyter Lab笔记本上使用来自numpy.random的函数,并尝试使用numpy.random.seed(333)设置种子。只有当种子设置与代码在同一个notebook单元格中时,这才能按预期工作。例如,如果我有一个这样的脚本:
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随机种子?
发布于 2018-07-19 22:18:19
因为您反复调用randint,所以它每次都会生成不同的数字。重要的是要注意,seed并不会使函数始终返回相同的数字,而是会使函数在重复运行相同次数的时会产生相同的数字序列。因此,每次重新运行random.randint时都会得到相同的序列数字,而不是总是生成相同的数字。
如果您希望每次都使用相同的随机数,那么在每次调用random.randint之前,在该特定单元中重新设定种子应该是可行的。否则,您可以期望始终获得相同的数字序列,但不是每次都获得相同的数字。
发布于 2019-03-20 23:30:34
因为您在与np.random.seed()不同的单元中运行np.random.choice()。尝试在同一个单元格中运行np.random.seed()和np.random.choice(),您将得到相同的数字。
# in [11]
import numpy as np
# even if I set the seed here the other cells don't see it
np.random.seed(333)
np.random.choice([1,23,44,3,2])
2
# gets the same numbers
# in [12]
import numpy as np
# even if I set the seed here the other cells don't see it
np.random.seed(333)
np.random.choice([1,23,44,3,2])
2
# gets the same numbershttps://stackoverflow.com/questions/51424857
复制相似问题