【问题标题】:Cython ndarray with arbitrary dimensions具有任意维度的 Cython ndarray
【发布时间】:2015-10-24 08:30:40
【问题描述】:

我正在编写一些需要能够处理具有任意维数的 NumPy ndarray 的 Cython 代码。目前,我只有不同的函数可以接受不同大小的 ndarray,有点像:

def func1(np.ndarray[DTYPE_float64_t, ndim=1] arr):
    # Do something with the 1-D ndarray.

def func2(np.ndarray[DTYPE_float64_t, ndim=2] arr):
    # Do something with the 2-D ndarray.

def func3(np.ndarray[DTYPE_float64_t, ndim=3] arr):
    # Do something with the 3-D ndarray.

但我想编写一个通用函数,它将任意维度的 ndarray 作为参数。我尝试简单地关闭“ndim”参数,但随后 Cython 假定 ndim=1,这不好。

有没有办法做到这一点,或者我只需要为每个维度编写一个函数?

【问题讨论】:

    标签: python numpy cython


    【解决方案1】:

    如果你只是想按元素做一些事情,诀窍是获取数组的一维视图并对其进行操作

    def func(arr):
       shape = arr.shape
       output = _func_impl(arr.ravel())
       return output.reshape(shape) # ensure that the output is the same shape
           # as the input. Skip this if it doesn't make sense!
    
    def _func_impl(np.ndarray[DTYPE_float64_t, ndim=1] arr):
       # do something useful
    

    【讨论】:

    • 好点。但是我们可以在 cython 中展平内存视图吗?例如,我有一个函数cdef foo(float[:,:] arr),我想在arr 上应用逐元素函数,所以我需要将其展平为仅1dim。
    • 我认为这并不容易——你可能会通过一个指针,但它不会“很好”。 (请注意,它仅适用于float[:,::1] C 连续内存视图 - 其他内存视图需要重新分配内存,这绝对超出了内存 view 的范围)。如果 Cython 的问题跟踪器还没有,则可能值得在问题跟踪器上提出功能请求
    • 感谢您的回复。其实在玩了一阵 Cython 之后,我想我现在可能不会继续使用 Cython,因为与我拥有的 numpy 代码相比,Cython 似乎根本无法运行得更快,而且我仍然想重用Cython 内部的 numpy 广播函数,这使得 GIL 无法释放,进一步使得 Cython 代码无法并行运行。
    猜你喜欢
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 2013-12-24
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多