numpy.random.seed(0) 有什么作用? [英] What does numpy.random.seed(0) do?

查看:22
本文介绍了numpy.random.seed(0) 有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

np.random.seed 在以下来自 Scikit-Learn 教程的代码中做了什么?我不是很熟悉 NumPy 的随机状态生成器的东西,所以我真的很感激外行对此的解释.

np.random.seed(0)指数 = np.random.permutation(len(iris_X))

解决方案

np.random.seed(0) 使随机数可预测

<预><代码>>>>numpy.random.seed(0) ;numpy.random.rand(4)数组([ 0.55, 0.72, 0.6, 0.54])>>>numpy.random.seed(0) ;numpy.random.rand(4)数组([ 0.55, 0.72, 0.6, 0.54])

随着种子重置(每次),每次都会出现相同的一组数字.

如果随机种子没有被重置,每次调用都会出现不同的数字:

<预><代码>>>>numpy.random.rand(4)数组([ 0.42, 0.65, 0.44, 0.89])>>>numpy.random.rand(4)数组([ 0.96, 0.38, 0.79, 0.53])

(伪)随机数的工作原理是从一个数字(种子)开始,将它乘以一个大数,加上一个偏移量,然后对该总和进行取模.然后将结果数字用作种子以生成下一个随机"数字.当你设置种子时(每次),它每次都做同样的事情,给你相同的数字.

如果您想要看似随机的数字,请不要设置种子.但是,如果您要调试使用随机数的代码,那么在每次运行之前设置种子会非常有帮助,这样代码每次运行时都会做同样的事情.

要为每次运行获得最多的随机数,请调用 numpy.random.seed().将导致 numpy将种子设置为从 /dev/urandom 或它的 Windows 模拟获得的随机数,或者,如果这两个都不可用,它将使用时钟.

有关使用种子生成伪随机数的更多信息,请参阅维基百科.

What does np.random.seed do in the below code from a Scikit-Learn tutorial? I'm not very familiar with NumPy's random state generator stuff, so I'd really appreciate a layman's terms explanation of this.

np.random.seed(0)
indices = np.random.permutation(len(iris_X))

解决方案

np.random.seed(0) makes the random numbers predictable

>>> numpy.random.seed(0) ; numpy.random.rand(4)
array([ 0.55,  0.72,  0.6 ,  0.54])
>>> numpy.random.seed(0) ; numpy.random.rand(4)
array([ 0.55,  0.72,  0.6 ,  0.54])

With the seed reset (every time), the same set of numbers will appear every time.

If the random seed is not reset, different numbers appear with every invocation:

>>> numpy.random.rand(4)
array([ 0.42,  0.65,  0.44,  0.89])
>>> numpy.random.rand(4)
array([ 0.96,  0.38,  0.79,  0.53])

(pseudo-)random numbers work by starting with a number (the seed), multiplying it by a large number, adding an offset, then taking modulo of that sum. The resulting number is then used as the seed to generate the next "random" number. When you set the seed (every time), it does the same thing every time, giving you the same numbers.

If you want seemingly random numbers, do not set the seed. If you have code that uses random numbers that you want to debug, however, it can be very helpful to set the seed before each run so that the code does the same thing every time you run it.

To get the most random numbers for each run, call numpy.random.seed(). This will cause numpy to set the seed to a random number obtained from /dev/urandom or its Windows analog or, if neither of those is available, it will use the clock.

For more information on using seeds to generate pseudo-random numbers, see wikipedia.

这篇关于numpy.random.seed(0) 有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆