假设我有一个Cython代码,其函数计算滚动移动平均值并返回与输入相同大小的数组(函数为初始部分添加nan
,但这对于手头的问题)。
我写了三个Cython函数(如下所示):
(a)sma_vec
来处理一维<{p>}的numpy
数组
(b)sma_mat
来处理numpy
二维数组
(c)第三个sma
根据尺寸返回sma_vec
或sma_mat
的值。 (我的动机是最终将cpdef
或sma_vec
之前的sma_mat
替换为cdef
,以便Python代码只能看到sma
函数)
功能1 - 处理1维
的numpy
数组
cimport cython
import numpy as np
cimport numpy as np
from numpy cimport ndarray as ar
ctypedef double dtype_t
@cython.boundscheck(False)
@cython.wraparound(False)
cpdef sma_vec(ar[dtype_t, ndim=1] x, int m):
cdef int n
cdef Py_ssize_t i, j
cdef ar[dtype_t, ndim=1] y
if m == 1:
return x.copy()
else:
y = np.zeros_like(x) * np.nan
n = x.shape[0]
if n < m:
return y
else:
for i in range(m-1, n):
for j in range(i-m+1, i+1):
if j == i-m+1:
y[i] = x[j]
else:
y[i] += x[j]
y[i] /= float(m)
return y
功能2 - 处理numpy
二维数组(在ndarray
的每一行调用函数1)
@cython.boundscheck(False)
@cython.wraparound(False)
cpdef sma_mat(ar[dtype_t, ndim=2] x, int m):
cdef int n
cdef Py_ssize_t i
cdef ar[dtype_t, ndim=2] y
if m == 1:
return x.copy()
else:
y = np.zeros_like(x) * np.nan
n = x.shape[0]
if n < m:
return y
else:
for i in range(0, x.shape[0]):
y[i] = sma_vec(x[i], m)
return y
功能3 - 根据尺寸调用功能1或功能2
@cython.boundscheck(False)
@cython.wraparound(False)
cpdef sma(ar[dtype_t] x, int m):
if x.ndim == 1:
return sma_vec(x, m)
elif x.ndim == 2:
return sma_mat(x, m)
else:
raise ValueError('Cannot handle more than two dimensions')
测试代码
import numpy as np
import common.movavg as mv
x1 = np.array([1.0, 1.4, 1.3, 5.3, 2.3])
y1 = mv.sma_vec(x1, 3)
y1a = mv.sma(x1, 3)
y1
和y1a
都正确地返回array([nan, nan, 1.233333, 2.666667, 2.966667])
x2 = np.array([[1.0, 1.4, 1.3, 5.3, 2.3], [4.2, 1.3, 2.3, 5.7, -1.3]])
y2 = mv.sma_mat(x2, 2)
y2
正确返回
array([[ nan, 1.2 , 1.35, 3.3 , 3.8 ],
[ nan, 2.75, 1.8 , 4. , 2.2 ]])
但是当我尝试时:
y2a = mv.sma(x2, 2)
我收到错误:
Traceback (most recent call last):
File "C:\PF\WinPython-64bit-3.4.2.4\python-3.4.2.amd64\lib\site-packages\IPython\core\interactiveshell.py", line 2883, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-4-dc092e343714>", line 3, in <module>
y2a = mv.sma(x2, 2)
File "movavg.pyx", line 54, in movavg.sma (stat\movavg.c:2206)
ValueError: Buffer has wrong number of dimensions (expected 1, got 2)
在sma
函数中,问题似乎是ar[dtype_t] x
(即np.ndarray[double] x
)自动认为x.ndim
的维度应为1
。
如何重新编写sma
函数,以便它可以接受维度未知的np.ndarray
?
答案 0 :(得分:1)
从此链接:numpy_tutorial,“...”ndim“仅限关键字参数,如果未提供,则假定为一维...”
解决方案是将功能3转换为:
@cython.boundscheck(False)
@cython.wraparound(False)
cpdef sma(ar x, int m):
if x.ndim == 1:
return sma_vec(x, m)
elif x.ndim == 2:
return sma_mat(x, m)
else:
raise ValueError('Cannot handle more than two dimensions')
我们需要完全删除[]
中的所有内容。