numpy - 将 numpy 整数数组传递给 C 代码

标签 numpy cython python-extensions

我正在尝试编写 Cython 代码以比 sklearn 的内置代码更快地将密集特征矩阵、目标向量对转储为 libsvm 格式。我收到一个编译错误,提示将目标向量(一个 numpy 数组)传递给相关的 c 函数时出现类型问题。

代码如下:

import numpy as np
cimport numpy as np
cimport cython

cdef extern from "cdump.h":
    int filedump( double features[], int numexemplars, int numfeats, int target[], char* outfname)

@cython.boundscheck(False)
@cython.wraparound(False)
def fastdumpdense_libsvmformat(np.ndarray[np.double_t,ndim=2] X, y, outfname):
    if X.shape[0] != len(y):
        raise ValueError("X and y need to have the same number of points")

    cdef int numexemplars = X.shape[0]
    cdef int numfeats = X.shape[1]

    cdef bytes py_bytes = outfname.encode()
    cdef char* outfnamestr = py_bytes

    cdef np.ndarray[np.double_t, ndim=2, mode="c"] X_c
    cdef np.ndarray[np.int_t, ndim=1, mode="c"] y_c
    X_c = np.ascontiguousarray(X, dtype=np.double)
    y_c = np.ascontiguousarray(y, dtype=np.int)
    retval = filedump( &X_c[0,0], numexemplars, numfeats, &y_c[0], outfnamestr)

    return retval

当我尝试使用 distutils 编译此代码时,出现错误

cythoning fastdump_svm.pyx to fastdump_svm.cpp

Error compiling Cython file:
------------------------------------------------------------ ...

    cdef np.ndarray[np.double_t, ndim=2, mode="c"] X_c
    cdef np.ndarray[np.int_t, ndim=1, mode="c"] y_c
    X_c = np.ascontiguousarray(X, dtype=np.double)
    y_c = np.ascontiguousarray(y, dtype=np.int)
    retval = filedump( &X_c[0,0], numexemplars, numfeats, &y_c[0], outfnamestr)
                                                         ^
------------------------------------------------------------

fastdump_svm.pyx:24:58: Cannot assign type 'int_t *' to 'int *'

知道如何解决这个错误吗?我最初遵循传递 y_c.data 的范例,这是有效的,但这显然不是推荐的方法。

最佳答案

您还可以在启动 numpy 数组时使用 dtype=np.dtype("i") 来匹配您机器上的 C int

cdef int [:] y_c
c_array = np.ascontiguousarray(y, dtype=np.dtype("i"))

关于numpy - 将 numpy 整数数组传递给 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23435756/

相关文章:

python - 如何将pandas中的if/else转换为np.where

python - "TypeError: data type not understood"比较数据类型 np.datetime64

c++ - 包装与内置函数同名的函数

python - 在 cython 中声明 numpy 数组和 c 指针

python - C++ 扩展中的 DateTime 对象方法出现问题

python - 使用 Numpy 准备 .npy 数据作为 CNN 的输入

python - numpy 轴数的明确权威解释?

小数选项大于 2 的 python np.round()

python - 找不到包: *. pxd文件的Cython C级接口(interface)

python - C 代码在尝试通过 xmlrpc 进行 Python 远程过程调用时崩溃