Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For SciPy sparse matrix, one can use todense() or toarray() to transform to NumPy matrix or array. What are the functions to do the inverse?

I searched, but got no idea what keywords should be the right hit.

like image 571
Flake Avatar asked Oct 27 '11 21:10

Flake


People also ask

How do you transform a Numpy matrix?

Applying a geometric transformation to a given matrix in Numpy requires applying the inverse of the transformation to the coordinates of the matrix, create a new matrix of indices from the coordinates and map the matrix to the new indices.


2 Answers

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]])  >>> 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 
like image 68
David Alber Avatar answered Sep 20 '22 04:09

David Alber


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

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

like image 21
cyborg Avatar answered Sep 23 '22 04:09

cyborg