【问题标题】:how to declare numpy.bool in cython?如何在 cython 中声明 numpy.bool?
【发布时间】:2018-04-08 07:33:10
【问题描述】:

根据官方文档: http://docs.cython.org/en/latest/src/tutorial/numpy.html 我们应该“ctypedef”一个相应的编译时类型,但我尝试了几种方法来处理numpy.bool。还是错了。

(1) DTYPE2 = np.bool

ctypedef np.bool_t DTYPE2_t

提高: 'bool_t' 不是类型标识符

(2) DTYPE2 = np.bint

ctypedef np.bint_t DTYPE2_t

提高: 'bint_t' 不是类型标识符

(3) 在 .pyx 文件顶部添加:

from libcpp cimport bool
#? As recommended by McKelvin in  [https://stackoverflow.com/questions/24659723/cython-issue-bool-is-not-a-type-identifier][2]
#from libcpp cimport bool_t 
from libcpp.vector cimport vector

没有帮助!

(4) 我看过帖子: Declaring a numpy boolean mask in Cython 但是我需要在函数的参数中定义变量来传递一个 numpy.bool 数组。

def Func(np.ndarray[np.bool_t, ndim=1] f)

## def Func(np.ndarray[np.bool, ndim=1] f)

提高: 无效类型

(5) 忽略声明?如果我想加快它的速度,根据官方文档,函数的参数似乎是必要的:

def naive_convolve(np.ndarray[DTYPE_t, ndim=2] f, np.ndarray[DTYPE_t, ndim=2] g):

那么我应该如何处理 numpy.bool?

我的测试基于以下简单代码:

import numpy as np
cimport numpy as np
cimport cython

DTYPE2 = np.bint
ctypedef np.bint_t DTYPE2_t
def Func(np.ndarray[DTYPE2_t, ndim=1] npdata):
    print(npdata)

cython:最新版本

windows7 操作系统

我确定 cython 安装正确。没有 np.bool 时它可以正常工作。

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    numpy boolean ctype 的名称是npy_bool。所以你的测试代码的正确版本是:

    import numpy as np
    cimport numpy as np
    cimport cython
    
    def Func(np.ndarray[np.npy_bool, ndim=1, cast=True] npdata):
        print(npdata)
        return npdata
    

    注意上面的cast=True(我还添加了一个返回语句用于测试目的)。这里有一些代码测试Func out:

    arr = np.random.randint(0,2, size=3, dtype=int)
    boolArr = np.array(arr, dtype=bool)
    
    # Func(arr)                     # raises "ValueError: Item size of buffer (8 bytes) does not match size of 'npy_bool' (1 byte)"
    returnArr = Func(boolArr)
    assert returnArr.dtype is np.dtype(bool)
    

    注意cast

    如果没有cast 关键字,当您尝试调用Func 时会收到一条非常奇怪的错误消息:

    ValueError: Does not understand character buffer dtype format string ('?')
    

    深入了解Cython source code 可以对上述ValueError 有所了解。 Numpy 使用的 dtype 的一种表示形式是"array-protocol type strings"。布尔值是'?'。其中许多可以使用数字指定,例如'4i',它表示该类型的单个元素需要多少字节。 Cython 显然根据这个字符串解释数组类型,and expects there to be a number,它似乎 Numpy 不为 bool 提供。可能只是某些东西(在 Numpy 或 Cython 中)需要某个地方的错误修复。

    更新

    cast=True 参数可能不再需要了。我提交了pull request with a fix to Cython,它似乎即将通过。

    【讨论】:

    • 太棒了!非常感谢!这就是我想要的
    • 有趣。漏洞还在!感谢您写详细的解释。
    • @Ginger 我刚刚提交了一个PR with a fix to Cython,所以希望这个错误很快就会消失。
    • 很好的答案,谢谢!你知道如何通过内存视图访问这个数组吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多