首页 文章

将numpy数组传递给Cython

提问于
浏览
6

我正在学习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 回答

  • 8

    你的结果是np.ndarray,而不是int . 它没有尝试将第一个转换为后者 . 相反

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

相关问题