如何将 scipy.sparse CSR 矩阵正确传递给 cython 函数? [英] How to properly pass a scipy.sparse CSR matrix to a cython function?
本文介绍了如何将 scipy.sparse CSR 矩阵正确传递给 cython 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将 scipy.sparse CSR 矩阵传递给 cython 函数.如何指定类型,就像 numpy 数组一样?
I need to pass a scipy.sparse CSR matrix to a cython function. How do I specify the type, as one would for a numpy array?
推荐答案
这里有一个例子,说明如何使用 row
属性快速访问 coo_matrix
中的数据,col
和 data
.该示例的目的只是展示如何声明数据类型和创建缓冲区(还添加编译器指令,这通常会给您带来相当大的提升)...
Here is an example about how to quickly access the data from a coo_matrix
using the properties row
, col
and data
. The purpose of the example is just to show how to declare the data types and create the buffers (also adding the compiler directives that will usually give you a considerable boost)...
#cython: boundscheck=False
#cython: wraparound=False
#cython: cdivision=True
#cython: nonecheck=False
import numpy as np
from scipy.sparse import coo_matrix
cimport numpy as np
ctypedef np.int32_t cINT32
ctypedef np.double_t cDOUBLE
def print_sparse(m):
cdef np.ndarray[cINT, ndim=1] row, col
cdef np.ndarray[cDOUBLE, ndim=1] data
cdef int i
if not isinstance(m, coo_matrix):
m = coo_matrix(m)
row = m.row.astype(np.int32)
col = m.col.astype(np.int32)
data = m.data.astype(np.float64)
for i in range(np.shape(data)[0]):
print row[i], col[i], data[i]
这篇关于如何将 scipy.sparse CSR 矩阵正确传递给 cython 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文