我正在学习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
你能告诉我为什么以及如何正确地做吗?不幸的是,谷歌没有提供有用的信息...
谢谢!
DTYPE
和ctypedef
这些行对于这个示例是否真的必要?它们是在内部使用的标志吗? - n1k31t4