本文介绍了整粒随机种子,适用于整个Jupyter笔记本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Jupyter Lab笔记本上使用numpy.random中的函数,并且尝试使用numpy.random.seed(333)设置种子.仅当种子设置与代码位于同一笔记本单元中时,此方法才能按预期工作.例如,如果我有一个这样的脚本:

I'm using functions from numpy.random on a Jupyter Lab notebook and I'm trying to set the seed using numpy.random.seed(333). This works as expected only when the seed setting is in the same notebook cell as the code. For example, if I have a script like this:

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)的输出将相同,因为设置了种子:

The output from both np.random.choice(ll) will be same, because the seed is set:

# python seed.py
4.0 
123.0
# python seed.py
4.0
123.0

现在,如果我尝试在Jupyter笔记本上执行相同的操作,则会得到不同的结果:

Now, if I try to do the same on the Jupyter notebook, I get different results:

# 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随机种子?

Is there a way to set the numpy random seed globally in a Jupyter lab notebook?

推荐答案

由于您反复调用randint,因此每次生成的数字都不相同.重要的是要注意,seed并不会使函数始终返回相同的数字,而是使它使得如果您重复运行randint相同的次数,将产生相同的序列.因此,每次重新运行random.randint时,您都会得到相同的序列编号,而不是总是产生相同的编号.

Because you're repeatedly calling randint, it generates different numbers each time. It's important to note that seed does not make the function consistently return the same number, but rather makes it such that the same sequence of numbers will be produced if you repeatedly run randint the same amount of times. Therefore, you're getting the same sequence of numbers every time you re-run the random.randint, rather than it always producing the same number.

如果您每次都希望使用相同的随机数,则在每个random.randint调用之前,应在该特定单元格中进行重新播种.否则,您可以期望始终获得相同的数字序列,但是不会每次都获得相同的数字.

Re-seeding in that specific cell, before each random.randint call, should work, if you want the same random number every single time. Otherwise, you can expect to consistently get the same sequence of numbers, but not to get the same number every time.

这篇关于整粒随机种子,适用于整个Jupyter笔记本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 07:41