如何确定SciPy矩阵"类型"变量M

时间:2013-02-13 19:09:28

标签: python scipy sparse-matrix

是否有方法或可靠的方法来确定是否通过Mcoo_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 ...

谢谢!

3 个答案:

答案 0 :(得分:4)

假设您的矩阵是稀疏矩阵,您需要.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'

答案 1 :(得分:3)

似乎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

示例:

In [39]: spm = sps.lil_matrix((4, 5))

In [40]: spm
Out[40]: 
<4x5 sparse matrix of type '<type 'numpy.float64'>'
    with 0 stored elements in LInked List format>

In [41]: sps.isspmatrix_lil(spm)
Out[41]: True

In [42]: sps.isspmatrix_csr(spm)
Out[42]: False

答案 2 :(得分:2)

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工作正常。

但是......你为什么要这样做?它不是非常pythonic。