【问题标题】:writing numpy codes in cython with unknown dimensions在 cython 中编写未知维度的 numpy 代码
【发布时间】:2015-08-03 19:41:26
【问题描述】:

假设我有一个 Cython 代码,其函数计算滚动移动平均值并返回与输入大小相同的数组(该函数为初始部分添加 nan,但这对于问题并不重要手)。

我已经编写了三个 Cython 函数(如下所示):

(a) sma_vec 处理numpy 一维数组

(b)sma_mat 处理numpy 二维数组

(c) 第三个smasma_vecsma_mat 返回值,具体取决于大小。 (我的动机是最终将sma_vecsma_mat 之前的cpdef 替换为cdef,以便Python 代码只能看到sma 函数)

函数 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)

y1y1a 都正确返回 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

【问题讨论】:

  • 看起来像一个复制粘贴错误:您在检查 x.ndim == 2:elif x.ndim == 2: return sma_vec(x, m) 后调用向量。将其更改为return sma_mat(x, m),您应该一切顺利。
  • 感谢您指出。我改变了它,但代码出人意料地给出了同样的错误
  • 只是为了检查,但你做了更改后重新编译了吗?
  • 是的,我做到了。实际上几次。它在你的机器上运行了吗?

标签: python numpy cython


【解决方案1】:

找到了答案。

从此链接:numpy_tutorial,“...“ndim”仅关键字参数,如果未提供,则假定为一维...”

解决方法是将Function 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')

我们需要完全删除[] 中的所有内容。

【讨论】:

    猜你喜欢
    • 2021-08-23
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 2012-10-14
    • 2017-04-10
    • 1970-01-01
    • 2014-03-06
    • 2020-07-07
    相关资源
    最近更新 更多