How to transform numpy.matrix or array to scipy sparse matrix How to transform numpy.matrix or array to scipy sparse matrix numpy numpy

How to transform numpy.matrix or array to scipy sparse matrix


You can pass a numpy array or matrix as an argument when initializing a sparse matrix. For a CSR matrix, for example, you can do the following.

>>> 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]])>>> Aarray([[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


There are several sparse matrix classes in scipy.

bsr_matrix(arg1[, shape, dtype, copy, blocksize]) Block Sparse Row matrix
coo_matrix(arg1[, shape, dtype, copy]) A sparse matrix in COOrdinate format.
csc_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Column matrix
csr_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Row matrix
dia_matrix(arg1[, shape, dtype, copy]) Sparse matrix with DIAgonal storage
dok_matrix(arg1[, shape, dtype, copy]) Dictionary Of Keys based sparse matrix.
lil_matrix(arg1[, shape, dtype, copy]) Row-based linked list sparse matrix

Any of them can do the conversion.

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

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


As for the inverse, the function is inv(A), but I won'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 really need A-1.