np.random.seed
做什么?
np.random.seed(0)
原文由 covariance 发布,翻译遵循 CC BY-SA 4.0 许可协议
np.random.seed
做什么?
np.random.seed(0)
原文由 covariance 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果每次调用 numpy 的其他随机函数时设置 np.random.seed(a_fixed_number)
,结果将是相同的:
>>> import numpy as np
>>> np.random.seed(0)
>>> perm = np.random.permutation(10)
>>> print perm
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0)
>>> print np.random.permutation(10)
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0)
>>> print np.random.permutation(10)
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0)
>>> print np.random.permutation(10)
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0)
>>> print np.random.rand(4)
[0.5488135 0.71518937 0.60276338 0.54488318]
>>> np.random.seed(0)
>>> print np.random.rand(4)
[0.5488135 0.71518937 0.60276338 0.54488318]
但是,如果只调用一次并使用各种随机函数,结果仍然会有所不同:
>>> import numpy as np
>>> np.random.seed(0)
>>> perm = np.random.permutation(10)
>>> print perm
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0)
>>> print np.random.permutation(10)
[2 8 4 9 1 6 7 3 0 5]
>>> print np.random.permutation(10)
[3 5 1 2 9 8 0 6 7 4]
>>> print np.random.permutation(10)
[2 3 8 4 5 1 0 6 9 7]
>>> print np.random.rand(4)
[0.64817187 0.36824154 0.95715516 0.14035078]
>>> print np.random.rand(4)
[0.87008726 0.47360805 0.80091075 0.52047748]
原文由 Zhun Chen 发布,翻译遵循 CC BY-SA 4.0 许可协议
4 回答4.4k 阅读✓ 已解决
1 回答3.1k 阅读✓ 已解决
4 回答3.8k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
1 回答4.4k 阅读✓ 已解决
1 回答3.9k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决
np.random.seed(0)
使随机数可预测随着种子重置(每次),每次都会出现 相同 的一组数字。
如果未重置随机种子,则每次调用都会出现 不同的 数字:
(伪)随机数的工作原理是从一个数字(种子)开始,将其乘以一个大数,添加一个偏移量,然后对该总和取模。然后将得到的数字用作生成下一个“随机”数字的种子。当你设置种子(每次)时,它每次都做同样的事情,给你同样的数字。
如果您想要看似随机的数字,请不要设置种子。但是,如果您的代码使用要调试的随机数,那么在每次运行之前设置种子会非常有帮助,这样代码每次运行时都会执行相同的操作。
要为每次运行获取最多的随机数,请调用
numpy.random.seed()
。 这 将导致 numpy 将种子设置为从/dev/urandom
或其 Windows 模拟获得的随机数,或者,如果这些都不可用,它将使用时钟。有关使用种子生成伪随机数的更多信息,请参阅 wikipedia 。