我对cython中的并行编程相当陌生,我试图从numpy创建一个大小为3的1D数组,但是除非我逐个元素地指定它,否则我无法为这个数组分配值。
import numpy as np
cimport numpy as cnp
cdef int num = 3
cdef cnp.ndarray[cnp.int_t, ndim = 1] Weight = np.ones((num), dtype = "int")
Weight[2] = 6
print(Weight)
输出 -> [1 1 6]
Weight = cnp.ndarray([1,2,3])
输出 -> 值错误:缓冲区有错误的维数(预期为 1,得到 3)
在评论中,我建议更改:
Weight = cnp.ndarray([1,2,3])
自
Weight = np.array([1,2,3])
只是为了进一步澄清我的评论:
该行
cdef cnp.ndarray[cnp.int_t, ndim = 1] Weight = np.ones((num), dtype = "int")
实际上是两部分:
cdef cnp.ndarray[cnp.int_t, ndim = 1] Weight
仅声明。这没有分配内存,它只是创建一个变量,该变量可以引用 numpy 数组,并允许快速索引。
Weight = np.ones((num), dtype = "int")
这是对
np.ones
的正常Python调用,它为数组分配内存。它在很大程度上没有被Cython加速。从这一点开始,Weight
是对该分配数组的引用,可用于更改它。请注意,以下行中的Weight = ...
将更改Weight
引用的数组。
因此,我建议您跳过np.ones
步骤,只需执行
cdef cnp.ndarray[cnp.int_t, ndim = 1] Weight = np.ones([1,2,3], dtype = "int")
请注意,使用这些声明加速的唯一 Numpy 是索引到数组中。几乎所有其他 Numpy 调用都是通过正常的 Python 机制进行的,并且需要 GIL 并且将以正常的 Python 速度发生。