如何确定变量M的SciPy矩阵“类型”

2024-05-14 06:44:55 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法或可靠的方法来确定给定的矩阵M是通过coo_matrix()还是csc_matrix()/csr_matrix()创建的?在

我怎么能写出这样的方法:

MATRIX_TYPE_CSC = 1
MATRIX_TYPE_CSR = 2
MATRIX_TYPE_COO = 3
MATRIX_TYPE_BSR = 4
...

def getMatrixType(M):
    if ...:
         return MATRIX_TYPE_COO
    else if ...:
         return MATRIX_TYPE_CSR
    return ...

谢谢!在


Tags: 方法returnifdeftype矩阵matrixcsr
3条回答

假设您的矩阵是稀疏矩阵,您需要.getformat()方法:

In [70]: s = scipy.sparse.coo_matrix([1,2,3])

In [71]: s
Out[71]: 
<1x3 sparse matrix of type '<type 'numpy.int32'>'
    with 3 stored elements in COOrdinate format>

In [72]: s.getformat()
Out[72]: 'coo'

In [73]: s = scipy.sparse.csr_matrix([1,2,3])

In [74]: s
Out[74]: 
<1x3 sparse matrix of type '<type 'numpy.int32'>'
    with 3 stored elements in Compressed Sparse Row format>

In [75]: s.getformat()
Out[75]: 'csr'

SciPy似乎提供了一个功能接口来检查稀疏矩阵类型:

In [38]: import scipy.sparse as sps

In [39]: sps.is
sps.issparse        sps.isspmatrix_coo  sps.isspmatrix_dia
sps.isspmatrix      sps.isspmatrix_csc  sps.isspmatrix_dok
sps.isspmatrix_bsr  sps.isspmatrix_csr  sps.isspmatrix_lil

示例:

^{pr2}$
def getMatrixType(M):
    if isinstance(M, matrix_coo):
         return MATRIX_TYPE_COO
    else if isinstance(M, matrix_csr):
         return MATRIX_TYPE_CSR

scipy.sparse.coo_matrix的类型是type,因此isinstance工作正常。在

但是。。。你为什么要这么做?它不是很像Python。在

相关问题 更多 >