首页 文章

如何将numpy.matrix或数组转换为scipy稀疏矩阵

提问于
浏览
51

对于SciPy稀疏矩阵,可以使用 todense()toarray() 转换为NumPy矩阵或数组 . 反向的功能是什么?

我搜索过,但不知道哪些关键字应该是正确的点击 .

3 回答

  • 0

    初始化稀疏矩阵时,可以将numpy数组或矩阵作为参数传递 . 例如,对于CSR矩阵,您可以执行以下操作 .

    >>> import numpy as np
    >>> from scipy import sparse
    >>> A = np.array([[1,2,0],[0,0,3],[1,0,4]])
    >>> B = np.matrix([[1,2,0],[0,0,3],[1,0,4]])
    
    >>> A
    array([[1, 2, 0],
           [0, 0, 3],
           [1, 0, 4]])
    
    >>> sA = sparse.csr_matrix(A)   # Here's the initialization of the sparse matrix.
    >>> sB = sparse.csr_matrix(B)
    
    >>> sA
    <3x3 sparse matrix of type '<type 'numpy.int32'>'
            with 5 stored elements in Compressed Sparse Row format>
    
    >>> print sA
      (0, 0)        1
      (0, 1)        2
      (1, 2)        3
      (2, 0)        1
      (2, 2)        4
    
  • 19

    scipy中有几个稀疏矩阵类 .

    bsr_matrix(arg1 [,shape,dtype,copy,blocksize])块稀疏行矩阵coo_matrix(arg1 [,shape,dtype,copy])COOrdinate格式的稀疏矩阵 . csc_matrix(arg1 [,shape,dtype,copy])压缩稀疏列矩阵csr_matrix(arg1 [,shape,dtype,copy])压缩稀疏行矩阵dia_matrix(arg1 [,shape,dtype,copy])带DIAgonal存储的稀疏矩阵dok_matrix (arg1 [,shape,dtype,copy])基于密钥的字典稀疏矩阵 . lil_matrix(arg1 [,shape,dtype,copy])基于行的链表稀疏矩阵

    他们中的任何一个都可以进行转换 .

    import numpy as np
    from scipy import sparse
    a=np.array([[1,0,1],[0,0,1]])
    b=sparse.csr_matrix(a)
    print(b)
    
    (0, 0)  1
    (0, 2)  1
    (1, 2)  1
    

    http://docs.scipy.org/doc/scipy/reference/sparse.html#usage-information .

  • 84

    至于逆,函数是 inv(A) ,但我赢了't recommend using it, since for huge matrices it is very computationally costly and unstable. Instead, you should use an approximation to the inverse, or if you want to solve Ax = b you don' t真的需要A-1 .

相关问题