将numpy数组传递给Cython

7

我正在学习Cython。我在将numpy数组传递给Cython时遇到了问题,不太理解发生了什么。你能帮我吗?

我有两个简单的数组:

a = np.array([1,2])
b = np.array([[1,4],[3,4]])

我想计算它们的点积。在Python / NumPy中,一切都运行良好:
>>> np.dot(a,b)
array([ 7, 12])

我将代码翻译成了Cython(就像这里所示:http://docs.cython.org/src/tutorial/numpy.html):

import numpy as np
cimport numpy as np

DTYPE = np.int
ctypedef np.int_t DTYPE_t

def dot(np.ndarray a, np.ndarray b):
    cdef int d = np.dot(a, b)
    return d

它编译没有问题,但返回了一个错误:
>>> dot(a,b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.pyx", line 8, in test.dot (test.c:1262)
    cdef int d = np.dot(a, b)
TypeError: only length-1 arrays can be converted to Python scalars

你能告诉我为什么以及如何正确地做吗?不幸的是,谷歌没有提供有用的信息...

谢谢!

1个回答

9

你的结果是np.ndarray,不是int。尝试将前者转换为后者失败了。请改为

def dot(np.ndarray a, np.ndarray b):
    cdef np.ndarray d = np.dot(a, b)
    return d

一个与 OP 的脚本更相关的问题:DTYPEctypedef 这些行对于这个示例是否真的必要?它们是在内部使用的标志吗? - n1k31t4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接