【问题标题】:numpy implementing a custom RNGnumpy 实现自定义 RNG
【发布时间】:2023-04-07 16:42:01
【问题描述】:

出于一致性原因,我正在尝试让 numpy 使用我自己的 RNG 实现。我的理解是,根据我能从 numpy 文档here 和here 中找到的少量文档,我需要提供一个自定义 BitGenerator 类来实现random_raw 方法,然后使用np.random.Generator 进行初始化,所以我试过这个:

import numpy as np

class TestBitGenerator(np.random.BitGenerator):
  def __init__(self):
    super().__init__(0)
    self.counter = 0
  def random_raw(self, size=None):
    self.counter += 1
    if size is None:
      return self.counter
    return np.full(n, self.counter)  

mc_adapter = TestBitGenerator() 
npgen = np.random.Generator(mc_adapter)

print(npgen.random())

导致段错误:

$ python bitgen.py 
Segmentation fault (core dumped)

我假设我在这里遗漏了一些东西(来自 TestBitGenerator?),谁能指出我正确的方向?

我尝试不对 np.random.BitGenerator 进行子类化,但得到了不同的错误: object has no attribute 'capsule'

我使用 numpy 1.19.2 和 python 3.8.2

【问题讨论】:

  • 如果是出于一致性的原因,为什么不直接将种子设置为一致的值呢?
  • 解释我的确切需求似乎与问题无关,因为它很复杂。我有一些 C++ 代码(包括我的 RNG)通过 pybind11 传输到 python,并且我在 MPI 上运行,我需要控制每个进程的播种方式,并且每个进程应该(理想情况下)只使用一个可从两者访问的随机流C++ 和 python 层。

标签: python-3.x numpy random


【解决方案1】:

实际上,如果您使用库RandomGen(这是当前np.random.Generator 的孵化器)包装它,您可以在纯python 中完成它。所以有一个UserBitGenerator 允许你只使用python:https://bashtage.github.io/randomgen/bit_generators/userbitgenerator.html

很遗憾这没有在numpy 中出现(或者如果是我还没有找到它......)。

【讨论】:

    【解决方案2】:

    我做了一些挖掘here和Generator的构造函数看起来是这样的:

        def __init__(self, bit_generator):
            self._bit_generator = bit_generator
    
            capsule = bit_generator.capsule
            cdef const char *name = "BitGenerator"
            if not PyCapsule_IsValid(capsule, name):
                raise ValueError("Invalid bit generator. The bit generator must "
                                 "be instantiated.")
            self._bitgen = (<bitgen_t *> PyCapsule_GetPointer(capsule, name))[0]
            self.lock = bit_generator.lock
    

    here 还解释了bitgen_t 结构的要求:

    struct bitgen:
        void *state
        npy_uint64 (*next_uint64)(void *st) nogil
        uint32_t (*next_uint32)(void *st) nogil
        double (*next_double)(void *st) nogil
        npy_uint64 (*next_raw)(void *st) nogil
    
    ctypedef bitgen bitgen_t
    

    所以据我所知,看起来BitGenerator 的任何实现都必须在 cython 中完成,任何尝试在纯 python 中实现一个(也可能是 pybind11)都行不通(?)

    由于我不熟悉 cython 以及它是否/如何与 pybind11 共存,所以现在我只是要确保我的每个(并行)进程显式调用 np.random.Generator 并带有确定性播种的 numpy RNG所以它独立于我自己的RNG蒸汽。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-01
    • 2014-10-14
    • 2011-06-04
    • 2010-10-29
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多