如何正确地将scipy.sparse CSR矩阵传递给cython函数? [英] How to properly pass a scipy.sparse CSR matrix to a cython function?

查看:69
本文介绍了如何正确地将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?

推荐答案

以下是有关如何使用属性rowcoldatacoo_matrix快速访问数据的示例.该示例的目的只是说明如何声明数据类型并创建缓冲区(还添加了通常会给您带来极大提升的编译器指令)...

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆