Tim*_*Tim 6 python numpy cython
我正在学习Cython.我有将numpy数组传递给Cython的问题,并且不太了解发生了什么.你可以帮帮我吗?
我有两个简单的数组:
a = np.array([1,2])
b = np.array([[1,4],[3,4]])
Run Code Online (Sandbox Code Playgroud)
我想计算它们的点积.在python/numpy一切正常:
>>> np.dot(a,b)
array([ 7, 12])
Run Code Online (Sandbox Code Playgroud)
我将代码翻译成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
Run Code Online (Sandbox Code Playgroud)
它编译没有问题但返回错误:
>>> 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
Run Code Online (Sandbox Code Playgroud)
你能告诉我为什么以及如何正确地做到这一点?不幸的是谷歌没有帮助......
谢谢!
你的结果是np.ndarray,而不是int.它没有尝试将第一个转换为后者.相反
def dot(np.ndarray a, np.ndarray b):
cdef np.ndarray d = np.dot(a, b)
return d
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1117 次 |
| 最近记录: |