简体   繁体   English

将numpy数组传递给Cython

[英]Passing numpy array to Cython

I am learning Cython. 我正在学习Cython。 I have problem with passing numpy arrays to Cython and don't really understand what is going on. 我有将numpy数组传递给Cython的问题,并且不太了解发生了什么。 Could you help me? 你可以帮帮我吗?

I have two simple arrays: 我有两个简单的数组:

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

I want to compute a dot product of them. 我想计算它们的点积。 In python/numpy everything works fine: 在python / numpy一切正常:

>>> np.dot(a,b)
array([ 7, 12])

I translated the code to Cython (as here: http://docs.cython.org/src/tutorial/numpy.html ): 我将代码翻译成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

It compiled with no problems but returns an error: 它编译没有问题但返回错误:

>>> 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

Could you tell me why and how to do it correctly? 你能告诉我为什么以及如何正确地做到这一点? Unfortunately Google was not helpful... 不幸的是谷歌没有帮助......

Thanks! 谢谢!

Your result is np.ndarray, not int. 你的结果是np.ndarray,而不是int。 It fails trying to convert first one to latter. 它没有尝试将第一个转换为后者。 Do instead 相反

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM