简体   繁体   English

如何使用新的 NumPy 随机数发生器?

[英]How to use the new NumPy random number generator?

The fact that NumPy now recommends that new code uses the defacult_rng() instance instead of numpy.random for new code has got me thinking about how it should be used to yield good results, both performance vice and statistically. NumPy 现在建议新代码使用defacult_rng()实例而不是numpy.random的事实让我思考如何使用它来产生良好的结果,无论是性能还是统计。

This first example is how I first wanted to write:第一个例子是我最初想写的:

import numpy as np

class fancy_name():
  def __init__(self):
    self.rg = np.random.default_rng()
    self.gamma_shape = 1.0
    self.gamma_scale = 1.0

  def public_method(self, input):
    # Do intelligent stuff with input
    return self.rg.gamma(self.gamma_shape, slef.gamma_scale)

But I have also considered creating a new instance in every function call:但我也考虑过在每个 function 调用中创建一个新实例:

import numpy as np

class fancy_name():
  def __init__(self):
    self.gamma_shape = 1.0
    self.gamma_scale = 1.0

  def public_method(self, input):
    # Do intelligent stuff with input
    rg = np.random.default_rng()
    return rg.gamma(self.gamma_shape, slef.gamma_scale)

A third alternative would be to pass the rng as an argument in the function call.第三种选择是将 rng 作为参数传递给 function 调用。 This way the same rng can be used in other parts of the code as well.这样,相同的 rng 也可以用于代码的其他部分。

This is used in a simulation environment that is going to be called often to sample, for example, transition times.这用于模拟环境中,该环境将经常被调用来采样,例如,转换时间。

I guess the question is if there are arguments for any of these three methods and if there exists some kind of praxis?我想问题是这三种方法中是否有 arguments 以及是否存在某种实践?

Also, any reference to more in-depth explanations of using these random number generators (except for the NumPy doc and Random Sampling article) is of great interest!此外,对使用这些随机数生成器的更深入解释的任何参考(NumPy 文档和随机采样文章除外)都非常有趣!

default_rng() isn't a singleton. default_rng()不是 singleton。 It makes a new Generator backed by a new instance of the default BitGenerator class.它创建了一个由默认 BitGenerator class 的实例支持的新生成器。 Quoting the docs :引用文档

Construct a new Generator with the default BitGenerator (PCG64).使用默认的 BitGenerator (PCG64) 构造一个的生成器。

... ...

If seed is not a BitGenerator or a Generator, a new BitGenerator is instantiated.如果种子不是 BitGenerator 或 Generator,则实例化一个的 BitGenerator。 This function does not manage a default global instance.此 function 不管理默认全局实例。

This can also be tested empirically:这也可以通过经验进行测试:

In [1]: import numpy

In [2]: numpy.random.default_rng() is numpy.random.default_rng()
Out[2]: False

This is expensive.这是昂贵的。 You should usually call default_rng() once in your program and pass the generator to anything that needs it.您通常应该在程序中调用一次default_rng()并将生成器传递给任何需要它的东西。 (Yes, this is awkward.) (是的,这很尴尬。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM