始终如一地创建相同的随机 numpy 数组 [英] Consistently create same random numpy array

查看:31
本文介绍了始终如一地创建相同的随机 numpy 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在等待另一位开发人员完成一段代码,该代码将返回一个形状为 (100,2000) 且值为 -1,0 或 1 的 np 数组.

I am waiting for another developer to finish a piece of code that will return an np array of shape (100,2000) with values of either -1,0, or 1.

与此同时,我想随机创建一个具有相同特征的数组,这样我就可以在开发和测试中占得先机.问题是我希望这个随机创建的数组每次都相同,这样我就不会针对每次重新运行我的过程时不断更改其值的数组进行测试.

In the meantime, I want to randomly create an array of the same characteristics so I can get a head start on my development and testing. The thing is that I want this randomly created array to be the same each time, so that I'm not testing against an array that keeps changing its value each time I re-run my process.

我可以像这样创建我的数组,但是有没有办法创建它,以便每次都相同.我可以对对象进行腌制和取消腌制,但想知道是否还有其他方法.

I can create my array like this, but is there a way to create it so that it's the same each time. I can pickle the object and unpickle it, but wondering if there's another way.

r = np.random.randint(3, size=(100, 2000)) - 1

推荐答案

简单地用一个固定值给随机数生成器做种子,例如

Simply seed the random number generator with a fixed value, e.g.

numpy.random.seed(42)

这样,您将始终获得相同的随机数序列.

This way, you'll always get the same random number sequence.

此函数将作为全局默认随机数生成器的种子,并且对 numpy.random 中函数的任何调用都将使用并更改其状态.这对于许多简单的用例来说很好,但它是一种全局状态形式,具有全局状态带来的所有问题.如需更简洁的解决方案,请参阅下方 Robert Kern 的回答.

This function will seed the global default random number generator, and any call to a function in numpy.random will use and alter its state. This is fine for many simple use cases, but it's a form of global state with all the problems global state brings. For a cleaner solution, see Robert Kern's answer below.

这篇关于始终如一地创建相同的随机 numpy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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