Cython Class,用 Zeros 创建 NumPy
Cython Class, create NumPy with Zeros
我正在尝试创建一个用零创建 NumPy 的 cython class。后来我想在那个 Numpy 中写浮点值......
我的 python class 看起来像这样:
class test:
def __init__(self, b):
self.b = b
self.eTest = np.zeros((100, 100))
我的 cython class 目前看起来是这样的:
import numpy as np
cimport numpy as np
FTYPE = np.float
ctypedef np.float_t FTYPE_t
cdef class test:
def __init__(self, b):
cdef np.ndarray[FTYPE_t, ndim=2, mode='c'] eTest <<<works fine without this line
self.eTest = np.zeros((100,100), dtype=FTYPE)
我的 cython 代码目前无法运行。我正在努力解决如何创建没有任何 Python 的零 (100, 100) 的 NumPy 问题。这可能吗?我对 cython 不是很熟悉,如果我问了一些非常琐碎的问题,我很抱歉!
非常感谢您的帮助和建议!
重新定义你的 class::
cdef class test:
cdef double[:,:] eTest
def __init__(self, b):
cdef np.ndarray[FTYPE_t, ndim=2, mode='c'] tmp
tmp = np.zeros((100,100), dtype=FTYPE)
self.eTest = tmp
你的ndarray(在本例中为tmp
)只能是局部函数(在本例中为构造函数),所以你应该先声明eTest
作为一个缓冲区支持类型(a memoryview 在我的例子中),然后将 ndarray 复制到它。
作为旁注,我会直接将零 ndarray 分配给 eTest
:
cdef class test:
cdef double[:,:] eTest
def __init__(self, b):
self.eTest = np.zeros((100,100), dtype=FTYPE)
但我保留了您的结构以备不时之需。
我正在尝试创建一个用零创建 NumPy 的 cython class。后来我想在那个 Numpy 中写浮点值...... 我的 python class 看起来像这样:
class test:
def __init__(self, b):
self.b = b
self.eTest = np.zeros((100, 100))
我的 cython class 目前看起来是这样的:
import numpy as np
cimport numpy as np
FTYPE = np.float
ctypedef np.float_t FTYPE_t
cdef class test:
def __init__(self, b):
cdef np.ndarray[FTYPE_t, ndim=2, mode='c'] eTest <<<works fine without this line
self.eTest = np.zeros((100,100), dtype=FTYPE)
我的 cython 代码目前无法运行。我正在努力解决如何创建没有任何 Python 的零 (100, 100) 的 NumPy 问题。这可能吗?我对 cython 不是很熟悉,如果我问了一些非常琐碎的问题,我很抱歉!
非常感谢您的帮助和建议!
重新定义你的 class::
cdef class test:
cdef double[:,:] eTest
def __init__(self, b):
cdef np.ndarray[FTYPE_t, ndim=2, mode='c'] tmp
tmp = np.zeros((100,100), dtype=FTYPE)
self.eTest = tmp
你的ndarray(在本例中为tmp
)只能是局部函数(在本例中为构造函数),所以你应该先声明eTest
作为一个缓冲区支持类型(a memoryview 在我的例子中),然后将 ndarray 复制到它。
作为旁注,我会直接将零 ndarray 分配给 eTest
:
cdef class test:
cdef double[:,:] eTest
def __init__(self, b):
self.eTest = np.zeros((100,100), dtype=FTYPE)
但我保留了您的结构以备不时之需。