我未能将一个布尔掩码作为Cython类的属性保存。在实际代码中,我需要此掩码以更高效地执行任务。以下是一个示例代码:
core.pyx
import numpy as np
cimport numpy as np
cdef class MyClass():
cdef public np.uint8_t[:] mask # uint8 has the same data structure of a boolean array
cdef public np.float64_t[:] data
def __init__(self, size):
self.data = np.random.rand(size).astype(np.float64)
self.mask = np.zeros(size, np.uint8)
script.py
import numpy as np
import pyximport
pyximport.install(setup_args={'include_dirs': np.get_include()})
from core import MyClass
mc = MyClass(1000000)
mc.mask = np.asarray(mc.data) > 0.5
错误
当我运行 script.py
时,Cython 成功编译,但却抛出以下错误:
Traceback (most recent call last):
File "script.py", line 8, in <module>
mc.mask = np.asarray(mc.data) > 0.5
File "core.pyx", line 6, in core.MyClass.mask.__set__
cdef public np.uint8_t[:] mask
ValueError: Does not understand character buffer dtype format string ('?')
解决方法
我的当前解决方法是在所有需要的函数中传递掩码,使用 cast=True
,例如:
cpdef func(MyClass mc, np.ndarray[np.uint8_t, ndim=1, cast=True] mask):
return np.asarray(mc.data)[mask]
问题
有没有任何关于如何在Cython类中存储掩码的想法?
mc.mask = (np.asarray(mc.data) > 0.5).view(np.uint8_t)
可以正确地分配(作为另一种解决方法)。 - DavidW