2

是否有方法或可靠的方法来确定给定矩阵是否M是通过coo_matrix()or创建的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 ...

谢谢!

4

3 回答 3

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'
于 2013-02-13T19:14:04.547 回答
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
于 2013-02-13T19:18:48.300 回答
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_matrixtype,所以isinstance工作得很好。

但是……你为什么要这样做?它不是很pythonic。

于 2013-02-13T19:15:55.687 回答